text:
Q: Django {{ profile }} globally available in templates I'm building app with django-registration and django-profiles. Everywhere on the page I have the section displaying data of currently logged in user (like first and last name, using syntax like: {{ user.first_name }}) and it works fine. It is done with subpages templates extending the one main template with HTML structure and the section mentioned.
Now I try to add the user image (using {{ profile.image }}) to the section and there is a problem with availability of {{ profile }} template variable everywhere but on the following the pages:

*

*http://127.0.0.1:8000/profiles/myusername/ (where myusername is username of guy with profile photo),

*http://127.0.0.1:8000/profiles/edit/.

In settings.py I have:
AUTH_PROFILE_MODULE = 'intranet.UserProfile'

TEMPLATE_CONTEXT_PROCESSORS = (
   'django.core.context_processors.static',
)

Adding "django.contrib.auth.context_processors.auth", to TEMPLATE_CONTEXT_PROCESSORS does not change anything.
My UserProfile class in models.py is:
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    image = models.ImageField(upload_to=user_image_name,
        blank=True, null=True, verbose_name='User photo')

urls.py:
(r'^profiles/edit/', 'profiles.views.edit_profile', {'form_class': ProfileForm, }),
(r'^profiles/', include('profiles.urls')),

so the rest is set by default in django-profiles urls.py file.
I would like to be able to use {{ profile }} template variable everywhere (not only on the profile pages) in the templates of the application to make it possible to use it in the main template that is extended by the others.
Please let me know how can I get this. Any help will be very appreciated.
I'm using Django in version 1.3.1, django-registration in version 0.7 and django-profiles in version 0.2.

A: I think you want user.get_profile().
If you are using RequestContext and have auth in the context processors list in settings.py, then try {{user.get_profile.image}} and see if it does what you want.

A: I think the above answer by "Peter Rowell" answer must have worked for you in this specific case because of following reasons,

*

*User Object is available by "django.contrib.auth.context_processors.auth" context processor in templates.

*As you can use all methods of available Python Objects in django template context User.get_profile() method is available.

But If you need any other Object ( for example, Entry Object with id=2 or if you didn't have "django.contrib.auth.context_processors.auth" ) in your templates you can supply any objects in a dictionary to Template from your view as following
def view_needing_profile(request):
    c_user = request.user
    c_profile = c_user.get_profile()
    c_entry = Entry.objects.get(id=2)

    return render(request, 'template_using_profile_and_entry.html',
                           {'profile' : c_profile, 'entry' : c_entry } )

A: You could also put something like this in your userprofile app models.py file
# Fetches the user profile if it exists, otherwise, it creates one
User.get_or_create_profile = property(lambda u: Profile.objects.get_or_create(user=u)[0])
This ensures you will always return a profile object.


text:
Q: Partial order of a finite set is an intersection of a finite number of linear orders of this set I am trying to prove that every partial order of a finite set is an intersection of a finite number of linear orders of this set. Can this be proved using these observations:

*

*a partial order has a linear extension

*this partial order is an intersection of its linear extensions

*there is a finite number of linear extensions

Or is there a simpler proof?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to browse photos from iPhone on an iPad? Is it possible to stream/cast my photos app running on my iPhone to an iPad to have a larger screen to browse my photos? I don't want to move or copy them to the iPad, I just want to access the iPad's larger screen to review photos and delete the poor photos from a group. Is there any capability to do that much like AirPlay can handoff to a TV, can I likewise handoff to an iPad? Alternatively can I mirror my iPhone screen to an iPad?

A: I don't think there is a native option here.
You cannot use the iPad as an AirPlay target.
Maybe there is a third-party app?
I have two options for you that may or may not help, as they are not exactly what you asked for.
Option 1 (iCloud - Photos app)
Your easiest and most "Apple way" would be to use the Photos app in combination with iCloud to sync the photos between the two devices. You can edit them on the iPad and these changes get made on the iPhone as well. You can also delete them, sort them and do whatever you want with them, the changes will be synced to your Phone and vice versa.
The Photos app is smart enough not to fill up your storage and only keep some photos locally if you don't need all of them. (You will see them all, but they may take some time to download once you click on them depending on your internet speed)
Option 2 (AirDrop - copy paste & copy paste back)
Another option would be to AirDrop the photos to the iPhone, edit them there, and AirDrop them back. This would not match your request that you "don't want to move or copy them to the iPad". But it is an option that is fast and does not require iCloud.


text:
Q: Buscar responde con un renglon menos Utilizando practicamente el mismo php, excepto la parte de buscar, devuelve la lista completa, cuando agrego la parte de buscar, siempre falta uno, normalmente el 1º de la lista.
Id pac  Apellido    Nombres DNI
1   Alvarez Gomez   Alvaro  80100105
2   Bernardez Alvarez   Bernardo    80100100
3   Carles Alvarez  Carlos  80100101
4   Daniels Alvaro  Daniela 80100102
5   Estebanez Gomez Esteban 80100103
6   Alvarez Gomez   Alejo   80100104
<?php
     include('99_conn.php');

$search = '';
if (isset($_POST['search'])) {
    $search = $_POST['search'];
}
$sql020 = "SELECT 00_idpac, 00_apellido, 00_nombres, 00_dni from $t00 where 00_apellido LIKE '%".$search."%' ";
if (!$res020 = $conexion->query($sql020) )
{
    echo $conexion->error;
    exit;
}
$fila = $res020->fetch_assoc();
    if($res020->num_rows > 0){
        echo "
";
            echo "
";
                echo "Id 	";
                echo "Apellido	";
                echo "Nombres	";
                echo "DNI	";
            echo "
";
            echo "
.
";
        while($rw020 = $res020->fetch_array()){
            echo "

";
            echo "
";
                echo "" . $rw020['00_idpac'] . "	";
                echo "" . $rw020['00_apellido'] . "	";
                echo "" . $rw020['00_nombres'] . "	";
                echo "" . $rw020['00_dni'] . "	";
            echo "
";
        }
        echo "
";
}
mysqli_close($conexion);
?>

Les agradecería cualquier orientación al respecto.
2º pregunta en un caso similar de hace muchos años, pude establecer que si presionaba cualquier parte del renglon, me remitiera a otra página con el id (por ejemplo, pego un solo renglon) como en este caso se incluye el html en el php y no a la inversa como en el ejemplo que pegué, ando medio perdida.
Gracias.

<a href="Gar_4_invc_liv.php?reemplazo=<?php echo $row_RS7['reemplazo']; ?>" target="_self" class="link"><?php echo $row_RS7['desc']; ?>

A: Por qué falta siempre el primero?
$fila = $res020->fetch_assoc();

$res020 es un recurso de acceso a resultados y fetch_assoc() lee el primer registro y avanza el apuntador, después, en el while($rw020 = $res020->fetch_array()) inicias con el segundo registro y, automáticamente, avanza el apuntador para la siguiente iteración. Cuando se acaban los registros devuelve falso y termina el ciclo.
En resumen, los métodos fetch_*() leen el registro actual y avanzan el apuntador.
Cómo crear un link?
    while($rw020 = $res020->fetch_array()){
        // Modifica la ruta (pagina.php), variable (id)
        // y valor ($rw020['00_idpac'])
        // de acuerdo a tus necesidades
        $link = 'pagina.php?id=' . $rw020['00_idpac'];
        echo "

";
        echo "
";
            // Donde necesites el link:
            echo "" . $rw020['00_idpac'] . "	";
            echo "" . $rw020['00_apellido'] . "	";
            echo "" . $rw020['00_nombres'] . "	";
            echo "" . $rw020['00_dni'] . "	";
        echo "
";
    }

Con esto se agregó el link solo en la primera columna, pero no hay problema si decides agregarla también en las demás.


text:
Q: Why is nonlocal keyword being 'interrupted' by a global keyword? I'm a beginner programmer trying to learn python, and I have come across the topic of scopes. I came across the error 'no binding for nonlocal var_name found' when executing the bottom-most code. Can someone explain why is the nonlocal keyword unable to 'look past' the intermediate function and into the outer function?

#this works
globe = 5

def outer():
    globe = 10
    def intermediate():

        def inner():
            nonlocal globe
            globe = 20
            print(globe)
        inner()
        print(globe)
    intermediate()
    print(globe)

outer()

globe = 5

def outer():
    globe = 10
    def intermediate():
        global globe #but not when I do this
        globe = 15
        def inner():
            nonlocal globe #I want this globe to reference 10, the value in outer()
            globe = 20
            print(globe)
        inner()
        print(globe)
    intermediate()
    print(globe)

outer()

A: Expressions involving the nonlocal keyword will cause Python to try to find the variable in the enclosing local scopes, until it first encounters the first specified variable name.
The nonlocal globe expression will have a look if there is a variable named globe in the intermediate function. It will encounter it, in the global scope however, so it will presume it has reached the module scope and finished searching for it without finding a nonclocal one, hence the exception.
By declaring the global globe in the intermediate function you pretty much closed the path to reach any nonlocal variables with the same name in the previous scopes. You can have a look at the discussion here why was it "decided" to be implemented this way in Python.
If you want to make sure that the variable globe is or is not within the local scope of some function, you can use the dir() functions, because from Python docs:

Without arguments, return the list of names in the current local
  scope. With an argument, attempt to return a list of valid attributes
  for that object.


text:
Q: Springboot 3.0.0-M2 AuthenticationManager I wanted to create a backend using spring boot.
When I executed the application, this exception was thrown:

Field authenticationManager in projekt.controller.AuthController
required a bean of type
'org.springframework.security.authentication.AuthenticationManager'
that could not be found.

I quickly found a solution on the internet, which includes adding a WebSecurityConfigurerAdapter in which I would add this method:
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

But as I had to see, this is deprecated.
My question is how would I do the same thing without using something deprecated.

A: In your configuration class you can add this:
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
         throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}


text:
Q: Need a VBA module to loop through word files, find something, and report it in an excel spreadsheet What I'm trying to do is the following:

*

*Start module. Be presented with file picker dialog and choose a bunch of files. Files always have an 8 digit ID at the beginning of the name, but the rest of the name is variable.

*Find ALL strings of the form "T0***" in the word file and store them in an array.

*Open up an excel spreadsheet (one spreadsheet for the entire macro). Report the file ID in A1, and spit out the string of find results in B1.

*Close that word file; open the next one in the list and repeat the process. Report its results in A2 and B2 of the spreadsheet. Do this until the end of the selected list of word files.

There can be any number of T0*** strings.
So far I've got it opening up each file and then closing it. That's as far as I'm able to get. Any help is much appreciated!
'Toolfind Macro

Sub ToolFind()
Dim idarray
Dim FileSelections
Dim j As Integer
' ------------------------------------------------------

Dim MyDialog As FileDialog, GetStr(1 To 500) As String
On Error Resume Next
Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)

Set Ex0 = New Excel.Application
    Set Wb0 = Ex0.Workbooks.Add

' ---------------------------------------------------------------
' *.doc? allows processing of *.doc and *.docx files.
' ---------------------------------------------------------------
With MyDialog
    .Filters.Clear
    .Filters.Add "All WORD File ", "*.doc?", 1
    .AllowMultiSelect = True

i = 1
If .Show = -1 Then
For Each stiSelectedItem In .SelectedItems
GetStr(i) = stiSelectedItem
i = i + 1
Next

i = i - 1
End If

Application.ScreenUpdating = False

For j = 1 To i Step 1
Set Doc = Documents.Open(FileName:=GetStr(j), Visible:=True)
Set ID = Left(GetStr(j), 8)

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If

If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

'-----------------------------------------------------------------------'

Dim k As Long, SmArr()
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "T0***"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    k = k + 1
    ReDim Preserve SmArr(k)
    SmArr(k) = .Text
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With

'go into EXCEL'

    Wb0.Sheets(1).Range("A1").Value (ID)
    Wb0.Sheets(1).Range("B1").Value (SmArr)

    Application.ScreenUpdating = True

'-----------------------------------------------------------------------

ActiveDocument.Close (wdSaveChanges)
Next j
End With
End Sub


text:
Q: How do I prove that the difference between two odd functions is an odd function? Recently I've learned that the difference between two odd functions is an odd function, however, I do not understand how I could prove this. Could someone please show me how this works? Thanks in advance.

A: Let your odds be $f$ and $g$
With $h=f-g$ we have
$$h(-x) = f(-x) - g(-x) = -f(x) + g(x) = -h(x)$$
so $h$ is odd.

A: More generally check the definition of an odd function for any linear combination $\alpha f+\beta g$.

A: Let $f $ and $g $ be two odd functions, which means that
$$f (-x)=-f (x) $$ and $$g (-x)=-g (x) $$
let $$h (x)=f (x)-g (x) $$
then
$$h (-x)=f (-x)-g (-x ) $$
$$=-f (x)-(-g (x)) $$
$$=-f (x)+g (x ) $$
$$=-(f (x)-g (x)) $$
$$=-h (x ) $$
Done!

A: Hint: an odd function is a function that satisfies $f(-x) = -f(x)$. So if $f$ and $g$ are both odd functions, then what is $f(-x)-g(-x)$ in terms of $f(x)$ and $g(x)$?


text:
Q: How to do unit testing for retrofit2 callbacks? I want to do an unit test that verifies if function1() or function2() were called. I haven't work with callbacks before, can you give me any idea about how to do it?
public void sendData(HttpService service, Document userData) {
    Call<String> call = service.updateDocument(getId(), userData);

    call.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        function1(response.code());
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        function2();
    }
    });
}

A: I couldn't try, but it should work. Maybe you have to fix generic type
casting errors like mock(Call.class);.
@Test
public void should_test_on_response(){
    Call<String> onResponseCall = mock(Call.class);

    doAnswer(invocation -> {
        Response response = null;
        invocation.getArgumentAt(0, Callback.class).onResponse(onResponseCall, response);
        return null;
    }).when(onResponseCall).enqueue(any(Callback.class));

    sendData(....);

    // verify function1
}

@Test
public void should_test_on_failure(){
    Call<String> onResponseCall = mock(Call.class);

    doAnswer(invocation -> {
        Exception ex = new RuntimeException();
        invocation.getArgumentAt(0, Callback.class).onFailure(onResponseCall, ex);
        return null;
    }).when(onResponseCall).enqueue(any(Callback.class));

    sendData(....);

    // verify function2
}


text:
Q: Why does the last drag event that fires have negative x and y coordinates? JSFiddle: http://jsfiddle.net/ypYTT/1/
As you can see, I have a very simple markup, with an image that (eventually) will be dragged around changing the background position.
If you drag a bit you can see the x,y coordinates of the event fired as you would expect, but the last event fired always seems to have a negative X,Y coordinate pair, which seems to be dependent on the size of the "result" jsfiddle frame.
What are these coordinates from the last event, and why are they negative?  They are being fired from a "drag" type event, but only as the final mouseup happens (no mouseup is fired from the drag, because that wouldn't make sense).
Markup HTML
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" />

CSS
img {
    background: linear-gradient( to left top, blue, red);
    width:200px;
    height:200px;
    margin:20px;
}

JavaScript
$('img').on('dragstart drag dragstop', function(e){
    console.log(e.originalEvent);
});

A: I found an error in your code. 'dragstop' should be 'dragend'.
Please see this fiddle: http://jsfiddle.net/ypYTT/3/
I can still see the negative values appears, but they are not the last value received by the console, so it may be fixing your problem.
The code is now as follows:
$('img').on('dragstart drag dragend', function(e){
console.log(e.originalEvent);
});
$('img').on('mouseup', function(e){
    e.stopPropagation();
    e.stopImmediatePropagation();
});


text:
Q: AWS EMR - Saving Dataframe into hive external table on S3 - getting memory leak error Hello i am writing spark using python and tring to write the dataframe into table and table is hive external and stored on AWS S3
below is the command :
   sqlContext.sql(selectQuery).write.mode("overwrite").format(trgFormat).option("compression", trgCompression).save(trgDataFileBase)
Below is the error
ERROR ResourceLeakDetector: LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dio.netty.leakDetection.level=advanced' or call ResourceLeakDetector.setLevel() See http://netty.io/wiki/reference-counted-objects.html for more information.
spark sumit:
spark-submit --master yarn --queue default --deploy-mode client --num-executors 10 --executor-memory 12g --executor-cores 2 --conf spark.debug.maxToStringFields=100 --conf spark.yarn.executor.memoryOverhead=2048

A: Create a temp table, say trgDataFileBasetmp, then using the same definition create the table on s3. You will need all the parameters in the definition like SERDEPROPERTIES, TBLPROPERTIES. Here the difference I have is saveAsTable:
sqlContext.sql(selectQuery).write.mode("overwrite").format(trgFormat).option("compression", trgCompression).saveAsTable(trgDataFileBase)

If this does not work then you can start with:
sqlContext.sql(selectQuery).write.mode("overwrite").saveAsTable(trgDataFileBase)


text:
Q: Parsing sql query PHP I want to parse a SQL query into an array. I could not figure out the code.
Example:
$sql_query = "SELECT id, login, pass FROM users WHERE id=3, login=faforty ORDER DESC LIMIT 3"';

and this sql query should be as follows:
$data = array();
$data['select'] = array('id', 'login', 'pass');
$data['from'] = array('id' => 3, 'login' => 'faforty');
$data['order'] = 'desc';
$data['limit'] = 3;

Query may be different.

A: Use an SQL parser. http://code.google.com/p/php-sql-parser/
Copy paste from this example:
<?php
  require_once('php-sql-parser.php');
  $parser=new PHPSQLParser('SELECT a FROM some_table an_alias WHERE d > 5;', true);

  print_r($parser->parsed);

Example output:
Array
(
    [SELECT] => Array
        (
            [0] => Array
                (
                    [expr_type] => colref
                    [alias] =>
                    [base_expr] => a
                    [sub_tree] =>
                    [position] => 8
                )

        )

    [FROM] => Array
        (
            [0] => Array
                (
                    [expr_type] => table
                    [table] => some_table
                    [alias] => Array
                        (
                            [as] =>
                            [name] => an_alias
                            [base_expr] => an_alias
                            [position] => 29
                        )

                    [join_type] => JOIN
                    [ref_type] =>
                    [ref_clause] =>
                    [base_expr] => some_table an_alias
                    [sub_tree] =>
                    [position] => 18
                )

        )

    [WHERE] => Array
        (
            [0] => Array
                (
                    [expr_type] => colref
                    [base_expr] => d
                    [sub_tree] =>
                    [position] => 45
                )

            [1] => Array
                (
                    [expr_type] => operator
                    [base_expr] => >
                    [sub_tree] =>
                    [position] => 47
                )

            [2] => Array
                (
                    [expr_type] => const
                    [base_expr] => 5
                    [sub_tree] =>
                    [position] => 49
                )

        )

)


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'getStateForAction') in React Native I was coding in React Native (code below)...
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import NewsListScreen from '../screens/NewsListScreen';
import NewsItemScreen from '../screens/NewsItemScreen';
import FavoritesScreen from '../screens/FavoritesScreen';
import { createAppContainer } from 'react-navigation';

const Stack = createStackNavigator();

function StackNavigator() {
    return (
      <Stack.Navigator>
        <Stack.Screen name="News" component={NewsListScreen} />
        <Stack.Screen name="Details" component={NewsItemScreen} />
      </Stack.Navigator>
    );
  }

const Tab = createBottomTabNavigator();

function BottomTabNavigator() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={StackNavigator} />
      <Tab.Screen name="Favorites" component={FavoritesScreen} />
    </Tab.Navigator>
  );
}

const AppContainer = createAppContainer(BottomTabNavigator);

export default AppContainer

...when I encountered an error!

Does anyone know a solution? Thanks in advance!
Tried many solutions and they didn't work!


text:
Q: Connecting to Redis on Vagrant machine I'm trying to resolve this error when connecting from a Rails server to a Redis server, both running in Vagrant VM:
Redis::CannotConnectError: Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)

I can verify the Redis server is running, I think, with the following:
ps aux | grep redis
redis      839  0.1  0.1  35140  1840 ?        Ssl  00:21   0:00 /usr/local/bin/redis-server *:6379
vagrant   1220  0.0  0.0  11676   952 pts/0    R+   00:22   0:00 grep --color=auto redis

sudo netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      839/redis-server *:
tcp        0      0 0.0.0.0:57102           0.0.0.0:*               LISTEN      778/rpc.statd
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      507/rpcbind
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      725/sshd
tcp6       0      0 :::6379                 :::*                    LISTEN      839/redis-server *:
tcp6       0      0 :::111                  :::*                    LISTEN      507/rpcbind
tcp6       0      0 :::22                   :::*                    LISTEN      725/sshd
tcp6       0      0 :::49667                :::*                    LISTEN      778/rpc.statd

I have this in my redis.conf:
# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379

# If you want you can bind a single interface, if the bind option is not
# specified all the interfaces will listen for incoming connections.
#
bind 127.0.0.1

and Vagrantfile:
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "ubuntu-12.04-amd64"

  # THE URL FROM WHERE THE 'CONFIG.VM.BOX' BOX WILL BE FETCHED IF IT
  # DOESN'T ALREADY EXIST ON THE USER'S SYSTEM.
  config.vm.box_url = "http://files.vagrantup.com/precise64.box"

  config.vm.network "forwarded_port", guest: 6379, host: 6379, auto_correct: true

  config.vm.provider "virtualbox" do |v|
    v.customize ["modifyvm", :id, "--memory", "1024"]
    v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
  end

  config.vm.provision "shell", path: "init.sh"
end

I tried following the canonical entry but am not making any headway.  It might be something obvious I'm overlooking.  Can someone point me in the right direction as to what else I can try?
EDIT: Full error message:
$redis = Redis.new(:host => '127.0.0.1', :port => 6379)
=> #<Redis client v3.2.2 for redis://127.0.0.1:6379/0>
$redis.set('a', 'b')
Redis::CannotConnectError: Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)

EDIT: commented out the bind 127.0.0.1 and was able to ping from the redis box but still no luck from Rails:
redis-cli -h 127.0.0.1 ping
PONG

A: Figured it out, I needed to use the IP address of the adapter for my VM (VirtualBox) to get it to work on my Windows machine.  This worked:
$redis = Redis.new(:host => '192.168.56.1', :port => 6379)
=> #<Redis client v3.2.2 for redis://192.168.56.1:6379/0>
$redis.set('a', 'b')
=> "OK"
$redis.get('a')
=> "b"


text:
Q: Can we deploy a Chrome extension through local http server through GPO settings? I have a Windows system that is a part of a domain. I've imported the domain GPO chrome .admx file and then created the Chrome GPO policy for 'ExtensionInstallForceList' property by using http://dev.chromium.org/administrators/policy-list-3#ExtensionInstallForcelist as the reference.
Here I've specified the ID for the extension that gets generated when it was loaded in unpacked format. Also, I used the local HTTP server as the place to download. A pseudo value of the property that I used:
eelojgpfkmaaabbbccneneemcahoehjo;http://<some.ip.address>/crx

See attached snapshot for reference:

I've created an IIS server and enabled Directory browsing and then chose the root path of the server to point to the parent folder of 'crx'. I am able to access an xml file present inside crx using this above URL.
However my extension is still not installed. But I also have the extension in the Chrome Webstore and if I use the Webstore URL, the extension is deployed successfully.
As per comments from Xan below and further trials that I performed, I'll add the snapshots for each of the following:
1.
2. Tried FQDN instead of IP address but still couldn't install
3. Changed the GPO to point to the folder that contains the crx file instead of the update URL. Still not installed
4. I had already packed the extension using the link you mentioned. I dragged-n-dropped this packed crx file and found out the new ID. I then used this ID in my updates.xml file as well as in my Chrome GPO policies. However, extension is still not installed on the domain endpoint.

*

*Can someone please help me point out exactly what is missing?

*Is there some issue in the way I configured my IIS server? or

*Could it be because I used an IP address instead of an FQDN? or

*Is it because of some other possible configuration error?

A: You don't specify this well in your question, but I spot a few problems/omissions:
CRXs and IDs

Here I've specified the ID for the extension that gets generated when it was loaded in unpacked format.

This will not work; that ID is just a temporary one based on the hash of the path to the extension.
Chrome needs to generate a keypair and sign the CRX for it to be useable in enterprise deployment.

*

*You need to package it as CRX through chrome://extensions's Developer Mode.

*It will generate a private key .pem that you need to save for any future updates (otherwise the ID will change again and you won't be able to use it as an update).

*Then, install the CRX on the same machine by dragging it onto chrome://extensions to get its final, signed ID.
As an alternative to this step, you can use OpenSSL to generate the key from the .pem obtained from the previous steps.
What are you actually hosting?
The URL that you point to in the GPO policy is the Update URL, not the actual CRX file!
See this documentation on Update manifests. Here's an example:
<?xml version='1.0' encoding='UTF-8'?>
<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>
  <app appid='eelojgpfkmaaabbbccneneemcahoehjo'>
    <updatecheck codebase='http://<some.ip.address>/actual_extension.crx' version='1.0' />
  </app>
</gupdate>

Modify the updatecheck.version as needed when updating. Don't touch any of the gupdate properties.
How are you serving files?
There may be a minor issue with content-types your server is sending.
I could not find bulletproof information on what should be the content type for the files, but a good guess is:

*

*application/xml for the update manifest

*application/octet-stream for the CRX file

Still not working?
Perhaps you're on to something with IP vs FDQN. It should be possible for you to create a local DNS entry for the update server - try and see if it helps.

A: Here's an Alternative Extension Distribution Options documentation for the possible ways on how to distribute Chrome extensions.

All Chrome extensions must be distributed either directly from the Chrome Web Store, using inline installation, or using the mechanisms described below. Failure to comply with one of these distribution methods constitutes a violation of the Chrome extension policy and may result in the extension and/or the software distributing it to be flagged as unwanted software.

You may also check this support page if you want to force install Chrome extensions on corporate-managed Windows devices via machine and OS-user policies.


text:
Q: Phonegap iOS getjson not working - but working in desktop I wrote this JSON but it doesnt execute. maybe somthing wrong with my syntax?
because it does execute on a dekstop computer, but when i run with with an iphone simulator it doesnt. :/
$.getJSON('http://***.com/**/***.php?uid='+uid+'&hash='+hash, function(data) {

thanks

A: Check your config.xml access tag. From: http://cordova.apache.org/docs/en/3.3.0/config_ref_index.md.html#The%20config.xml%20File
 elements define the set of external domains the app is allowed to communicate with. The default value shown above allows it to access any server. See the Domain Whitelist Guide for details.
And this is the whitelist guide: http://cordova.apache.org/docs/en/3.3.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide


text:
Q: Hibernate @Id @GeneratedValue annotation doesn't recognise increment ID generated by DB2 Database Inserting a second record using Hibernate 3 into DB2 v9.x where a column has a Unique primary key column Id generated by DB2 doesn't work with persisting my Hibernate entity.
Inserting the first record works fine, however unless I manually increment and set the value using the setter no more records can be persisted. I have tried commenting out @GeneratedValue....am I using this correctly? I do not want Hibernate to auto increment the Id column, I want it to use the incremented ID generated by DB2 itself to insert the next row. Thanks:)
This is my code:
private short APLSEQNUM;

@javax.persistence.Column(name = "MRT_APLSEQNUM")
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public short getAPLSEQNUM() {
    return APLSEQNUM;
}

The contrainst added in DB2 create table script to generate the Id:
"MRT_APLSEQNUM" SMALLINT NOT NULL GENERATED BY DEFAULT AS IDENTITY (  START WITH +1
INCREMENT BY +1
MINVALUE +1
MAXVALUE +32767
NO CYCLE
CACHE 20
NO ORDER )

This is the exception:

Hibernate: insert into RPS.TMRT (MRT_APRNUM, MRT_CHKLOC, MRT_DPTCDE, MRT_FUNCDE, MRT_MDCNUM, MRT_MDCRSLCDE, MRT_MDCRSLDTE, MRT_OCCCDE, MRT_QIDNO, MRT_REGDTE, MRT_REMARK, MRT_SECCDE, MRT_SMP, MRT_USRID, MRT_VISNUM, MRT_APLYER, MRT_APLSEQNUM, MRT_ACMPNUM) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  15-Mar-2011 17:37:44 org.hibernate.util.JDBCExceptionReporter logExceptions
  WARNING: SQL Error: -803, SQLState: 23505
  15-Mar-2011 17:37:44 org.hibernate.util.JDBCExceptionReporter logExceptions
  SEVERE: DB2 SQL error: SQLCODE: -803, SQLSTATE: 23505, SQLERRMC: 1;RPS.TMRT
  15-Mar-2011 17:37:44 org.hibernate.event.def.AbstractFlushingEventListener performExecutions
  SEVERE: Could not synchronize database state with session
  org.hibernate.exception.ConstraintViolationException: could not insert: [qa.gov.moi.rps.db.entity.Medical_MRT]
      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2272)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2665)
      at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:60)
      at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
      at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
      at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
      at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
      at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
      at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
      at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
      at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
      at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
      at qa.gov.moi.rps.db.helper.MedicalHelper.create(MedicalHelper.java:74)
      at qa.gov.moi.rps.db.helper.MedicalHelper.main(MedicalHelper.java:285)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
  Caused by: com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -803, SQLSTATE: 23505, SQLERRMC: 1;RPS.TMRT
      at com.ibm.db2.jcc.c.fg.d(fg.java:1340)
      at com.ibm.db2.jcc.b.gb.k(gb.java:351)
      at com.ibm.db2.jcc.b.gb.a(gb.java:60)
      at com.ibm.db2.jcc.b.w.a(w.java:52)
      at com.ibm.db2.jcc.b.wb.c(wb.java:213)
      at com.ibm.db2.jcc.c.gg.ab(gg.java:1779)
      at com.ibm.db2.jcc.c.gg.d(gg.java:2324)
      at com.ibm.db2.jcc.c.gg.W(gg.java:457)
      at com.ibm.db2.jcc.c.gg.executeUpdate(gg.java:440)
      at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2252)
      ... 18 more
  javax.persistence.RollbackException: Error while commiting the transaction
      at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:71)
      at qa.gov.moi.rps.db.helper.MedicalHelper.create(MedicalHelper.java:74)
      at qa.gov.moi.rps.db.helper.MedicalHelper.main(MedicalHelper.java:285)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
  Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [qa.gov.moi.rps.db.entity.Medical_MRT]
      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2272)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2665)
      at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:60)
      at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
      at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
      at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
      at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
      at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
      at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
      at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
      at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
      at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
      ... 7 more
  Caused by: com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -803, SQLSTATE: 23505, SQLERRMC: 1;RPS.TMRT
      at com.ibm.db2.jcc.c.fg.d(fg.java:1340)
      at com.ibm.db2.jcc.b.gb.k(gb.java:351)
      at com.ibm.db2.jcc.b.gb.a(gb.java:60)
      at com.ibm.db2.jcc.b.w.a(w.java:52)
      at com.ibm.db2.jcc.b.wb.c(wb.java:213)
      at com.ibm.db2.jcc.c.gg.ab(gg.java:1779)
      at com.ibm.db2.jcc.c.gg.d(gg.java:2324)
      at com.ibm.db2.jcc.c.gg.W(gg.java:457)
      at com.ibm.db2.jcc.c.gg.executeUpdate(gg.java:440)
      at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2252)
      ... 18 more

A: Use  @GeneratedValue(strategy = GenerationType.IDENTITY)

A: here's what we did :
we created a sequence in DB2 :

in the hibernate mapping file :
<id name="idClass" column="IDROW" >
    <generator class="sequence">
      <param name="sequence">SIDFINANCEMENT</param>
    </generator>
</id>

Works in a clustered environment where many instances need to get a sequence and the sequence generated is unique.


text:
Q: How to Explain the the following situation? I have thought a simple thing:
consider a system of a planet and its natural satellite revolving around it in a perfectly circular orbit(assumed) and this is happening in an isolated space in some part of universe. Now something just happened at infinity that made the planet and its satellite to lose electrons and they both became a positively charged (up to that much, so that they could repel and also take the two bodies spherical, approximately).
My question is will that satellite still be in the same orbit of that planet?
Well, that's pretty simple question, isn't it?
But i was reading a book Halliday resnick krane. There on page 638, para.6 under "Potential Energy of a System of Charges",  it is written (and also we all know this)

if the external agent does positive work in assembling the charges from the infinite separation(opposing the repulsive forces in the process), the total energy calculated using Eq. 28-8 will be positive. The External agent has in effect stored the energy in the system. If the charged are released from their position, they will tend to fly apart, the potential energy will decrease and hence their kinetic energy will increase.

now let us consider the above situation again, the two bodies before becoming a charge particles were held by the gravitational force($F_g$) and the satellite (S) was revolving around the planet (P), so when the bodies S and P become charged, the body S wasn't brought from infinity so no external force was there which could have stored energy in the system in the form of potential energy and further more the body S is revolving in a perfectly circular orbit because of $F_g$ and the motion of S is always perpendicular to the direction of the field of the body P hence S is also not doing any work i.e. it is not storing and energy in the system in the form of Potential energy. So if no potential energy was stored in the system in the form of the potential energy then how could the body S gain kinetic energy and go away from the body P?

A: The orbit will change.
To be concrete, lets say that the satellite and planet are illuminated by ultraviolet light for a short period of time, so that some electrons are photoemitted from their surfaces. Make the bodies conducting so that the surface charge spreads out evenly.
The repulsion between the charged bodies acts in the opposite direction of the gravitational force, so the force of attraction between satellite and planet is reduced.  But since the satellite was originally held in a circular orbit by gravity, it can no longer be in a circular orbit and will have an elliptical orbit instead.  If the orbit is elliptical, that means that sometimes the satellite is closer to the planet and other times it is farther away: There is radial motion.
It requires energy (work) to make the radial motion.  Where did this energy come from? It came when you extracted the electrons from the bodies. If you remove an electron from the body, then the body becomes positively charged and you have to do work to bring the electron far from the body. As the body charges up, removing electrons becomes harder and harder requiring more work.  This is the energy that ultimately does work on the satellite and changes its orbit.


text:
Q: Conversion failed when converting the varchar value '2 year -2 month 21 day' to data type int I am trying to find out for how long employees have been working for the company and I should also find out if any of the employees have a resignation date.
But I don't have data for this right now, therefore value of this column in my database is Null. But i consider in my sql when it's happened take Resignation Date instead current time But for now take work start date and current time.  my theory is if the column resignation date is null, take "Current Date - Work start date", else
should it take resignation date - Work start date.
I wrote a SQL query for this theory and it's working fine but when I tried return for ex year month day for  how long employees working I got a problem which is:
a ) I struggled with this error for hours and I also tried convert those lines, I thought its should be converted but it's not working well so, when I run my main query, I get this error:
> Msg 245, Level 16, State 1, Line 1
> Conversion failed when converting the varchar value '2 year -2 month 21 day' to data type int.

My main query looks like this:
**--- sql for how long employees work with year month day ----**
    CASE
        WHEN Users.ResignationDate IS NOT NULL
           THEN DATEDIFF(YEAR, WorkStartDate, ResignationDate)
           ELSE CAST(DATEDIFF(yy, WorkStartDate, GETDATE()) AS varchar(4)) + ' year ' +
                CAST(DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()) AS varchar(2)) + ' month ' +
                CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()), DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate)), GETDATE()) AS varchar(2)) +' day'  END as Ancinitet,
        Paychecks.DepartmentName AS Afdelinger
   FROM dbo.Paychecks INNER JOIN  dbo.Users ON Users.Id=Paychecks.UserId
WHERE Users.CustomerId=214 order by Users.FirstName;

A: A case expression returns a single value -- and a single type.  Yours is returning two different types, and SQL Server decides that the appropriate return type is the first one, an integer.
Just cast to a string:
(CASE WHEN Users.ResignationDate IS NOT NULL
      THEN CAST(DATEDIFF(YEAR, WorkStartDate, ResignationDate) as VARCHAR(255))
      ELSE (CAST(DATEDIFF(year, WorkStartDate, GETDATE()) AS varchar(4)) +' year ' +
            CAST(DATEDIFF(month, DATEADD(year, DATEDIFF(year, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()) AS varchar(2)) +' month ' +
            CAST(DATEDIFF(day, DATEADD(month, DATEDIFF(month, DATEADD(year, DATEDIFF(year, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()), DATEADD(year, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate)), GETDATE()) AS varchar(2)) +' day'
          )
END) as Ancinitet,

I suspect there is a better way to do what you want.  If that is of interest, ask another question with sample data and desired results.

A: What's wrong with this?
datediff(year, workStartDate, isNull(resignationDate, getDate()))

A: You'd be better off using weeks instead of months, since a week always contains 7 days.  You could also use a 30 day month which will generally get you close but your days may be off by a couple.
DECLARE @StartDate DATETIME = '20151115',
        @EndDate DATETIME = GETDATE();

SELECT  YearWeekDay = CONCAT(DATEDIFF(DAY, @StartDate, @EndDate) / 365, ' year ', DATEDIFF(DAY, @StartDate, @EndDate) % 365 / 7, ' week ',
                              DATEDIFF(DAY, @StartDate, @EndDate) % 365 % 7, ' day'
                            ),
        YearMonthDay = CONCAT(DATEDIFF(DAY, @StartDate, @EndDate) / 365, ' year ', DATEDIFF(DAY, @StartDate, @EndDate) % 365 / 30, ' month ',
                               DATEDIFF(DAY, @StartDate, @EndDate) % 365 % 30, ' day '
                             ),
        YWDHMS = CONCAT( DATEDIFF(SECOND, @StartDate, @EndDate) / 86400 / 365, 'y ', DATEDIFF(SECOND, @StartDate, @EndDate) / 86400 % 365 / 7, 'w ',
                         DATEDIFF(SECOND, @StartDate, @EndDate) / 86400 % 365 % 7, 'd ', DATEDIFF(SECOND, @StartDate, @EndDate) % 86400 / 3600, 'h ',
                         DATEDIFF(SECOND, @StartDate, @EndDate) % 3600 / 60, 'm ', DATEDIFF(SECOND, @StartDate, @EndDate) % 60, 's '
                       );

Output:
StartDate   EndDate                 YearWeekDay             YearMonthDay            YWDHMS
2015-11-15  2017-02-22 15:11:34.123 1 year 14 week 2 day    1 year 3 month 10 day   1y 14w 2d 15h 11m 34s


text:
Q: How to use MFC with ATL I'm trying to write a COM EXE using ATL. I also have a MFC application.
Both these applications would be run in local machines. Therefore, I don't
need to run these two processes (COM EXE and MFC) separately.
Can I create a single application (process) by combining these two applications ?
Is there any possibility that I can embed my MFC code in ATL code, or
is there a way to initialize the COM EXE within my MFC code ?
Appreciate your help and concerns .
Thank you

A: You can make your code more reusable by moving your ATL objects to a new ATL COM DLL project and make your two exe projects clients of your ATL objects.
If you add an ATL object to a MFC project without ATL support, Visual C++ will prompt you to add ATL support. You can then cancel the wizard without really adding an ATL object, but the ATL support will remain,


text:
Q: Automatic White Balancing with RGB color space I am trying to implement white balance in python to do image processing.
I found the following implementation from Automatic White Balancing with Grayworld assumption
def white_balance_loops(img):
    result = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    print(result)
    avg_a = np.average(result[:, :, 1])
    avg_b = np.average(result[:, :, 2])
    print(avg_a, avg_b)
    result[:, :, 1] = result[:, :, 1] - ((avg_a - 128) * (result[:, :, 0] / 255.0) * 1.1)
    result[:, :, 2] = result[:, :, 2] - ((avg_b - 128) * (result[:, :, 0] / 255.0) * 1.1)
    result = cv2.cvtColor(result, cv2.COLOR_LAB2BGR)
    return result

However, I could not understand the way it is calculated, particularly with LAB color space. Is it possible to convert the algorithm in RGB color space? Any help is appreciated.


text:
Q: Swapping words in method for Word Chain I have a list of words that all differ by one letter. I'm trying to make a word chain so that if the user enters one word, then the next word will differ by one character at random from that and then the next word will differ by one character of the last character.
Ex: test to nest to newt to nett to yett to yeti.
So I created the amount of words that differ by one letter to test.  I created a swap method:
public static void swap( String[] str, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;

}
My professor recommended to swap the word to the last position in the list so that way you don't use it again, and then you look for a similar character position in the list that differs by one letter and then when you find that word, you keep swapping it to the end until you have no words left, or no similar positions left.
So my question is am I on the right track with swapping my words?

A: If your only question is am I on the right track with swapping my words?, then yes, you are doing so correctly.


text: Q: After updating the module, the payment method name has not been changed but error "The requested Payment Method is not available" After updating the payment module and making new order, I see in DB that payment method name is same as old module but old orders can not be opened. So updating sales_flat_order_payment did not help. What else I need to check? Thanks


text:
Q: How can I protect a directory using PHP? Notice, this is a remote server, I don't have access to it, only to the FTP. I want to do this using purely PHP, not .htaccess. Is there a way similar to .net, where you put the web.config file and you set who can access it and their password?

A: I'd say the equivalent of that kind of functionnality from web.config on Apache is with .htaccess files : PHP is used to generate pages, but if you are trying to work at the directory level, the check has to come before PHP is even called.
In your PHP scripts, you can access the data of HTTP Authentication ; see $_SERVER, especially PHP_AUTH_USER and PHP_AUTH_PW ; but the protection will be at the file's level, and not directory -- and, obviously, it will be enforced only for PHP files (not images in a subdirectory, for instance).
For more informations, you can have a look at, for instance : HTTP Basic and Digest authentication with PHP
The right way to do this for an entire directory is definitly with .htpasswd / .htaccess files (or directly in the Apache's configuration file).

A: Why using PHP?  .htaccess files were designed for this purpose.  If you're trying to do something like store user logons in a database, look at the something like Mod_auth_mysql
What you can do is place the files outside of your webroot and write a php script to serve those files after passing your authentication logic.

A: As far as I'm aware there is no way to do this purely in PHP.
If you can use .htaccess but cannot upload it for whatever reason, then I would suggest writing the htaccess via PHP.

A: Directory protection is always the work of the webserver. Whatever you do in your PHP script, it's the webserver's responsibility to execute the script in the first place. If you try to access another file in the directory, the webserver will hand it to the user without even looking at your script. If the user requests a directory listing, it's the webserver that's handing it to the user.
You will have to configure the webserver correctly, most likely using .htaccess files, if you want to protect real, "physical" directories.


text:
Q: Gitlab - Build docker images from within docker shared runner Trying to build a docker image from withing shared runner, below is the CI configuration
image: osrg/dind-ubuntu-vivid

services:
  - docker:dind

stages:
    - build
    - test
    - release

variables:
  CONTAINER_TEST_IMAGE: registry.gitlab.com/somasundaramsekar/ci-test:$CI_BUILD_REF_NAME
  CONTAINER_RELEASE_IMAGE: registry.gitlab.com/somasundaramsekar/ci-test:latest

before_script:
  - apt-get update -y >/dev/null 2>&1
  - apt-get install -y --fix-missing software-properties-common python-software-properties >/dev/null 2>&1
  - apt-get update -y >/dev/null 2>&1
  - apt-get install -y openjdk-8-jdk >/dev/null 2>&1
  - apt-get install apt-transport-https -y >/dev/null 2>&1
  - wget www.scala-lang.org/files/archive/scala-2.11.7.deb >/dev/null 2>&1
  - dpkg -i scala-2.11.7.deb >/dev/null 2>&1
  - scala -version
  - echo "deb https://dl.bintray.com/sbt/debian /" | tee -a /etc/apt/sources.list.d/sbt.list
  - apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823 >/dev/null 2>&1
  - apt-get update >/dev/null 2>&1
  - apt-get install -y sbt >/dev/null 2>&1
  - wget https://downloads.typesafe.com/typesafe-activator/1.3.10/typesafe-activator-1.3.10.zip >/dev/null 2>&1
  - apt-get install -y unzip >/dev/null 2>&1
  - unzip typesafe-activator-1.3.10.zip >/dev/null 2>&1
  - export ACTIVATOR_HOME="$(pwd)/activator-dist-1.3.10"
  - export PATH=$PATH:$ACTIVATOR_HOME/bin
  - service docker start
  - docker ps
  - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN registry.gitlab.com

build:
  stage: build
  script:
    - sbt clean compile

test:
  stage: test
  script:
    - sbt clean coverage test coverageReport

release:
    stage: release
    script:
     - activator dist
     - docker build --pull -t $CONTAINER_TEST_IMAGE .
     - docker push $CONTAINER_TEST_IMAGE

But when the job runs it fails like below

 * Starting Docker: docker
   ...done.
$ docker ps
Get http:///var/run/docker.sock/v1.19/containers/json: dial unix /var/run/docker.sock: no such file or directory. Are you trying to

connect to a TLS-enabled daemon without TLS?
      ERROR: Build failed: exit code 1

Tried with the same Base docker image in my local, to docker ps, which works after service docker start
I would like to package the application and create docker image within the same job, appreciate any help

A: Use different image for each stage, in your case use osrg/dind-ubuntu-vivid for build and test, and docker image in release stage with dind service. Check this thread.


text:
Q: How do I map variables to lists and then join the lists together? Hey guys I have three lists:
a={{1, 2}, {1, 3}, {1, 2}, {1, 2}, {1, 2}}

b={{{2, 3}, {1, 3}}, {{2, 3}, {1, 3}}, {{2, 3}, {1, 3}}, {{2, 3}, {1,3}}, {{2, 3}, {1, 2, 3}}}

c={{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0, 0}}

What I'm trying to figure out is how do I do the following:  I want to add a "T" into the front of every number in all the sublists for list "a". Then I want to do something similar with list "b" but this time I want to add an "A" into the front of every number in all the sublists giving me the following lists:
aa={{T1, T2}, {T1, T3}, {T1, T2}, {T1, T2}, {T1, T2}}

bb={{{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A2, A3}}}

Lastly what I want to do is I want to match certain elements in list "aa" to list "bb" and then insert those matched elements into list "c" giving me a new list "cc".  For example, in the first sublist of list "aa" there's a {T1,T2}  that corresponds to the first sublist of {{A2,A3},{A1,A3}}.....} in list "bb".  What I want to do is then take T1 and pair it to the first sublist of the list given for "bb".  So T1 would be distributed to A2 and A3giving me elements of {T1,A2},{T1,A3}.  Then taking T2 I want to distribute it to A1 and A3 to give me elements {T2,A1}, {T2,A3}.
That would overall give me elements {{T1,A2},{T1,A3},{T2,A1},{T2,A3}}.  I then want to take those elements and insert them into list "c".  List "c" is just comprised of 0's which are just placeholders.  So in the first sublist of list "c" we have {{0,0,0,0,0}....}.  I want to insert the elements above into list "c" to give me a new list "cc"
cc={{{T1,A2},{T1,A3},{T2,A1},{T2,A3}}...}}

I'm trying to find a way to do this process for all the sublists in "aa" and "bb" and input them all into "c" to give me a new list "cc".
In lists "aa" and "bb" each sublist correspond to one another.  So in list "aa", the first sublist of {T1,T2} relates to the first sublist in list "bb" of {{{A2, A3}, {A1, A3}}....  The second sublist correspond together, e.g. in "aa" the second sublist {T1, T3} corresponds to the second sublist of {...{{A2, A3}, {A1, A3}}...} in list "bb",  So on and so forth.

A: aa = Map[Symbol["T" <> ToString[#]] &, a, {-1}]

{{T1, T2}, {T1, T3}, {T1, T2}, {T1, T2}, {T1, T2}}

bb = Map[Symbol["A" <> ToString[#]] &, b, {-1}]

{{{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A3}},
   {{A2, A3}, {A1, A3}}, {{A2, A3}, {A1, A2, A3}}}

ClearAll[combine]
combine = MapThread[Join @@ (Thread /@ Thread@{##}) &, {##}] &;

cc  = combine[aa, bb]

{{{T1, A2}, {T1, A3}, {T2, A1}, {T2, A3}},
   {{T1, A2}, {T1, A3}, {T3, A1}, {T3, A3}},
   {{T1, A2}, {T1, A3}, {T2, A1}, {T2, A3}},
   {{T1, A2}, {T1, A3}, {T2, A1}, {T2, A3}},
   {{T1, A2}, {T1, A3}, {T2, A1}, {T2, A2}, {T2, A3}}}

Alternatively:
ClearAll[combine2, combine3]

combine2 = MapThread[Apply[Join]@*Map[Thread]@*Thread@*List];

combine3 = Map[Apply[Join] @* Map[Thread]] @* Map[Transpose] @* Transpose @* List;

cc == combine2[{aa, bb}] ==combine3[aa, bb]

True

Notes:
To get some intuition on how combine works, consider first an arbitrary function foo in the first argument of MapThread:
MapThread[foo, {aa, bb}] // Column

If we try Thread[{##}]& in place of foo:
MapThread[Thread[{##}] &, {aa, bb}] // Column

Squinting at each sublist suggest one more round of Thread will get us closer:
MapThread[Thread /@ Thread[{##}] &, {aa, bb}] // Column

We are almost there. Need to get rid unwanted braces which is what Join does:
MapThread[Join @@ (Thread /@ Thread[{##}]) &, {aa, bb}] // Column

You might enjoy the flash animations in the following link of all the functions used above:
Animated illustrations of how MapThread, Thread, Apply, etc work
MapThread:

Thread:

Map:

Apply:

Join:


text:
Q: Some fields Undefined when display results from REST query I am learning to build custom SP solution with JS and HTML following the Apress book of same name.
I use the following script (in Code Snippet of a SEWP):

to display results of the Tills Custom List (in the div with ID 'tills' in a CEWP).
Some of the fields show data as expected (Number, POS, IP, Version) but Till and Type show as 'undefined. They like most other fields are defined as 'Single Line of Text' with the default values.
I tried adding a $select and $expand to the query string, but Fiddler gives Error 400 with message

The field or property 'Till' does not exist.

Any suggestions please?

A: Only simple values (numbers, strings, dates) are brought back by default. If you want the other values you need to explicitly request them by using $select. You will most likely need to also use $expand to get object or collection property values.
You should get used to using a tool like Fiddler to see what the response coming back from SharePoint looks like. Anything with __deferred underneath the property name means the value was not returned by default.

A: The answer to my problem turned out to be the List itself. Recreating the list shows all fields. (I am not clear on what was wrong with the way it was first created.)
Fiddler is a great tool to use, so thanks Rob for the tip.

A: One thing I want to add if you face again this kind of problem, try to use alphanumeric name of the fields as sometimes it fails to recognize these user created column names.
For shortcut just press F12 and select the column which is not find by the compiler.
You would get something like this,
displayname="JobTitle" fieldtype="Text" SortField=**_x006e_xc2**;><a class="ms-headerSortTitleLink" id="diidSort0_x006e_xc2"

Copy the text and use the same in your query.


text:
Q: Storing matrix after every iteration I have following code.
for(i in 1:100)
{
   for(j in 1:100)
    R[i,j]=gcm(i,j)
}

gcm() is some function which returns a number based on the values of i and j and so, R has all values. But this calculation takes a lot of time. My machine's power was interrupted several times due to which I had to start over. Can somebody please help, how can I save R somewhere after every iteration, so as to be safe? Any help is highly appreciated.

A: You can use the saveRDS() function to save the result of each calculation in a file.
To understand the difference between save and saveRDS, here is a link I found useful. http://www.fromthebottomoftheheap.net/2012/04/01/saving-and-loading-r-objects/

A: If you want to save the R-workspace have a look at ?save or ?save.image (use the first to save a subset of your objects, the second one to save your workspace in toto).
Your edited code should look like
for(i in 1:100)
{
   for(j in 1:100)
    R[i,j]=gcm(i,j)
    save.image(file="path/to/your/file.RData")
}

About your code taking a lot of time I would advise trying the ?apply function, which

Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix

You want gmc to be run for-each cell, which means you want to apply it for each combination of row and column coordinates
R = 100; # number of rows
C = 100; # number of columns
M = expand.grid(1:R, 1:C); # Cartesian product of the coordinates
# each row of M contains the indexes of one of R's cells
# head(M); # just to see it

# To use apply we need gmc to take into account one variable only (that' not entirely true, if you want to know how it really works have a look how at ?apply)
# thus I create a function which takes into account one row of M and tells gmc the first cell is the row index, the second cell is the column index
gmcWrapper = function(x) { return(gmc(x[1], x[2])); }

# run apply which will return a vector containing *all* the evaluated expressions
R = apply(M, 1, gmcWrapper);

# re-shape R into a matrix
R = matrix(R, nrow=R, ncol=C);

If the apply-approach is again slow try considering the snowfall package which will allow you to follow the apply-approach using parallel computing. An introduction to snowfall usage can be found in this pdf, look at page 5 and 6 in particular


text:
Q: jQuery metadata, how to get the value? I'm having a tough time getting the value of a key in the data attribute. I'm using the jquery metadata plugin.
jQuery:
jQuery.metadata.setType("attr", "data");

$('ul li').each(function () {
   console.log($(this).metadata())
});

HTML

Some List Item

Some List Item 2

Some List Item 3

I am outputting the object, but have no idea how to get at the value. I've tried $(this).metadata().someKey and $(this).metadata('someKey') and now I am grasping for straws.

A: Looks like you want this:
myMeta = $(this).metadata();

Then you can access myMeta.someKey or myMeta.anotherKey - whatever meta keys you have set.


text:
Q: Confusion in generics in java I am learning generics in java.At first we made a arraylist of Integer and we added a value in list.
import java.util.ArrayList;
import java.util.List;

public class GenericsRunner {
    public static void main(String[] args) {
        ArrayList<Integer> numbers=new ArrayList<>();
        numbers.add(1);
    }

    static <X extends List> void duplicate(X list) {
        list.addAll(list);
    }
}

The Method duplicate can be only used by those objects which are extending List. But, since List is interface
public interface List<E> extends Collection<E>

And ArrayList is implemeting List
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable,
                   java.io.Serializable

I got stuck at this point. Extends is used by those classes which inherits the property from super class.
But how Arraylist is extending List? Actually ArrayList is implementing List. How is this extends keyword working for this implements mechanism? I am getting confused that it is using extends and implements are same?

A: The reason is <X extends T> means just that X is inherited from T. There is no special syntax for interfaces like when you describe inheritance in class declaration.
ArrayList implements interface List which means that it is inherited from List, thus it is suitable for generic type <X extends List>.
In Java any class can extend only one class. By default it's Object when you do not specify another parent class. And class and interface can implement any amount of interfaces.
Hope this helps.


text:
Q: how can I get the text around whatsapp fa icon? I'm trying to put the svg text around the whatsapp fa icon, something like this

but unable to achieve desired result. this is what I'm getting so far.

I tried with the below code.
<a id='whatsapp'
  style={{
    bottom: '162px', right: '32px', fontSize: '3.3rem',
    padding: '0.6rem', backgroundColor: '#70d470',
    color: '#fff'
    }}
    href="https://wa.me/1232365326"
    target="_blank" rel="noopener noreferrer"
    className={`${visible ? "block whatsapp" : "none"}`}
>
    <svg viewBox="0 0 100 100" width="100" height="100">
      <defs>
        <path id="circle"
          d="
            M 50, 50
            m -37, 0
            a 37,37 0 1,1 74,0
            a 37,37 0 1,1 -74,0"/>
      </defs>
      <text font-size="8">
        <textPath xlinkHref="#circle">
          Need Appointment? Click me!
        </textPath>
      </text>
    </svg>
  <RiWhatsappFill/>

A: You could try using position: 'absolute' on the text, then aligning it manually.
Here's something that might work, give it a shot.
<a id='whatsapp'
  style={{
    bottom: '162px', right: '32px', fontSize: '3.3rem',
    padding: '0.6rem', backgroundColor: '#70d470',
    color: '#fff'
    }}
    href="https://wa.me/1232365326"
    target="_blank" rel="noopener noreferrer"
    className={`${visible ? "block whatsapp" : "none"}`}
>
    <svg viewBox="0 0 100 100" width="100" height="100">
      <defs>
        <path id="circle"
          d="
            M 50, 50
            m -37, 0
            a 37,37 0 1,1 74,0
            a 37,37 0 1,1 -74,0"/>
      </defs>
      <text style={{position: 'absolute', right: '32px', top: '2px'}}  font-size="8">
        <textPath xlinkHref="#circle">
          Need Appointment? Click me!
        </textPath>
      </text>
    </svg>
  <RiWhatsappFill/>


text:
Q: How to print out the contents of a HashMap in a certain format? I'm not entirely sure how I would do this, here is my code:
public class PizzaMenu
{
    static Map<String,Pizza> namedPizzas= new HashMap<String,Pizza>();

    public static void main(String[] args)
    {

    }

    public static void addItem(String name, Pizza pizza)
    {
        namedPizzas.put(name, pizza);
    }

    public String printMenu()
    {
        /*
        String menuString="";
        for (Every menu item)

        {
            //Add name of menu item to menuString with carriage return
            //Add details of menu item (pizza.getInfo();) to menuString
        }
        */

        //return menuString
    }
}

I would then call System.out.println(PizzaMenu.printMenu()) in another class. The sort of format I'm hoping to achieve is as follows:
/*
 * PizzaName
 *      Details
 *
 * Next PizzaName in menu
 *      Details
 *
 * Next PizzaName in menu
 *      Details
 *
 *
 *
 */

Am I maybe using the wrong data structure for this type of operation or is there a way of achieving this?
Here is the structure of the Pizza class (apologies for poor formatting):
public class Pizza
{
private double cost;
private Boolean veg;
private PizzaBase base;
private List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();

public Pizza(PizzaBase base, PizzaTopping topping) //Constructor for pizza with 1 topping
{
    setBase (base);
    toppings.add(topping);
}

public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2) //Constructor for pizza with 2 toppings
{
    setBase (base);
    toppings.add(topping);
    toppings.add(topping2);
}

public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2, PizzaTopping topping3) //Constructor for pizza with 3 toppings
{
    setBase (base);
    toppings.add(topping);
    toppings.add(topping2);
    toppings.add(topping3);
}

public double getCost()
{
    return cost;
}

public void setCost(double cost)
{
    this.cost = cost;
}

public PizzaBase getBase()
{
    return base;
}

public void setBase(PizzaBase base)
{
    this.base = base;
}

public List<PizzaTopping> getToppings()
{
    return this.toppings;
}

public String getToppingsInfo()
{
    String toppingInfo = "\n";
    PizzaTopping t;
    for (int i = 0; i<getToppings().size();i++)
    {
        t = toppings.get(i);
        toppingInfo=toppingInfo+t.getInfo();
    }

    return toppingInfo;
}

public Boolean getVeg()
{
    return veg;
}

public void setVeg(Boolean veg)
{
    this.veg = veg;
}

public double calculateCost()
{
    PizzaTopping p;
    //Loop through all ingredients and add their costs to total cost
    for (int i = 0; i<toppings.size();i++)
    {
        p = toppings.get(i);
        cost+=p.getCost();
    }

    cost+=base.getCost(); //Add pizza base cost to total cost
    return cost;
}

//Check if pizza is vegetarian depending upon its ingredients
public Boolean isVeg()
{
    Boolean toppingCheck =true;
    Boolean baseCheck = true;
    PizzaTopping t; //Temporary value used to stored toppings being compared in for loop

    //Check each topping and check if it's suitable for vegetarians
    for (int i =0; i<toppings.size();i++)
    {
        while (toppingCheck == true)
        {
            t = toppings.get(i);
            if (t.getVeg()==false)
            {
                toppingCheck = false;
            }
        }
    }

    //Check base to see if it's suitable for vegetarians
    if (getBase().getVeg()==false)
    {
        baseCheck = false;
    }

    //Return value depending on if all ingredients are suitable for vegetarians
    if (toppingCheck == true && baseCheck == true)
    {
        return true;
    }

    else return false;

}

public String getInfo()
{
    String vegInfo;

    if (this.isVeg()==true)
    {
        vegInfo = "Yes";
    }

    else vegInfo ="No";

    return String.format("Toppings:%s\n"+"Base:\n%s"+"\nTotal Cost:\t£%.2f"+"\nSuitable for vegetarians: %s", getToppingsInfo(), getBase().getInfo(), calculateCost(), vegInfo);
    //Return list of toppings, Total Price, vegetarian

}

}

A: Try this:
String menuString="";
for (Map.Entry<String, Pizza> pizzaItem : namedPizzas.entrySet()) {
    menuString += pizzaItem.getKey() + "\n";
    menuString += "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}

A: public String printMenu()
    {

        String s ="";
        for (String key: namedPizzas.keySet()){
            s+= pizzaItem.getKey() + "\n";
            s+= "\t" + pizzaItem.getValue().getInfo() + "\n\n";
        }
       return menuString
    }

A: To address your question directly:
You need a set of keys. With a set of keys you can also get values. HashMap#keySet should work for this. You can loop through a set using a for each loop.
Then as you said, you need to build your string and return. Putting it together gives you:
public String printMenu()
{
    String menuString = "";
    for(String key : namedPizzas.keySet())
    {
        menuString += key + "\n" +
                      "\t" + namedPizzas.get(key).getInfo() + "\n\n";
    }
    return menuString;
}

I would also like to suggest a design improvement. You should be overriding the Object#toString method for things like this. The toString method will get automatically called when you try to print the object. This allows you to do: System.out.println(myPizzaMenu); instead of System.out.println(myPizzaMenu.printMenu());
The name printMenu is also misleading, so for that reason it's also bad.

A: Unfortunately, after switching the map to a list, it still didn't work. An hour later I found the bug causing it all! Thanks for everyone's answers, I will keep these methods in mind when I need to use maps again.
EDIT: Here is the new class structure for reference:
public class PizzaMenu
{
static List<Pizza> namedPizzas = new ArrayList<Pizza>();

public static void main(String[] args)
{

}

public static void addItem(String name, Pizza pizza)
{
    pizza.setName(name.toLowerCase());
    namedPizzas.add(pizza);
}

public static String  printMenu()
{
    String menuString="";
    Pizza p;

    //Collect all pizzas and add their information to string
    for (int i =0; i<namedPizzas.size(); i++)
    {
        p = namedPizzas.get(i);
        menuString+=p.getName().toUpperCase()+"\n"+p.getInfo()+"\n\n";
        p.resetCost();
    }

    return menuString;

}

}


text:
Q: Line chart fill color is faded I am trying to setup a line chart with one fill colour but for some reason, the fill colour is faded.
Example

Both the random view I have added to middle of screen and the fill colour of the line chart are set to be red, but for some reason the fill colour of the chart is faded.
Can see code here
@IBOutlet var liveChart : LineChartView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Chart Tests"

        configureChart(chart: liveChart)

        var xAxis = [String]()
        var yAxis = [Double]()
        for _ in 0..<10
        {
            xAxis.append("")
            let yVal = Double(randomBetweenNumbers(firstNum: 1.0, secondNum: 100.0))
            yAxis.append(yVal)
        }
        setData(xAxisArray: xAxis, yAxisArray: yAxis, chart: liveChart)

        let testView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        testView.center = view.center
        testView.backgroundColor = UIColor.red
        view.addSubview(testView)
    }

    func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
        return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
    }

    func configureChart(chart : LineChartView)
    {
        chart.chartDescription?.text = ""
        chart.noDataText = "Loading Data"
        chart.backgroundColor = UIColor.clear

        chart.drawGridBackgroundEnabled = false
        chart.dragEnabled = true
        chart.rightAxis.enabled = false
        chart.leftAxis.enabled = true
        chart.doubleTapToZoomEnabled = false
        chart.legend.enabled = false
        chart.pinchZoomEnabled = true
        chart.highlightPerTapEnabled = false
        chart.highlightPerDragEnabled = false

        chart.xAxis.enabled = false
        chart.leftAxis.drawAxisLineEnabled = false
        chart.leftAxis.drawGridLinesEnabled = false
        chart.leftAxis.labelCount = 5
        chart.leftAxis.forceLabelsEnabled = true
    }

    func setData(xAxisArray : [String], yAxisArray : [Double], chart : LineChartView)
    {
        var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
        if(xAxisArray.count > 0)
        {
            for i in 0 ..< xAxisArray.count
            {
                let chartEntry = ChartDataEntry(x: Double(i), y: yAxisArray[i], data: nil)
                yVals1.append(chartEntry)
            }
        }
        let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: "")
        set1.fillColor = UIColor.red
        set1.drawFilledEnabled = true
        set1.drawCirclesEnabled = false

        let data = LineChartData()
        data.addDataSet(set1)

        liveChart.data = data
    }

Is there a way to fix this? Or is this just the way the fill colour of the chart works?
Edit:
I am using
https://github.com/danielgindi/Charts

A: I assume you use this library: https://github.com/kevinbrewster/SwiftCharts
So the LineChartView automatically set alpha for the fill color: https://github.com/kevinbrewster/SwiftCharts/blob/master/SwiftCharts/LineChart.swift#L758
try to set fillAlpha property of the data set


text:
Q: Partitions of sums of $k$ random odd/even $r$th powers from array of consecutive $r$th powers Like my previous question, I'll pose this one too with an array.
$1^r, 3^r, 5^r, 7^r, 9^r$ (all odd $r$th powers)
That's array 1. And array 2;
$2^r, 4^r, 6^r, 8^r, 10^r$ (all even $r$th powers)
Let's take the sum of random $k$ integers from each array, where $r>2$ (to eliminate Pythagorean triplets), so our $r=3, k=3$, and from Array 1, we have $(1^3 + 5^3 + 7^3)=469$ and for Array 2, $(6^3 + 10^3 + 2^3)=1224$
Now let me get to the point. I want to know, is it possible for the sum of $k$ random odd/even $r$th powers from an array of consecutive odd/even $r$th powers respectively, to be partitioned in any other way than the $r$th powers that constituted them?
I guess the answer for this must be $1$ (the initial sum of $r$th powers)...
PS I've taken separate arrays to avoid the trouble of Hardy-Ramanujan-like numbers (as in cubes) and equivalence to other powers (like $3^3 + 4^3 + 5^3=6^3$) from occuring in the sum. The effort is to keep the possible partitions as close as possible to $1$ (initial composition).

A: If you look at the small summary about "taxicab" numbers, you will see that there are a fair number of $(s,t)$, $(u,v)$ such that $s^3+t^3=u^3+v^3$ and $s$ and $t$ are both odd, while $u$ and $v$ are both even.
By looking at tables of Hardy-Ramanujan numbers, we can produce examples that have more cubes. For $k=4$, all we need to do is to find in the tables two numbers $A$ and $B$ which can each be expressed as the sum of two odd cubes and also of two even cubes. Then the sum $A+B$ can be expressed as the sum of four odd cubes, and also of four even cubes.

A: Here's an example with odd numbers: $$1^3+9^3+15^3+23^3=3^3+5^3+19^3+21^3$$


text:
Q: I am Trying to Load a JSON Payload for Slack Messages with Multiple Messages to a Slack Channel I am trying to create a python script that can send customized JSON payloads to slack via a Slack App. See the code below:
import json
import requests
import os
import platform

decrypt = "gpg --output secrets.json --decrypt secrets.gpg"

if os.path.exists("secrets.gpg"):
      returned_value = subprocess.call(decrypt, shell=True)
else:
        print("The file does not exist")

with open('secrets.json','r') as f:
      config = json.load(f)

# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/
# webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
# slack_data = {'text': "BODY"}
webhook_url = (config['slack_config']['slack_target_url'])
#slack_messages = {
#slack_message_1={'text': "(config['slack_messages'['message_1'])"},
#slack_message_2={'text': "(config['slack_messages'['message_2'])"},
slack_message_3={'text': "(print(config['slack_messages'['message_3']))"}
#}

response = requests.post(
    webhook_url, data=json.dumps(slack_message_3),
    headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
    raise ValueError(
        'Request to slack returned an error %s, the response is:\n%s'
        % (response.status_code, response.text)
    )

While it does send a message to my slack channel, it does not print the payload from the JSON file containing:
{
  "slack_config": {
    "slack_target_url": "https://hooks.slack.com/services/xxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxx"
  },
  "slack_messages": {
    "message_1": "SLACK_MESSAGE_1",
    "message_2": "SLACK_MESSAGE_2",
    "message_3": "SLACK_MESSAGE_3"
  }
}

Instead, it just prints out the following:

Eventually, I would like to have a flat-file read multiple messages into a Slack Channel as defined within the secrets.json. How can I achieve this? Furthermore, I would then like to encrypt them and have them read. However, I feel like that is another question.
My main thing is how do I get all messages printed into the Slack channel as dictated by the secerets.json payload?

A: So I was able to complete this thanks to @Atreus' comments mentioned above.
Thanks to their remark the code now allows for me to make multiple messages from a payload json called secrets.json in the format of
{
  "slack_config": {
    "slack_target_url": "https://hooks.slack.com/services/xxxxxxxxxx/xxxxxxxxxxxxxx/xxxxxxxxxxx"
  },
  "slack_messages": {
    "message_1": "SLACK_MESSAGE_1",
    "message_2": "SLACK_MESSAGE_2",
    "message_3": "SLACK_MESSAGE_3"
  }
}

The code was altered to look like the following:
import json
import requests
import os
import platform

decrypt = "gpg --output secrets.json --decrypt secrets.gpg"

if os.path.exists("secrets.gpg"):
      returned_value = subprocess.call(decrypt, shell=True)
else:
        print("The file does not exist")

with open('secrets.json','r') as f:
      config = json.load(f)

# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/
# webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
# slack_data = {'text': "BODY"}
webhook_url = (config['slack_config']['slack_target_url'])
slack_message_1={'text': config['slack_messages']['message_1']}
slack_message_2={'text': config['slack_messages']['message_2']}
slack_message_3={'text': config['slack_messages']['message_3']}

# Send message_1
response = requests.post(
    webhook_url, data=json.dumps(slack_message_1),
    headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
    raise ValueError(
        'Request to slack returned an error %s, the response is:\n%s'
        % (response.status_code, response.text)
    )

# Send message_2
response = requests.post(
    webhook_url, data=json.dumps(slack_message_2),
    headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
    raise ValueError(
        'Request to slack returned an error %s, the response is:\n%s'
        % (response.status_code, response.text)
    )

# Send message_3
response = requests.post(
    webhook_url, data=json.dumps(slack_message_3),
    headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
    raise ValueError(
        'Request to slack returned an error %s, the response is:\n%s'
        % (response.status_code, response.text)
    )


text:
Q: TypeError: props.navigation.getParam is not a function. (In 'props.navigation.getParam('docId')', 'props.navigation.getParam' is undefined) I am trying to fetch the data from one screen to another through props.naviagtion.getParam, however I am getting this error :'TypeError: props.navigation.getParam is not a function. (In 'props.navigation.getParam('docId')', 'props.navigation.getParam' is undefined)'.
I have shared the code; if someone is familiar with the problem, your help will be appreciated!
import { useNavigation } from '@react-navigation/core'
import React from 'react'
import { StyleSheet, Text, TouchableOpacity, View, FlatList, ScrollView, Pressable } from 'react-native'
import { auth } from '../firebase'
import { DOC } from '../Data/dummy-data'

const HomeScreen = props => {
  const navigation = useNavigation()

  const handleSignOut = () => {
    auth
      .signOut()
      .then(() => {
        navigation.replace("Login")
      })
      .catch(error => alert(error.message))
  }

  const renderGridItem = (itemData) => {
    return (
      <TouchableOpacity
      style={styles.grid}
      onPress={ () => {
        navigation.navigate('Doctors',{docId:itemData.item.id})

  }}>
    <View>
      <Text>
        {itemData.item.title}
      </Text>
    </View>
    </TouchableOpacity>
    )
  }

  return (
    <View style={styles.container}>

      <FlatList keyExtractor={(item, index) => item.id}
      data={DOC}
      renderItem={renderGridItem} />

      <Text style={styles.txt}>Email: {auth.currentUser?.email}</Text>
      <TouchableOpacity
        onPress={handleSignOut}
        style={styles.button}
      >
        <Text style={styles.buttonText}>Sign out</Text>
      </TouchableOpacity>

    </View>
  )
}

HomeScreen.navigationOptions = {
  headerTitle: 'All Doctors',
  headerStyle: {
    backgroundColor: 'red'
  },
  headerTintColor: 'red'
};

export default HomeScreen

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',

  },
   button: {
    backgroundColor: '#0782F9',
    width: '60%',
    padding: 15,
    borderRadius: 10,
    alignItems: 'center',
    marginTop: 40,
  },
  buttonText: {
    color: 'white',
    fontWeight: '700',
    fontSize: 16,
  },
  txt:{
    fontSize:20,
    color:'black',
    alignItems:'flex-start'
  },
  screen:{
    marginTop:10,
    width:'30%',
    height:2,
    borderRadius:10,
    backgroundColor:'red',

  },
  grid:{
    flex:1,
    margin:15,
    height:150
  },
})

/////////////Doctor.js//////////////
import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import { DOC } from '../Data/dummy-data'

const Doctors = props => {
  const docId = props.navigation.getParam('docId')
  const selectedCategory = DOC.find(doc => doc.id === docId)
  return (
    <View>
      <Text>{selectedCategory.title}</Text>
    </View>
  )
}

export default Doctors

const styles = StyleSheet.create({})

A: There are two things that you need to take care of. First, if Doctors is not a screen in a navigator, then the route object will not be passed to it by the navigation framework. Second, if you are using react-navigation v5 or higher, then you access the params via the route object.
Since you navigate to Doctors, it should be a screen defined in the navigator, thus you can access it as follows.
const Doctors = props => {

  // destructure
  const { docId } = props.route.params

  const selectedCategory = DOC.find(doc => doc.id === docId)
  return (
    <View>
      <Text>{selectedCategory.title}</Text>
    </View>
  )
}

If you have a component that is not a screen inside a navigator, then you can use the useRoute hook.
const route = useRoute()
const { docId } = route.params

References: The last version for getParams is v4 as documented here. This has changed for higher versions as documented here. The useRoute hook is documented here.


text:
Q: apply a background to a android dialogue box i am trying to create a basic custom dialoge view on android witha few drop down boxes and a  background image.
the issue i am having is that  for some reason, it always draws the dialogue box bigger than necesary and therefore, the background image doesnt cover the whole dialogue box.
Its best i show you a pic of what i mean:

Sorry, here is my xml file related to this view:

<ImageButton android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/closeButton"
    android:src="@drawable/close_dialogue" android:background="@null"
    android:layout_alignParentRight="true" android:layout_marginRight="10dip" android:layout_marginTop="10dip"></ImageButton>
<TextView android:layout_height="wrap_content"
    android:layout_width="wrap_content" android:id="@+id/nzbNameText"
    android:text="Nzb Title" android:layout_below="@+id/closeButton" android:layout_marginLeft="10dip" style="@style/BoldBlackStyle"></TextView>
<TextView android:layout_height="wrap_content"
    android:layout_below="@+id/nzbNameText" android:layout_width="wrap_content"
    android:text="Catagory" android:id="@+id/catagoryLabel"
    android:layout_marginTop="20dip" android:layout_marginLeft="10dip" android:textColor="@color/Black"></TextView>
<Spinner android:layout_height="wrap_content"
    android:layout_below="@+id/catagoryLabel" android:layout_width="fill_parent"
    android:id="@+id/catagorySpinner" android:layout_marginLeft="10dip" android:layout_marginRight="10dip"></Spinner>
<TextView android:layout_height="wrap_content"
    android:layout_width="wrap_content" android:layout_below="@+id/catagorySpinner"
    android:id="@+id/postProcessLabel" android:text="Post process"
    android:layout_marginTop="10dip" android:textColor="@color/Black" android:layout_marginLeft="10dip"></TextView>
<Spinner android:layout_height="wrap_content"
    android:layout_below="@+id/postProcessLabel" android:id="@+id/postProcessSpinner"
    android:layout_width="fill_parent" android:layout_marginRight="10dip" android:layout_marginLeft="10dip"></Spinner>
<TextView android:layout_height="wrap_content"
    android:layout_below="@+id/postProcessSpinner" android:layout_width="wrap_content"
    android:id="@+id/priorityLabel" android:text="Priority"
    android:layout_marginTop="10dip" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:textColor="@color/Black"></TextView>
<Spinner android:layout_height="wrap_content"
    android:layout_below="@+id/priorityLabel" android:layout_width="fill_parent"
    android:id="@+id/prioritySpinner" android:layout_marginLeft="10dip" android:layout_marginRight="10dip"></Spinner>
<Button android:layout_height="wrap_content"
    android:layout_below="@+id/prioritySpinner" android:layout_width="wrap_content"
    android:id="@+id/downloadButton" android:text="Download" android:layout_marginLeft="10dip" android:layout_marginRight="10dip"></Button>

A: i think you have to remove the TitleBox on your DialogBox. In my Dialog i use this code requestWindowFeature(Window.FEATURE_NO_TITLE);


text:
Q: Create a patch to add a kubernetes annotation I would like to write an mutating webhook to add a default ingress class to all ingress object, that do not explicitly provide one.
According to the examples I found I need to provide a proper json patch for the webhook to return.
I first tried my patches using kubectl:
$ kubectl patch ingress mying --type='json' -p='[{"op": "add", "path": "/metadata/annotations/key", "value":"value"}]'
The  "" is invalid

Looks like this is not working when there is not already an annotations element present.
$ kubectl patch ingress mying --type='json' -p='[{"op": "add", "path": "/metadata/annotations", "value":{"key":"value"}}]'
ingress.extensions/kafka-monitoring-topics-ui patched

Creating the complete annotations element works fine, however in my case I need a key of kubernetes.io/ingress.class which contains a slash.
kubectl patch ingress mying --type='json' -p='[{"op": "add", "path": "/metadata/annotations", "value":{"kubernetes.io/ingress.class":"value"}}]'
ingress.extensions/kafka-monitoring-topics-ui patched

This works fine when creating the annotation object. However, if there is already a some annotation present and I simply want to add one, it seems to be impossible to add one.
Simply using [{"op": "add", "path": "/metadata/annotations", "value":{"kubernetes.io/ingress.class":"value"}}] removes all existing annotation, while something like '[{"op": "add", "path": "/metadata/annotations/kubernetes.io/ingress.class", "value": "value"}] does not work because of the contained slash.
Long story short: What is the correct way to simply add a ingress class using a proper patch?
PS: Yes, I am aware of kubectl annotate, but unfortunately that does not help with my webhook.

A: much easier for me was to annotate rather than patch:
kubectl annotate ingress mying kubernetes.io/ingress.class=value

add --dry-run -o yaml flags if you want to test it before applying the change.

A: Using just:
[{"op": "add", "path": "/metadata/annotations/kubernetes.io~1ingress.class", "value":"nginx"}]

does not work when the created pod has no annotations, for example when coming from kubectl run --generator=run-pod/v1 --attach test-deploy --image=busybox ls
To detect this you need a separate parsing step into a metadata with pointer annotation so it can be detected as nil, or always send an empty annotation when it's empty:
type Metadata struct {
    Annotations  *map[string]string
}

type ObjectWithMeta struct {
    Metadata Metadata
}

then send:
[
  {"op":"add","path":"/metadata/annotations","value":{}},
  {"op":"add","path":"/metadata/annotations/foo","value": "bar"}
]

A: Replace the forward slash (/) in kubernetes.io/ingress.class with ~1.
Your command should look like this,
$ kubectl patch ingress mying --type='json' -p='[{"op": "add", "path": "/metadata/annotations/kubernetes.io~1ingress.class", "value":"nginx"}]'

Reference:
RFC 6901 https://www.rfc-editor.org/rfc/rfc6901#section-3


text:
Q: why does tkinter does not recognise entry values? first my specs:
python 3.6.1
windows 10
Well, i can´t figure out why these code gives me these error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Juan Diego\AppData\Local\Programs\Python\Python36\lib\tkinter__init__.py", line 1699, in call
    return self.func(*args)
  File "C:\Users\Juan Diego\Desktop\cosasque no son programas (miosno)\Test1 - copia.py", line 11, in run1
    num= int(num_Entry.get())
AttributeError: 'NoneType' object has no attribute 'get'
I understand that python does not recognize num_Entry as an Entry, but WHY?
import tkinter
        import fractions
        #declares the function
        main= tkinter.Tk(className="main")
        num_Entry =tkinter.Entry(main).pack()
        den_Entry = tkinter.Entry(main).pack()
        def run1():
            global den_Entry
            global num_Entry
            num= int(num_Entry.get())
            den= int(den_Entry.get())
            den=int(input("denominator 1\n:-:->"))
            Fraction1= fractions.Fraction(num,den)
            print(Fraction1)
        #runs the code
        button = tkinter.Button(main, text="run!",command= run1).pack()
        main.mainloop()`

A: You cannot initialize a widget and layout on the same line. You need to split them all into 2 lines like this:
den_Entry = tkinter.Entry(main)
den_Entry.pack()


text:
Q: Big $O$ notation on both the sides of equality If $$ f(x)+O(g(x))=O(g(x)),$$
is it possible to write $$ f(x)=O(g(x))$$
and if yes, how does that work?

A: Remark on interpretation
The equals sign in big O notation is an unfortunate but prevalent abuse of notation which makes it harder to interpret relationships such as $f(x) + O(g(x)) = O(g(x))$.
In particular, note the asymmetry: it is true that $O(n) = O(n^2)$, but it is not true that $O(n^2) = O(n)$. A clearer, but rarely used notation for $f(x) = O(g(x))$ is $f(x) \in O(g(x))$ which highlights the asymmetry. It also shows that the appropriate interpretation of $f(x) + O(g(x)) = O(g(x))$ is:
For every $h(x) = O(g(x))$, we have $f(x) + h(x) = O(g(x))$.

Proof
The relationship can be proven using the "limit" definition of big-O which says
$$
a(x) = O(b(x))\iff \limsup_{x\to\infty} \frac{|a(x)|}{b(x)} \lt +\infty.
$$
Now, $h(x) = O(g(x))$ means that
$$
\limsup_{x\to\infty} \frac{|h(x)|}{g(x)} \lt +\infty
$$
and $f(x)+h(x)=O(g(x))$ says that
$$
\limsup_{x\to\infty} \frac{|f(x) + h(x)|}{g(x)} \lt +\infty.
$$
Finally, observe that
$$
\limsup_{x\to\infty} \frac{|f(x)|}{g(x)} \le \limsup_{x\to\infty} \frac{|f(x)+h(x)|}{g(x)}+\limsup_{x\to\infty} \frac{|h(x)|}{g(x)} \lt +\infty
$$
which means that $f(x)=O(g(x))$.

A: $$f(x)+O(g(x))=O(g(x))$$
I'm not familiar with the notation of writing $O()$ on the LHS of an equation. But presumably the $O(g(x))$ on the LHS represents a functions $h(x)=O(g(x))$ such that $|h(x)|\leqslant A g(x)$ for sufficiently large $x$.
The $O(g(x))$ on the RHS represents a functions $j(x)=O(g(x))$ such that $|j(x)|\leqslant B g(x)$ for sufficiently large $x$.
So we have
$$f(x)=j(x)-h(x)$$
$$|f(x)|=|j(x)-h(x)|$$
and so by the triangle inequality
$$|f(x)|\leqslant |j(x)|+|h(x)| \leqslant (A+B)g(x)$$
and so
$$f(x)=O(g(x))$$