text:
Q: Requisição angular $http não esta retornando dados Código Javascript
$http({
   url: "http://app.calculadoradesementes.com.br",
   method: "POST",
   headers: {
       "Content-Type": "application/x-www-form-urlencoded"
   },
   data: {
       nome: "Rafael",
       email: "rafael@b300.com.br",
       telefone: "82285181"
  }
  }).success(function(data){
       console.log(data);
  }).error(function(data){
      console.log(data);
  });

Dados retornados
array(0) {
}

Arquivo PHP onde acontece a requisição
var_dump($_POST);

A: Sim, a requisição do serviço $http do Angular está retornando dados e funcionando da maneira esperada.
O conteúdo retornado é exatamente a resposta do endpoint, que me parece ser o foco do problema:

var app = angular.module('sampleApp', []);

app.controller('SampleController', function ($scope, $http) {

  $http({
    url: "http://app.calculadoradesementes.com.br",
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: {
      nome: "Rafael",
      email: "rafael@b300.com.br",
      telefone: "82285181"
    }
  }).success(function(data){
    $scope.result = data;
  }).error(function(data){
    $scope.result = data;
  });

});

    {{result}}

O resultado é a resposta completa do servidor. Abaixo, o cabeçalho de retorno:
HTTP/1.1 200 OK
Date: Wed, 17 Feb 2016 18:26:32 GMT
Server: Apache/2.2.31 (Unix) mod_ssl/2.2.31 OpenSSL/1.0.1e-fips mod_bwlimited/1.4
X-Powered-By: PHP/5.4.45
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000
Content-Length: 13
Connection: close
Content-Type: text/html


text:
Q: React Native: DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script a I am continuously running into this error while trying to learn react native. The app will run fine and then I make some additions and it breaks and shows this error:

The code that is producing it is:
import React from 'react';
import {StyleSheet, View, Text} from 'react-native';

const App = () => {
  return (
    <View>
      <Text>Hello</Text>
    </View>
  );
};

const styles = StyleSheet.create({});

export default App;

Any information would be awesome, I just want a consistent dev environment to be able to work in. I have looked through similar posts however they all seem to already have functioning projects when receiving this error.

A: The fix is that it was a problem with the react-native debugger that apparently just happens sometimes, disable the debugger with ctr+m on the android device and debug using node command line or third party debugger

A: Running below command fixed the issue for me.
cd android
./gradlew clean

A: I have faced similar issue. Apparently, my react native debugger is trying to reference a module from previous react native folder.
(That time, I created 2 same react native folder, one as a backup. In case I messed up with the coding)
In order to fix this, I have to clear the react native cache. I found my answer in this post.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parallelize downloads across hostnames on WordPress? I'm getting this message "Parallelize downloads across hostnames" when checking my WordPress site on GTmetrix > https://gtmetrix.com
Here are the details > https://gtmetrix.com/parallelize-downloads-across-hostnames.html
How do I fix that ?

A: Details
Web browsers put a limit on the number of concurrent connections they will make to a host. When there are many resources that need to be downloaded, a backlog of resources waiting to be downloaded will form. The browser will make up as many simultaneous connections to the server as the browser allows in order to download these resources, but then will queue the rest and wait for the requests to finish.
The time spent waiting for a connection to finish is referred to as blocking and reducing this blocking time can result in a faster loading page. The waterfall diagram below shows a page which loads 45 resources from the same host. Notice how long the resources are blocked (the brown segments), before they are downloaded (the purple segments) as they wait for a free connection.

So here is a hack to implement it on WordPress.
In order to work properly, all subdomains/hostnames MUST have the same structure/path. Ex:

*

*example.com/wp-content/uploads/2015/11/myimage.jpg

*media1.example.com/wp-content/uploads/2015/11/myimage.jpg

*media2.example.com/wp-content/uploads/2015/11/myimage.jpg

Add to functions.php
function parallelize_hostnames($url, $id) {
 $hostname = par_get_hostname($url);
 $url =  str_replace(parse_url(get_bloginfo('url'), PHP_URL_HOST), $hostname, $url);
 return $url;
}

function par_get_hostname($name) {
 //add your subdomains below, as many as you want.
 $subdomains = array('media1.mydomain.com','media2.mydomain.com');
 $host = abs(crc32(basename($name)) % count($subdomains));
 $hostname = $subdomains[$host];
 return $hostname;
}
add_filter('wp_get_attachment_url', 'parallelize_hostnames', 10, 2);

A: This is mainly due do HTTP/1.1 in which browsers open on average 6 connections per hostname.
If you are running over HTTPS with a provider that supports HTTP/2, this warning can usually be safely ignored now. With HTTP/2 multiple resources can now be loaded in parallel over a single connection.
--
However, if you need to fix it, you can follow the below steps:

*

*Create additional subdomains such as:
domain.com static1.domain.com static2.domain.com

*Simply add the following code to your WordPress theme's functions.php file. And replace the $subdomains values with your subdomains.
All subdomains/hostnames MUST have the same structure/path.
function parallelize_hostnames($url, $id) {
$hostname = par_get_hostname($url); //call supplemental function
$url = str_replace(parse_url(get_bloginfo('url'), PHP_URL_HOST), $hostname, $url);
return $url;
}

function par_get_hostname($name) {
$subdomains = array('static1.domain.com','static2.domain.com');
$host = abs(crc32(basename($name)) % count($subdomains));
$hostname = $subdomains[$host];
return $hostname;
}

add_filter('wp_get_attachment_url', 'parallelize_hostnames', 10, 2);

Read more about the parallelize downloads across hostnames warning and why you probably don't need to worry about this anymore.


text:
Q: How to disable Bootstrap on an element? I am trying to disable the Bootstrap styles on my image and hr, but when I try to add class="list-unstyled" nothing changes. I have even tried using it on a div, but no luck there.

A: .list-unstyled

Removes the default list-style and left margin on list items (works on both
 and
). This class only applies to immediate children list items (to remove the default list-style from any nested lists, apply this class to any nested lists as well)
For more detailed about .list-unstyled
http://getbootstrap.com/css/#unstyled
For your problem, you need to override this class or remove this class and apply your own class and then apply CSS styling.

A: You need to override the css for the particular elements(where you don't want bootstrap default css). Also, class="list-unstyled" in not working here because it's used for disabling list-items styling.


text:
Q: ASP.Net Connection String Issue I'm new to ASP.Net and I'm going through this database tutorial:
https://www.guru99.com/insert-update-delete-asp-net.html
I created a new database "test" on Microsoft SQL Server Management Tool.

However, my connectionString in Visual Studio returns a 'login failed for user testerguy6' when I run it.

Does anyone see the issue here?

A: You must ensure you have correct permission set against the database.
In MSSQL Server Management Studio go to:
Security > Logins > on the db user (testerguy6) right click > Properties > in the new window click User Mapping (on the left hand side) and tick:

*

*db owner

*db datareader

*db datawriter


text:
Q: Security Method Annotations with Java Configuration and Spring Security 3.2 I am having some issues getting my application set up using method level annotation controlled by @EnableGlobalMethodSecurity I am using Servlet 3.0 style initialization using
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(MultiSecurityConfig.class);
    }
}

I have attempted 2 different ways of initialising an AuthenticationManager both with their own issues. Please note that not using @EnableGlobalMethodSecurity results in a successful server start up and all of the form security executes as expected. My issues arise when I add @EnableGlobalMethodSecurity and @PreAuthorize("hasRole('ROLE_USER')") annotations on my controller.
I am attempting to set up form-based and api-based security independently. The method based annotations need only work for the api security.
One configuration was the following.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**").httpBasic();
        }

        protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
        }
    }

    @Configuration
    public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/static/**","/status");
        }

        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().hasRole("USER").and()
                .formLogin().loginPage("/login").permitAll();
        }

        protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
        }
    }

}

This is not ideal as I really want only a single registration of the authentication mechanism but the main issue is that it results in the following exception:
java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []

As far as I am aware @EnableGlobalMethodSecurity sets up its own AuthenticationManager so I'm not sure what the problem is here.
The second configuration is as follows.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return new AuthenticationManagerBuilder(ObjectPostProcessor.QUIESCENT_POSTPROCESSOR)
                .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER").and()
                    .withUser("admin").password("password").roles("USER", "ADMIN").and()
                    .and()
                .build();
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        @Override protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**").httpBasic();
        }
    }

    @Configuration
    public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/static/**","/status");
        }

        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().hasRole("USER").and()
                .formLogin().loginPage("/login").permitAll();
        }
    }

}

This config actually starts successfully but with an exception
java.lang.IllegalArgumentException: A parent AuthenticationManager or a list of AuthenticationProviders is required
at org.springframework.security.authentication.ProviderManager.checkState(ProviderManager.java:117)
at org.springframework.security.authentication.ProviderManager.<init>(ProviderManager.java:106)
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.performBuild(AuthenticationManagerBuilder.java:221)

and when I test I found that the security doesn't work.
I've been looking at this for a couple of days now and even after diving into spring security implementation code I can't seem to find what is wrong with my configuration.
I am using spring-security-3.2.0.RC1 and spring-framework-3.2.3.RELEASE.

A: When you use the protected registerAuthentication methods on WebSecurityConfigurerAdapter it is scoping the Authentication to that WebSecurityConfigurerAdapter so EnableGlobalMethodSecurity cannot find it. If you think about this...it makes sense since the method is protected.
The error you are seeing is actually a debug statement (note the level is DEBUG). The reason is that Spring Security will try a few different ways to automatically wire the Global Method Security. Specifically EnableGlobalMethodSecurity will try the following ways to try and get the AuthenticationManager:

*

*If you extend GlobalMethodSecurityConfiguration and override the registerAuthentication it will use the AuthenticationManagerBuilder that was passed in. This allows for isolating the AuthenticationManager in the same way you can do so with WebSecurityConfigurerAdapter

*Try to build from the global shared instance of AuthenticationManagerBuilder, if it fails it logs the error message you are seeing (Note the logs also state "This is ok for now, we will try using an AuthenticationManager directly")

*Try to use an AuthenticationManager that is exposed as a bean.

For your code, you are going to be best off using something like the following:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {
    // Since MultiSecurityConfig does not extend GlobalMethodSecurityConfiguration and
    // define an AuthenticationManager, it will try using the globally defined
    // AuthenticationManagerBuilder to create one

    // The @Enable*Security annotations create a global AuthenticationManagerBuilder
    // that can optionally be used for creating an AuthenticationManager that is shared
    // The key to using it is to use the @Autowired annotation
    @Autowired
    public void registerSharedAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        // Since we didn't specify an AuthenticationManager for this class,
        // the global instance is used

        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")
                .httpBasic();
        }
    }

    @Configuration
    public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        // Since we didn't specify an AuthenticationManager for this class,
        // the global instance is used

        public void configure(WebSecurity web) throws Exception {
            web
                .ignoring()
                    .antMatchers("/static/**","/status");
        }

        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().hasRole("USER")
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll();
        }
    }

}

NOTE: More documentation around this will be getting added to the reference in the coming days.


text:
Q: C# Extend class by adding properties Is it possible in C# to extend a class not by adding only functions but properties. Ex: i have a standard DLL library I am relying on and the vendor does not want to modify it.
Already throughout the code I have used the DataCell class extensively and only now realized that I need to add an extra property to it, as creating a new extension class that inherits from this class just does not look like it would work + a lot of rewriting.
DataCell [metadata]
public class DataCell : Message
{
public int Field1;
public int Field2;
public DataCell()
{
 ..
}
..
}

Basically I want to add a public int Flags;  to this class.    So I can do now without rewriting anything,    (new DataCell).Flags = 0x10;

A: Well you can certainly extend a class and only add fields/properties to it (although I'd discourage the use of public fields as per your sample). However, unless other code uses your new class, the fields won't exist in the objects created. For example, if other code has:
DataCell cell = new DataCell();

then that won't have your Field1 and Field2 fields.
If every instance of the base class really should have these fields, you'd be better off working out how to change the base class rather than extending it.
If you were wondering whether you could add "extension fields" in the same way as extension methods are added (e.g. public static void Foo(this DataCell cell)) then no, that's not possible.

A: There are two ways to add properties to an existing class

*

*Add partial class, but this won't work for you because partial classes should be in the same assembly.

*Inherit this class in a different class which as far I know would be a better solution for you.
And no you can't use a extension property like an extension method.

A: First of all, you should probably reconsider your approach.
But if all else fails, here is how you can sort of add a property to a sealed class:
using System;
using System.Runtime.CompilerServices;

namespace DataCellExtender
{

    #region sample 3rd party class
    public class DataCell
    {
        public int Field1;
        public int Field2;
    }
    #endregion

    public static class DataCellExtension
    {
        //ConditionalWeakTable is available in .NET 4.0+
        //if you use an older .NET, you have to create your own CWT implementation (good luck with that!)
        static readonly ConditionalWeakTable<DataCell, IntObject> Flags = new ConditionalWeakTable<DataCell, IntObject>();

        public static int GetFlags(this DataCell dataCell) { return Flags.GetOrCreateValue(dataCell).Value; }

        public static void SetFlags(this DataCell dataCell, int newFlags) { Flags.GetOrCreateValue(dataCell).Value = newFlags; }

        class IntObject
        {
            public int Value;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dc = new DataCell();
            dc.SetFlags(42);
            var flags = dc.GetFlags();
            Console.WriteLine(flags);
        }
    }
}

Please don't do this unless you really must. Future maintainers of this code may have some strong words for you if there's a cleaner solution that you skipped in favor of this slightly hacky approach.


text:
Q: How can I fix the error message "code EACCES" when I tried to install the react-router-dom node? I have tried this many times and had this issue in the past, when I tried to install a different node package in another project. I moved on without that other package, but now I'm stuck.
I've tried:

*

*Unsetting the read properties for everything in my working directory

*Using the sudo commands to install packages and change the file owner

*Disabling controlled access in Windows

*And a number of other commands that I found on the web that just aren't recognized at all.

I guess I have to remove and re-install Ubuntu. I'm not sure what else to do at this point. For context, my experience is limited with Ubuntu and using a terminal in general. I'm using it for web development, so npm install, run and test are pretty much all I ever use. Now it doesn't work.
~/development/code/phase-2/react-hooks-react-router-code-along$ npm install react-router-dom@5
npm ERR! code EACCES
npm ERR! syscall rename
npm ERR! path /home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/type-fest
npm ERR! dest /home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/.type-fest-KEXQjTnf
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, rename '/home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/type-fest' -> '/home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/.type-fest-KEXQjTnf'
npm ERR!  [Error: EACCES: permission denied, rename '/home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/type-fest' -> '/home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/.type-fest-KEXQjTnf'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'rename',
npm ERR!   path: '/home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/type-fest',
npm ERR!   dest: '/home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/.type-fest-KEXQjTnf'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bambam320/.npm/_logs/2022-09-13T06_04_28_484Z-debug-0.log

Update: I checked permissions and was finally able to change them but it's not a permission issue. It's trying to rename a file that has all the permissions. I'm not sure why it's returning an error, the package itself is very common.
file: home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/type-fest
#owner: bambam320
#group: bambam320
user::rwx
group::rwx
other::rwx

> File: /home/bambam320/development/code/phase-2/react-hooks-react-router-code-along/node_modules/type-fest
> Size: 512             Blocks: 0          IO Block: 512    directory
Device: 2h/2d   Inode: 1125899909662013  Links: 1
Access: (0777/drwxrwxrwx)  Uid: ( 1000/bambam320)   Gid: ( 1000/bambam320)
Access: 2022-09-13 02:04:08.504282200 -0400
Modify: 2022-09-11 02:36:32.761662300 -0400
Change: 2022-09-13 02:04:07.077342300 -0400
Birth: -


text:
Q: No sound output both speakers and headphone toshiba satellite m55 Xubuntu 12.10 I am running Xubuntu 12.10 and I was trying to repair the sound on the headphone jack since I had sound output through there and now I have no sound what so ever. So I think I made things worst. No sound through the speakers and no sound through the headphone. I know I did something wrong but I don't know what I did. I have pulseaudio. If I could at least get the speakers working again I'll be happy. Any help will be highly appreciated!

A: Try this - Navigate to this menu -  settings-> sound -> output  & try different options under play sound through. You can use Test sound button to check if choosing any of those options work for you.


text:
Q: Simple way to get regionemail in second table and in body column their branch I have a 2 tables
First table
Id      branchemail                            regionemail
-------------------------------------------------------------------------------
1.     Amar@gmail.com.                  har@gmail.com
2.     Sima@gmail.com.                   har@gmail.com
3.     Sam@gmail.com.                    mic@gmail.com
4.     Suzane@gmail.com.               mic@gmail.com

Second table
Id       regionemail       Body
--------------------------------------------

I would like to get regionemail in second table and in body column their branchemail
For exmaple:second table look like
Id   regionemail           Body
--------------------------------------------
1  har@gmail.com   Amar@gmail.com,Sima@gmail.com.
2 mic@gmail.com     Sam@gmail.com, Suzane@gmail.com

The above is dummy data. I have 20 regionemails and thousands of branchemail against.


text:
Q: How to fix out TF53001 issue in TFS2015? Working with TFS2015 Upade2 and VS2015 Update2. Everything works well until one of the project collection can't add, rename, delete files. Will prompt an error Message:

TF53001: The database operation was canceled by an Administrator.

This issue can  be reproduced by everyone in my team even with team project collection administrator. How to fix out the issue? Any help would be appreciate!
Thanks Tomhans.

A: In order to resolve this error, you might want to start by checking the version of your SQL instance hosting the TFS databases.
To find the version of the SQL instance run the query 'select @@version'. The version list for SQL can be found here.
If your SQL version is lesser than SQL 2014 CU4 then update it to CU4 or a higher update. And then try it again. More details please refer this blog from MSDN.


text:
Q: Ansible "when variable == true" not behaving as expected I have the following tasks in a playbook I'm writing (results listed next to the debug statement in <>):
  - debug: var=nrpe_installed.stat.exists <true>
  - debug: var=force_install <true>
  - debug: var=plugins_installed.stat.exists <true>

  - name: Run the prep
    include: prep.yml
    when: (nrpe_installed.stat.exists == false or plugins_installed.stat.exists == true or force_install == true)
    tags: ['prep']

  - debug: var=nrpe_installed.stat.exists <true>
  - debug: var=force_install <true>
  - debug: var=force_nrpe_install <false>

  - name: Install NRPE
    include: install-nrpe.yml
    when: (nrpe_installed.stat.exists == false or force_install == true or force_nrpe_install == true)
    tags: ['install_nrpe']
    vars:
      nrpe_url: 'http://url.goes.here'
      nrpe_md5: 3921ddc598312983f604541784b35a50
      nrpe_version: 2.15
      nrpe_artifact: nrpe-{{ nrpe_version }}.tar.gz
      nagios_ip: {{ nagios_ip }}
      config_dir: /home/ansible/config/

And I'm running it with the following command:
ansible-playbook install.yml -i $invFile --extra-vars="hosts=webservers force_install=True"

The first include runs, but the second skips with this output:
 skipping: [server1] => {"changed": false, "skip_reason": "Conditional check failed", "skipped": true}

I'm under the impression that the conditional check should pass for all of them as force_install == true evaluates to true which should make the whole when evaluate to true (since it's a series of 'OR's).
How do I get the when to run when the variables are set appropriately?

Edit:
Changing the second when for the Install NRPE include to the following works, but doesn't explain why the other one, Run the prep runs appropriately:
Working:
when: (not nrpe_installed.stat.exists or force_install or force_nrpe_install)

Also working:
when: (nrpe_installed.stat.exists == false or plugins_installed.stat.exists == true or force_install == true)

Not working:
when: (nrpe_installed.stat.exists == false or force_install == true or force_nrpe_install == true)

The truncated (duplicates removed) output of that particular section of the play is:
TASK [debug] *******************************************************************
ok: [server2] => {
    "nrpe_installed.stat.exists": true
}

TASK [debug] *******************************************************************
ok: [server2] => {
    "plugins_installed.stat.exists": true
}

TASK [debug] *******************************************************************
ok: [server2] => {
    "force_install": true
}

TASK [Run the prep] ************************************************************
included: /tasks/nrpe-install/prep.yml for server2, server3, server4, server5, server6, server7

TASK [Prep and configure for installation | Install yum packages] **************
ok: [server6] => (item=[u'gcc', u'glibc', u'glibc-common', u'gd', u'gd-devel', u'make', u'net-snmp', u'openssl-devel', u'unzip', u'tar', u'gzip', u'xinetd']) => {"changed": false, "item": ["gcc", "glibc", "glibc-common", "gd", "gd-devel", "make", "net-snmp", "openssl-devel", "unzip", "tar", "gzip", "xinetd"], "msg": "", "rc": 0, "results": ["gcc-4.1.2-55.el5.x86_64 providing gcc is already installed", "glibc-2.5-123.el5_11.3.i686 providing glibc is already installed", "glibc-common-2.5-123.el5_11.3.x86_64 providing glibc-common is already installed", "gd-2.0.33-9.4.el5_4.2.x86_64 providing gd is already installed", "gd-devel-2.0.33-9.4.el5_4.2.i386 providing gd-devel is already installed", "make-3.81-3.el5.x86_64 providing make is already installed", "net-snmp-5.3.2.2-20.el5.x86_64 providing net-snmp is already installed", "openssl-devel-0.9.8e-40.el5_11.x86_64 providing openssl-devel is already installed", "unzip-5.52-3.el5.x86_64 providing unzip is already installed", "tar-1.15.1-32.el5_8.x86_64 providing tar is already installed", "gzip-1.3.5-13.el5.centos.x86_64 providing gzip is already installed", "xinetd-2.3.14-20.el5_10.x86_64 providing xinetd is already installed"]}

TASK [Prep and configure for installation | Make nagios group] *****************
ok: [server2] => {"changed": false, "gid": 20002, "name": "nagios", "state": "present", "system": false}

TASK [Prep and configure for installation | Make nagios user] ******************
ok: [server6] => {"append": false, "changed": false, "comment": "User for Nagios NRPE", "group": 20002, "home": "/home/nagios", "move_home": false, "name": "nagios", "shell": "/bin/bash", "state": "present", "uid": 20002}

TASK [debug] *******************************************************************
ok: [server2] => {
    "nrpe_installed.stat.exists": true
}

TASK [debug] *******************************************************************
ok: [server2] => {
    "force_install": true
}

TASK [debug] *******************************************************************
ok: [server2] => {
    "force_nrpe_install": false
}

TASK [Install NRPE] ************************************************************
skipping: [server2] => {"changed": false, "skip_reason": "Conditional check failed", "skipped": true}

A: Yeah... certainly requires testing. I recommend

*

*| bool is good unless you expect undefined vars

*var is defined and (var | bool) if you expect undefined vars

default(False) is OK as long and you are happy that these are true if the input is not parsed from YAML. I.e. variables defined through --extra_vars CLI parameter are strings.
 "false"
 "null"
 "defined string"

Hope this helps:
#!/usr/bin/env ansible-playbook
---
- name: Test truthiness
  hosts: localhost
  gather_facts: False
  vars:
    truthy_vars:
    # TRUE
    - True
    - 1
    - "true"
    # FALSE
    - "false"
    - null
    - False
    - 0
    # ERROR (invalid sytax error stops the loop of the first of these)
    - "null"
    - "defined string"
    # ERROR
    # truthy_var_undefined
    # FALSE
    truthy_var_defined:
  tasks:
  - name: Test truthy
    debug:
      msg: "is truthy"
    ignore_errors: True # beware, the loo
    when: item
    loop: "{{ truthy_vars }}"
    loop_control:
      label: Test {{ item }}
  - name: truthy_var_undefined
    debug:
    when: truthy_var_undefined
    ignore_errors: true
  - name: truthy_var_defined
    debug:
    when: truthy_var_defined

- name: Test | default(False)
  hosts: localhost
  gather_facts: False
  vars:
    default_pipe_vars:
    # TRUE
    - True
    - 1
    - "true"
    # beware these:
    - "false"
    - "null"
    - "defined string"
    # FALSE
    - null
    - False
    - 0
    # FALSE
    # default_pipe_undefined
    # FALSE
    default_pipe_defined:
  tasks:
  - name: Test | default(False)
    debug:
      msg: "is not | default(False)"
    when: item | default(False)
    loop: "{{ default_pipe_vars }}"
    loop_control:
      label: Test {{ item }}
  - name: default_pipe_undefined | default(False)
    debug:
    when: default_pipe_undefined | default(False)
  - name: default_pipe_defined | default(False)
    debug:
    when: default_pipe_defined | default(False)

- name: Test | bool
  hosts: localhost
  gather_facts: False
  vars:
    bool_vars:
    # TRUE
    - True
    - 1
    - "true"
    # FALSE
    - "defined string"
    - "null"
    - "false"
    - null
    - False
    - 0
    # ERROR
    # bool_undefined
    # FALSE
    bool_defined:
  tasks:
  - name: Test bool parsing
    debug:
      msg: "parsed as true booleans"
    when: item | bool
    loop: "{{ bool_vars }}"
    loop_control:
      label: Test {{ item }}
  - name: bool_undefined | bool
    debug:
    when: bool_undefined | bool
    ignore_errors: true
  - name: bool_defined var | bool
    debug:
    when: bool_defined | bool

- name: Test is defined and | bool
  hosts: localhost
  gather_facts: False
  vars:
    defined_bool_vars:
    # TRUE
    - True
    - 1
    - "true"
    # FALSE
    - "defined string"
    - "null"
    - "false"
    - null
    - False
    - 0
    # FALSE
    # defined_bool_undefined
    # FALSE
    defined_bool_defined:
  tasks:
  - name: Test bool parsing
    debug:
      msg: "parsed as true booleans"
    when:
    - item is defined
    - item | bool
    loop: "{{ defined_bool_vars }}"
    loop_control:
      label: Test {{ item }}
  - name: defined_bool_undefined | bool
    debug:
    when:
    - defined_bool_undefined is defined
    - defined_bool_undefined | bool
    ignore_errors: true
  - name: defined_bool_defined var | bool
    debug:
    when:
    - defined_bool_defined is defined
    - defined_bool_defined | bool

https://gist.github.com/kcd83/4ea23d201c271b58f1c4ef7844408657

A: You need to convert the variable to a boolean:
force_install|bool == true

I don't claim I understand the logic behind it. In python any non-empty string should be truthy. But when directly used in a condition it evaluates to false.
The bool filter then again interprets the strings 'yes', 'on', '1', 'true' (case-insensitive) and 1 as true (see source). Any other string is false.
You might want to also set a default value in case force_install is not defined, since it would result in an undefined variable error:
force_install|default(false)|bool == true


text:
Q: Collections sort Java Hi guys i have 3 Collections,
the first one I want sort per name, the second for email then last one I want sort for age.
My question is it work using collections?
if I do it in sql like
sort by name,email,age

I know that it work right?
Im trying do it in java like this.
Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        return o1.getName().compareTo(o2.getName());
    }
});

//then

Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        return o1.getEmail().compareTo(o2.getEmail());
    }
});

//and then

Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        return o1.getAge().compareTo(o2.getAge());
    }
});

it work? or each collection Overwrite previous?

A: If I got it correct, you should be using the java-8 features here...
Collections.sort(listPeople, Comparator.comparing(People::getName)
                     .thenComparing(People::getEmail)
                     .thenComparing(People::getAge));

A: If you successively sort the same collection than the operations will override the effects of the other sorting operations.

What you want can be accomplished by adjusting your custom comparator. First compare for the name, if elements are equal then compare by email, if again equal compare by age.
Take a look at this code snippet:
Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        int nameOrder = o1.getName().compareTo(o2.getName());
        if (nameOrder != 0) {
            return nameOrder;
        }

        // Elements names are equal, compare by their email
        int emailOrder = o1.getEmail().compareTo(o2.getEmail());
        if (emailOrder != 0) {
            return emailOrder ;
        }

        // Elements emails are equal, compare by their age
        int ageOrder = o1.getAge().compareTo(o2.getAge());
        // Return that in any case as we do not have another sorting criteria
        return ageOrder;
    }
});

Since Java 8 you can achieve the same with less code (see the answer of @Eugene):
Comparator.comparing(People::getName)
    .thenComparing(People::getEmail)
    .thenComparing(People::getAge));

This will create the same comparator than explained above.


text:
Q: Why transaction security and message security modes have different behaviours when passing the message to the destination? suppose there are three machine: client,load balancer and Service machine ,and the service is invoked by the load balancer.
When using transport security,the load balancer must decrypt and understand the messages before dispating them  to service,
but when using messages security,the load balancer just forward the encrypted messages to the service,
My puzzles is why the load balancer must decrypt and understand the messages before dispating them to service when using transport security ,but the load balancer doesn't do the decrypt operation when using message security mode ?
Can't the load balancer just forward the encrypted messages to the service just like it plays in the messages security?

A: A number of issues might require that.
For example, Consider the case of a web-server system. Using HTTP1.1, a client might open a single connection, and use it to send many GET requests to the server. If the transport layer is encrypted, and the load-balancer only forwards the packets, it would not be aware of the different requests flowing through the same connection. In such a case, all requests will go to the same server, without any load balancing.
On the other hand, if the load balancer acts as a connection end-point, it would be able to perform effectively.
(note that depending on the protocols and on the goal of load-balancing in the specific system, there might be cases with other issues, and there also might be cases which would work even without decryption in the load-balancer)


text:
Q: Mass-energy equivalence and Newton's Second Law of motion According to Einstein's Mass-energy equivalence,
$ E = mc^2$ OR
$ m = \frac E{c^2}$..... (1)
and According to Newton's Second Law of motion,
$ F = ma$ OR $m = \frac Fa$ ..... (2)
If we compare eq. (1) and eq. (2), we obtain;
$\frac E{c^2} = \frac Fa$..... (3)
If we multiply both the sides of eq. (3) with $c^2$, we get;
$E = \frac Fac^2$ ..... (4)
Is the above relation valid?

A: Your symbolic manipulations are correct, but the relations you write down do not properly describe Newton's second law in the context of special relativity.
In the context of special relativity, the relativistic momentum of a particle is defined as
$$
  \mathbf p = \gamma m \mathbf v, \qquad \gamma = (1-\mathbf v^2/c^2)^{-1/2}
$$
Using this definition, Newton's second law is written as
$$
  \mathbf F = \frac{d\mathbf p}{dt}
$$
In particular, note that since $\gamma$ has the velocity in it and therefore depends on time, we cannot move the time derivative past $\gamma$ when we differentiate $\mathbf p$ like we would in non-relativistic mechanics for a point particle.  So in the context of special relativity, we in general have
$$
  \mathbf F \neq m\frac{d\mathbf v}{dt}
$$
in direct constrast to non-relativistic mechanics. Also, the equation $E=mc^2$ is actually only true if the symbol $E$ represents the rest energy of the particle, the energy it has when it's speed is zero.  Otherwise, the total energy of the particle is
$$
  E = \gamma mc^2
$$
In particular, the energy of a massive point particle in special relativity depends on its speed and increases with increasing speed.


text:
Q: Make an Array of the Names from the Image Folder (java and Spring boot) I've got an image folder in my resources folder and there are pictures stored.
Now I want an Array in my Java Class who has stored the names of each Picture in the folder. Later I want to test if a picture name equals a specific word, but that can I handle by myself. I just dont know, how to make the 'PictureName' Array.
I am using Spring boot with Java.

A: It can be done easily:
File folder = new File("your_path");
File[] listOfFiles = folder.listFiles();

        for (File file : listOfFiles) {
        if(file.isFile()){
            System.out.println("File Name:" + file.getName());
        }
    }

A: File folder = new File("C:\\path\\to\\your\\folder\\");
List<File> files = Arrays.asList(folder.listFiles());

Insert the path to the folder that contains all your images in the first line.
In files List you will find the list of all the images in your folder in objects of type File.
Every File object has the method getName() that will return the name of the image.

A: Try somethings like this(Check if f is file( because it can be dictionary):
File folder = new File("yourPathTofolder");
        File[] listOfFiles = folder.listFiles();
        for (File f: listOfFiles) {
            if (f.isFile()) {
                System.out.println("File " + f.getName());
            }
        }

A: You can use below code:

*

*First provide your folder path, that will contain all the images.
File folder = new File("your/path");

*Store all files in File type array variable.

File[] listOfFiles = folder.listFiles();

*Iterate over variable to get filename(s)
for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else  {
    System.out.println("Not a File..");
  }
}

Full code
File folder = new File("your/path");
     File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
      } else  {
        System.out.println("Not a File..");
      }
    }

Hope that helps.


text:
Q: How to display the Lookup icon automatically to select Opportunity on a custom visualforce page? My expectation is to display lookup icon next to Opportunity field. The results  received from custom class in controller.
I am trying to display the opportunity name, but am expecting to display with lookup icon next to it which allows user to select another opportunity. My intention is update the record with another opportunity if user decides to do.
<apex:inputField value="{!result.oppty.Name}"/>

public class SearchResultController {
    public List<SearchResult> resultList {get; set;}
    public SearchResult searchResult {get; set;}

    public SearchResultController() {
    searchResult = new SearchResult();
    getSearchResults();
    }

    public class SearchResult {
        public Id acctId {get; set;}
        public Opportunity oppty {get; set;}
    }

    public void getSearchResults() {
       // populate resultList.
    }

}

Expected: SearchResults displayed using pageBlockTable. Display lookup icon next to opportunity name.

A: One way we found the solution is below:

*

*Create an object (kind of dummy object) with all the lookup fields that we wanted. Add it to the Controller as instance variable.

*In UI, display this dummy object with opportunity which automatically displays the standard look up icon and functionality.

*Once user selects the opportunity values and saves / submits, map the dummy object ID into SearchResult object's oppty in the Controller.


text:
Q: Auto generated IDs causing Uncaught TypeError: Cannot read property 'state' of undefined, i want plugin to map DB generated IDs i am using Bootstrap-TreeView Plugin and i am getting following error, what i have done is that i have already rendered the tree view, now i wanna have something similar to `"selected=selected"' for all the nodes that i wanna show as checked.
Uncaught TypeError: Cannot read property 'state' of undefined

Following is my code where i am trying to set the nodes by id
 var catgories_for_edit = {!! json_encode($product->categories) !!};

     $.each(catgories_for_edit,function(index,categoryObject){

            $categTreeView.treeview('checkNode', [categoryObject.id, { silent: true } ]);

        });

Json data:
// var catgories_for_edit returns following data
 [{"id":21,"parent_id":null,"lft":17,"rgt":24,"depth":2,"name":"admin","created_at":"2016-12-29 21:42:25","updated_at":"2017-01-02 08:30:23"}]

referring to following plugin
https://github.com/jonmiles/bootstrap-treeview


text:
Q: SharePoint 2010 Strips my CSS I was able to add in custom CSS using the "Edit HTML" option using these:
-float
-margin-right
-padding-left
-text-align
however, it modifies and removes my "border-left" that I add. Is this a common thing with borders using css within the regular content editing area? Or does it just hate me?

A: It depends on the page. Publishing type pages will typically remove HTML modifications, but Web Part Pages will allow them. To make custom CSS work, put the CSS into a file, upload it to a document library, insert a Content Editor Web Part into the page and reference the CSS file from there.


text:
Q: Javascript on Pocket PC Internet Explorer I have a problem with JavaScript not working in IE on Pocket PC.
The HTML is on the PDA loading locally, it has a simple function to show/hide SPAN tags:
function More(id) {
  if (document.getElementById(id).style.display=='block') {
    document.getElementById(id).style.display='none'; }
  else { document.getElementById(id).style.display='block'; }
}

Called like this:
click here
Hidden text

This works perfectly well using IE on Windows Mobile 5/6, but just doesn't do anything on Pocket PC.
As a test I have tried getting the JavaScript to do simpler things directly from the onclick part of the anchor tag.  The only thing that worked was alert() with hard coded text.
Is there a trick to getting JavaScript to work on Pocket PC?
I am using Pocket PC 4.20.0 (Build 14053).

A: PIE and PIE 2.0 only support JScript (which is not the same as Javascript). At IE mobile 6.0 Javascript support was added.


text:
Q: JSPG0301E: Invalid attribute, valueChangeListener, for deferred method returning void While migrating JSF application from WebSphere 6.1 to WebSphere 8.5.5 we faced following exception.

0000009b webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[/content/provinceStatHolidayContent.jsp]: com.ibm.ws.jsp.translator.JspTranslationException: JSPG0227E: Exception caught while translating xxx.jsp:
      JSPG0301E: Invalid attribute, valueChangeListener, for deferred method returning void.

A: Following snippet into concern jsp page resolve the problem.
<%@ page isELIgnored="false" deferredSyntaxAllowedAsLiteral="false"%>


text:
Q: How by ajax return a view blade in controller? I want to return a view using ajax in the controller regardless of response ajax.
for this state refresh the page

A: You can simply use the render() function.
$html = view('view.name')->render();

After that just return it.
return response()->json(['success' => true, 'html' => $html ]);


text:
Q: Is there a way to define "raw" strings in R? I realise there's another similar question asked 3 years ago at Are there raw strings in R for regular expressions?, but wonder if there is now a new answer to the question.
So, my question is more general about writing raw strings, not just for regex but also for windows paths and other strings that can have backlash present.

A: With R>4.0.0, you can parse raw strings using the following syntax:
> r"(C:\Users\)"
[1] C:\\Users\\

Note that, () are part of syntax i.e. r"(....)". You can use r"{...}" and r"[....]" also. Also note that, the double back slashes which you see printed is R's way of printing backslashes.


text:
Q: How do I generate a compiled lambda with method calls? I'm generating compiled getter methods at runtime for a given member.  Right now, my code just assumes that the result of the getter method is a string (worked good for testing).  However, I'd like to make this work with a custom converter class I've written, see below, "ConverterBase" reference that I've added.
I can't figure out how to add the call to the converter class to my expression tree.
    public Func<U, string> GetGetter<U>(MemberInfo info)
    {
        Type t = null;
        if (info is PropertyInfo)
        {
            t = ((PropertyInfo)info).PropertyType;
        }
        else if (info is FieldInfo)
        {
            t = ((FieldInfo)info).FieldType;
        }
        else
        {
            throw new Exception("Unknown member type");
        }

        //TODO, replace with ability to specify in custom attribute
        ConverterBase typeConverter = new ConverterBase();

        ParameterExpression target = Expression.Parameter(typeof(U), "target");
        MemberExpression memberAccess = Expression.MakeMemberAccess(target, info);

        //TODO here, make the expression call "typeConverter.FieldToString(fieldValue)"

        LambdaExpression getter = Expression.Lambda(memberAccess, target);

        return (Func<U, string>)getter.Compile();
    }

I'm looking for what to put in the second TODO area (I can handle the first :)).
The resulting compiled lambda should take an instance of type U as a param, call the specified member access function, then call the converter's "FieldToString" method with the result, and return the resulting string.

A: Can you illustrate what (if it was regular C#) you want the expression to evaluate? I can write the expression easily enough - I just don't fully understand the question...
(edit re comment) - in that case, it'll be something like:
    ConverterBase typeConverter = new ConverterBase();
    var target = Expression.Parameter(typeof(U), "target");
    var getter = Expression.MakeMemberAccess(target, info);
    var converter = Expression.Constant(typeConverter, typeof(ConverterBase));

    return Expression.Lambda<Func<U, string>>(
    Expression.Call(converter, typeof(ConverterBase).GetMethod("FieldToString"),
        getter), target).Compile();

Or if the type refuses to bind, you'll need to inject a cast/convert:
    MethodInfo method = typeof(ConverterBase).GetMethod("FieldToString");
    return Expression.Lambda<Func<U, string>>(
        Expression.Call(converter, method,
            Expression.Convert(getter, method.GetParameters().Single().ParameterType)),
            target).Compile();

A: You need to wrap the object in an ExpressionConstant, e.g. by using Expression.Constant. Here's an example:
class MyConverter
{
    public string MyToString(int x)
    {
        return x.ToString();
    }
}

static void Main()
{
    MyConverter c = new MyConverter();

    ParameterExpression p = Expression.Parameter(typeof(int), "p");
    LambdaExpression intToStr = Expression.Lambda(
        Expression.Call(
            Expression.Constant(c),
            c.GetType().GetMethod("MyToString"),
            p),
        p);

    Func<int,string> f = (Func<int,string>) intToStr.Compile();

    Console.WriteLine(f(42));
    Console.ReadLine();
}


text:
Q: AWS IAM policy for Billing & Cost Management I try to make a policy to read Billing & Cost Management for Amazon AWS.
I created the new policy AccessJustBillingReports:

Then i attached this policy to a new user:

But if i loggin with this user and I open the Billing & Cost Management Dashboard i have no access!

What do i wrong?

A: By default IAM users cannot access billing as mentioned here: http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html#user-permissions

Note These policies require that you activate IAM user access to the
  AWS Billing and Cost Management console on the Account Settings
  console page. For more information about activating IAM user access,
  see Activate Access to the AWS Website.

If you login as root and scroll down a bit you'll notice a section about allowing IAM access like this:

Once you activate IAM access you should be able to access the billing section.


text:
Q: How to secure my jQuery AJAX calls in PHP and Javascript? I have following PHP and Javascript code snippet in which I am making an jQuery AJAX call to get data from PHP and show it in the HTML.
PHP code

<?php

myfunction();

function myfunction()
{
 $myvar = $_POST['q']." how are you?";
 $myvar2 = $_POST['z'];
 echo $myvar."\n".$myvar2;
}
?>

HTML code

Javascript code

var data =" hello world";
var data2=" hello all";
function run()
{
 $.ajax(
               {
                   url: 'myscript.php',
                   data: {'q': data,'z':data2},
                   type: 'post',
                   success: function(output)
                   {
                          //alert(output);
                          document.getElementById("mydiv").innerHTML += output; //add output to div
                   }
                }
            );
}

Above code is working fine.
I want to secure this AJAX call to prevent it from hackers because I am making an AJAX call which is visible to all. This code is vulnerable to hackers attack. My question is what and where should I impose extra checks to make my AJAX call secure?
One thing I know that I should use following code snippet in my PHP file
if (!$_POST['q'] && !$_POST['z'])
{
  exit;
}|
else
{
  myfunction(); //call myfunction only if page is posted
}

What extra checks should I use in PHP and Javascript files?

A: there are lots of tricks that hackers use so you just have to make it hard/time consuming enough that the reward is not worth the investment.
First you should never echo back something that came in a post. Hackers are known to perform all sorts of injections with a hole like that.
To avoid that simply unescape the value first.
For MySQL use:mysqli_real_escape_string.
When echoing back HTML (echo or print) use: htmlspecialchars.
For executing code with exec use escapeshellcmd and escapeshellarg.
Example:
<?php
    define('CHARSET', 'ISO-8859-1');
    define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);

    function html($string) {
        return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
    }
    $myvar = $_POST['q']." how are you?";
    $myvar2 = $_POST['z'];
    echo html($myvar."\n".$myvar2);

?>

A: You are using POST that is good.

*

*More you can use "Session" for security.

*For code security you can put your functions and other important code in some different php files and include them in main file. To keep your code visible from directly.


text:
Q: Nested Loops "For" in Python : Order T I'm beginner in Python.
I am having difficulty resolving my problem:
Using nested for loops, print a right triangle of the character T on
the screen where the triangle is one character wide at its narrowest point and seven characters wide at its widest point:
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT

and
      T
     TT
    TTT
   TTTT
  TTTTT
 TTTTTT
TTTTTTT

Any idea?

A: I won't write a code for you but I can give you some hints:

*

*nested loops means a loop inside another loop, in this case one loop is for iterating through consecutive lines, the second is to print characters in each line

*the second example needs the same as the first, but you also need to check index of the inner loop and decide whether print space or 'T' character

A: I hope you already have got the answer :)
Pattern # 1
def triangle(n):
    for i in range(1, n +1):
        print ('T' * i).rjust(n, ' ')

triangle(7)

##Results >>>

      T
     TT
    TTT
   TTTT
  TTTTT
 TTTTTT
TTTTTTT

Pattern # 2
def triangle1(n):
    for i in range(1, n +1):
        print ('T' * i)

triangle1(7)

# Results >>>>
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT

Pattern generation by using only for loops
Here I have tried to generate the with the help of only for loops and will very generalized way. Purposefully I have not used any readily available functions so you can always optimize it further.
Pattern # 1
def triangle(n):
    # Iterate through number of columns
    for i in range(1, n +1):
        s = ""
        # Iterate through number of rows
        for j in list(range(i)):
            s += "T"
        print s

triangle(7)

Pattern # 2
def triangle1(n):
    # Iterate through number of columns
    for i in range(1, n +1):
        s = ""
        # Iterate through number of rows
        for j in list(range(i)):
            blank = ""
            # Generate 'blank spaces'
            for k in (range(n - i)):
                blank += " "
            # Generate 'T'
            s += "T"
        print blank + s

triangle1(7)


text:
Q: El primer proyecto Blazor con la demo del contador, no funciona Hace poco preparé mi Visual Studio 2019 Community para crear proyectos Blazor. Al crear un nuevo proyecto, trato de ejecutarlo como lo he visto en varios vídeos en que funciona bien. Pero cada proyecto que genero de prueba, da los mismos errores:

CS0115 FetchData.OnInitAsync(): No se encontró ningún miembro adecuado
  para invalidar FetchData.razor Linea 40
CS0234 El tipo o el nombre del espacio de nombres Layouts no existe en
  el espacio de nombres Microsof.AspNetCore.Components (¿falta alguna
  referencia de ensamblado?) _Imports.razor Línea 3

Veo en vídeos que con todos los pasos cumplidos, este proyecto predeterminado sale funcionando inmediatamente. Soy muy poco experimentado con esta IDE, y más aún con Blazor. Muchas gracias por su ayuda.


text:
Q: Batch file message popup, how to insert emoji? Write like this
msg * "My emoji "

But on popup I get
msg * "My emoji (random symbols)"
How to write a specific emoji for batch file popup on windows 10?

A: Based from the Mofi's comment, you should change the code page to 65001 and the batch file will be saved as UTF-8
@echo off
chcp 65001>nul
Title Emoji
msg * "My emoji "
pause


text:
Q: Hausdorff and diagonal Feedback on precision of argument and writing style is much needed.

Suppose that $(X, \mathcal{T})$ is a topological space. Show that if $X$ is Hausdorff, the diagonal $\Delta = \{(x,x) \mid x \in X\}$ is closed in $X \times X$.

ANSWER: Suppose $X$ is Hausdorff. We have to show that $\Delta$ is closed in $X \times X$, it is adequate to show that every point of closure of $\Delta = \{(x,x) \mid x \in X\}$ belongs to $\Delta$. Let $\delta = (u,v)$ be any point of closure of $\Delta$.  We have to show that $(u,v) \in \Delta$, i.e $u=v$. Since $\delta = (u,v)$ is a point of closure of $\Delta$, thus for every open neighbourhood $W$ of $u$ and $V$ of $v$,  $W(u) \times V (v)\cap \Delta \neq \emptyset$ . Consequently, $W(u) \cap V(v) \neq \emptyset$ for all open neighbourhoods $W,V$ of $u$ and $v$. However since $X$ is Hausdorff, $u$ and $v$ cannot be distinct, and so $u=v$.

How can I prove the converse?

A: $\Delta$ is closed
$\iff$ $X\times X\setminus \Delta$ is open
$\iff$ For any $(u,v)\notin \Delta$ there is an open neighbourhood $W$ disjoint to $\Delta$
$\iff$ For any $(u,v)\notin \Delta$ there is an open base set $W=U\times V$ disjoint to $\Delta$, where $U,V$ are open neighbourhoods of $u$ and $v$, respectively.
$\iff$ For any $u,v\in X$ with $u\ne v$ there are neighbourhoods $U\ni u,V\ni v$ such that there is no $z\in X$ with $(z,z)\in U\times V$
$\iff$ For any $u,v\in X$ with $u\ne v$ there are neighbourhoods $U\ni u,V\ni v$ such that $U\cap V=\emptyset$
$\iff$ $X$ is Hausdorff.

A: First, by definition, the topology on $X \times X$ is the one generated by the base $\mathcal{B} = \left\{ U \times V: U,V \mbox{ open in } X \right\}$. One can easily check that this is indeed a base for a topology, and it is the smallest topology that makes both the projection maps (onto the first and second coordinate) continuous. In general, for an arbitrary  product, this is also how the topology is defined (the smallest one to make all projections continuous).
Now, suppose $\Delta$ is closed in $X \times X$. We want to show that $X$ is Hausdorff, so we take any two distinct points $x \neq y$, both in $X$. Then $(x,y)$ is by definition not in $\Delta$ and so, as $\Delta$ is closed, there is a basic open set $U \times V \in \mathcal{B}$ that contains $(x,y)$ and is disjoint from $\Delta$.
Now, $(x,y) \in U \times V$ iff $x \in U$, $y \in V$ and $U,V$ are both open. And they are disjoint, because if $z$ were in both of them, $(z,z) \in \Delta \cap U \times V$, which is a contradiction with the way we chose $U \times V$. So $X$ is Hausdorff.
The reverse implication is essentially the same idea: if $X$ is Hausdorff, then we can show that $\Delta$ is closed by showing any point not in $\Delta$, so a point $(x,y)$ with $x \neq y$, has a neighbourhood that misses $\Delta$ (so it's not in the closure of $\Delta$).
Then of course we take disjoint $U$ and $V$, open around $x$ resp. $y$ and of course $U \times V$ is the required neighbourhood again...

A: I assume that $X\times X$ is endowed with the product topology. Suppose $\Delta$ is closed, and assume to the contrary that $X$ is not Hausdorff. There exist $a,b \in X$ such that for every open neighborhoods $U$ of $a$ and $V$ of $b$ we have $U \cap V \neq \emptyset$. Therefore, every basic neighborhood $U\times V$ of $(a,b)$ in $X\times X$ (with the product topology) satisfies $(U\times V)\cap \Delta \neq \emptyset$.  That is $(a,b)\in \bar{\Delta}$, and since $(a,b)\notin \Delta$ we have a contradiction to the fact that $\Delta$ is closed.


text:
Q: Securely using password as bash argument I'm extracting a part of a web application that handles the signup, the other part will be rewritten.
The idea is the signup part can exist as a separate application, interface with the rest of the application for creating and setting up the account. Obviously there are a ton of ways to do this, most of them network based solutions like SOAP, but I'd like to use a simpler solution: a setup script.
The concern is that certain sensitive data, specifically the admin password of the new account, would be passed through bash.
I was thinking of sharing a small class between the applications, so that the password can be passed already hashed, but I would also have to pass the salt, so it still seems like a (small) security risk. One of the concerns is bash logging (can I disable that for a single command?) but I'm sure there are other concerns as well?
This would be on the same private server, so the risk seems minimal, but I don't want to take any chances whatsoever.
Thanks.

A: Use the $HISTFILE environment variable, unset it (this is for all users):
echo "unset HISTFILE" >> /etc/profile

Then set it back again.
More info on $HISTFILE variable here: http://linux.about.com/cs/linux101/g/histfileenviron.htm
Hope this helps!

A: From the man page of bash:

HISTIGNORE
                A  colon-separated list of patterns used to decide which
  command
                lines should be saved on the  history  list.   Each  pattern
  is
                anchored  at  the  beginning of the line and must match
  the com-
                plete line (no implicit  '*'  is  appended).   Each  pattern
  is
                tested  against  the line after the checks specified by
  HISTCONTROL are applied.  In  addition  to  the  normal  shell
  pattern
                matching characters, '&' matches the previous history line.
  '&'
                may be escaped using  a  backslash;  the  backslash  is
  removed
                before attempting a match.  The second and subsequent
  lines of a
                multi-line compound command are not tested, and are added
  to the
                history regardless of the value of HISTIGNORE.

Or, based on your comment, you could store the password in a protected file, then read from it.

A: Passing the salt in clear is no problem (the salt is usually stored in clear), the purpose of the salt is avoiding the same password hashing to the same hash always (so users with the same password would have the same hash, and rainbow tables would only need a single hash for each possible password).
What is more problematic is passing sensitive data through command line arguments, an eavesdropper on the same box can see the arguments to any command (on Linux they appear on /proc//cmdline, and on most Unixes can be seen using ps; some systems restrict permissions on /proc// to only the owner of the process for security).
What you could do is pass the sensitive information through a file, don't forget to set the umask to a very restrictive setting before creating the file.

A: Bash doesn't normally log commands executed in scripts, but only in interactive sessions (depending on appropriate settings). To show this, use the following script:
#!/bin/bash
echo "-- shopt --"
    shopt | grep -i hist
echo "-- set --"
    set -o | grep -i hist
echo "--vars --"
    for v in ${!HIST*}
    do
        echo "$v=${!v}"
    done

Run it like this:
$ ./histshow

and compare the output to that from sourcing it like this:
$ . ./histshow

In the first case take note that HISTFILE is not set and that the set option history is off. In the second case, sourcing the script runs it in your interactive session and shows what your settings are for it.
I was only able to make a script keep an in-memory history by doing set -o history within the script and to log its history to a file by also setting HISTFILE and then doing an explicit history -w.


text: Q: What if gravitational mass and inertial mass of a body had different values? From the equivalence principle we know that the gravitational and inertial mass of a body have same values.  But I'm just wondering what would the universe be like if they had different values?


text:
Q: Remove whitespace using Imagick and PHP, then save as transparent PNG I've got an image and want to remove all whitespace around it, and then save it as a transparent PNG. I'm using Imagick in PHP to do so, but my script doesn't seem to function properly.
<?php
$im = new Imagick("http://images.icecat.biz/img/norm/high/14688888-2862.jpg");

$im->borderImage("#ffffff", 20, 20);
$im->trimImage(0.3);

$im->setImagePage($im->getImageWidth(), $im->getImageHeight(), 0, 0);
$im->setImageFormat("png");

header("Content-Type: image/" . $im->getImageFormat());
echo $im->getImageBlob();
?>

What do I need to do to remove all white (and close to white) areas at the borders? And when that is done, can I easily resize the image to crop all of the transparency?

A: The fuzz factor needs to be a quantum scaled value, not just for this function but almost all functions that take 'fuzz' as a parameter.
i.e. you need to scale it up to the quantum range.
$im->trimImage(0.3 * \Imagick::getQuantum());

Or if you are using an earlier version of Imagick that doesn't have that method, then instead do:
$range = $image->getQuantumRange();
$image->trimImage(0.3 * $range['quantumRangeLong']);

The reason for this is to allow precise control over the pixel matching. If the value was passed in as a float value in the range 0-1 it would not possible to have exact control over the value that was used for matching.
By instead using an integer value (for versions of Imagick that do not have HDRI enabled) it allows you to precisely control the values that are compared for the operation.

A: You need something like an autocrop based on pixel values, I think this will help:
http://www.imagemagick.org/script/command-line-options.php#trim
you might also like:
http://fmwconcepts.com/imagemagick/autotrim/index.php
source:
http://www.imagemagick.org/discourse-server/viewtopic.php?t=10843


text:
Q: Pass custom product meta data to the order in Woocommerce 3 In Woocommerce, I'm attempting to add a piece of custom meta to my products and I would like to pass it through to orders.
We have a substantial amount of products and they are accountable to different cost centers so I need a select box inside the product admin that we can choice the cost centers that passes a value into an order this does not need to be viewed by the customer but needs to be viewable by admin in the orders and also in the order exports each month for accounting.
This is what I have so far, this will display the select box in product edit pages (admin):
// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '
';

    woocommerce_wp_select(
    array(
    'id'      => '_select',
    'label'   => __( 'Cost Centre', 'woocommerce' ),
    'options' => array(
        'one'   => __( 'MFEG', 'woocommerce' ),
        'two'   => __( 'YDIT', 'woocommerce' ),
        )
    )
);

  echo '
';

}

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields_save( $post_id ){

    // Select
    $woocommerce_select = $_POST['_select'];
    if( !empty( $woocommerce_select ) )
        update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );

}

But it is not passing the value in to an order.
How can I pass this custom field value to the order?

A: I have revisited a bit your code. The following will save your product custom field "Cost centre" as hidden order item meta data, visible only in Admin Order edit pages on each item:
// Admin products: Display custom Field
add_action( 'woocommerce_product_options_general_product_data', 'product_options_general_product_data_add_field' );
function product_options_general_product_data_add_field() {
    global $post;

    echo '
';

    woocommerce_wp_select( array(
        'id'      => '_cost_centre',
        'label'   => __( 'Cost Centre', 'woocommerce' ),
        'options' => array(
            'MFEG'   => __( 'MFEG', 'woocommerce' ), // Default displayed option value
            'YDIT'   => __( 'YDIT', 'woocommerce' ),
        )
    ) );

    echo '
';
}

// Admin products: Save custom Field
add_action( 'woocommerce_process_product_meta', 'product_options_general_product_data_save_field' );
function product_options_general_product_data_save_field( $post_id ){
    if( isset( $_POST['_cost_centre'] ) )
        update_post_meta( $post_id, '_cost_centre', esc_attr( $_POST['_cost_centre'] ) );
}

// Order items: Save product "Cost centre" as hidden order item meta data
add_action('woocommerce_checkout_create_order_line_item', 'save_file_type_as_order_item_meta', 20, 4);
function save_file_type_as_order_item_meta($item, $cart_item_key, $values, $order) {
    if ( $cost_centre = $values['data']->get_meta('_cost_centre') ) {
        $item->update_meta_data( '_cost_centre', $cost_centre ); // Save as order item (visble on admin only)
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Export: (In StackOverFlow, the rule is one question for one answer).
The WordPress/Woocommerce basic order export don't allow to export order items
You will need to use a third party plugin and depending on the chosen plugin, you will have to add your order item custom field _cost_centre for your export based on the plugin possibilities.


text:
Q: How to modify font-size/style of Tooltip component? Not able to assign custom class to tooltip component in order to update the style of tooltip component
Tried by assigning to classes property
Posted at https://codesandbox.io/s/twilight-fire-907mp

A: Make your own Tooltip with custom styles and then use it:
const TooltipWithBiggerFontSize = withStyles({
  tooltip: {
    fontSize: 30
  }
})(Tooltip)

As you already did with other components, eg: DialogContent or DialogActions.
Usage
<TooltipWithBiggerFontSize title="Custom Search">
  <Publish />
</TooltipWithBiggerFontSize>

BTW, your code is confusing. You are mixing functional and class components. Once, you are styling with withStyles once with makeStyles.
You should choose one method and stick to it. Here is styling docs. It will solve most of your problems.
codesandbox


text:
Q: Specific issue with reading data I am not sure why the data is not loading in?? It was working fine before, then all of a sudden any file I try to read in just returns async
INPUT: data = FileAttachment("cincinnati_store.json").json
OUTPUT FROM CELL: data = async ƒ(…)

A: It looks like you need parentheses after .json. So, the input of the cell should look like:
data = FileAttachment("cincinnati_store.json").json()

You need the parentheses because json is a method on the FileAttachment (i.e. a function you have to call). That's as opposed to something like the length of a JavaScript array, which is a property of the object, so you can just call myArray.length without parentheses. It's fair to be confused by this — different objects do it differently, so you sort of just have to know (or look up) what's what!
You get a hint there in the output of the cell (the "inspector") because it's telling you that the value of what you've put in is an asynchronous function. It's showing you the function itself, as opposed to the return value of calling the function, so you can tell that you have to call it to get the Promise that resolves to your cincinnati_store.json data.
If that doesn't work, if you post a link to your notebook I'd be happy to take a look.


text:
Q: Как объединить два массива и сделать отображения по порядку Пытаюсь объединить два массива первый массив
 $begin = mktime(0, 0, 0, date('m'), 1, date("Y"));
    $end = mktime(0, 0, 0, date('m'), date("t"), date("Y"));

    $day = array();

    for($i = $begin; $i <= $end; $i += 86400)
    {
        if(date("w", $i) != 0 && date("w", $i) != 6)
            $day[] = array(
            'label' =>   date("Y-m-d", $i)
            );
    }

получаю  массив такого вида
Array
    (
        [0] => Array
        (
            [label] => 2017-03-01
        )

[1] => Array
    (
        [label] => 2017-03-02
    )

[2] => Array
    (
        [label] => 2017-03-03
    )

[3] => Array
    (
        [label] => 2017-03-04
    )

[4] => Array
    (
        [label] => 2017-03-05
    )

[5] => Array
    (
        [label] => 2017-03-06
    )

[6] => Array
    (
        [label] => 2017-03-07
    )

[7] => Array
    (
        [label] => 2017-03-08
    )

[8] => Array
    (
        [label] => 2017-03-09
    )

[9] => Array
    (
        [label] => 2017-03-10
    )

[10] => Array
    (
        [label] => 2017-03-11
    )

[11] => Array
    (
        [label] => 2017-03-12
    )

[12] => Array
    (
        [label] => 2017-03-13
    )

[13] => Array
    (
        [label] => 2017-03-14
    )

[14] => Array
    (
        [label] => 2017-03-15
    )

[15] => Array
    (
        [label] => 2017-03-16
    )

[16] => Array
    (
        [label] => 2017-03-17
    )

[17] => Array
    (
        [label] => 2017-03-18
    )

[18] => Array
    (
        [label] => 2017-03-19
    )

[19] => Array
    (
        [label] => 2017-03-20
    )

[20] => Array
    (
        [label] => 2017-03-21
    )

[21] => Array
    (
        [label] => 2017-03-22
    )

[22] => Array
    (
        [label] => 2017-03-23
    )

[23] => Array
    (
        [label] => 2017-03-24
    )

[24] => Array
    (
        [label] => 2017-03-25
    )

[25] => Array
    (
        [label] => 2017-03-26
    )

[26] => Array
    (
        [label] => 2017-03-27
    )

[27] => Array
    (
        [label] => 2017-03-28
    )

[28] => Array
    (
        [label] => 2017-03-29
    )

[29] => Array
    (
        [label] => 2017-03-30
    )

[30] => Array
    (
        [label] => 2017-03-31
    )

)
второй массив из базы
  Array
    (
        [0] => Array
        (
            [value] => 1
        [order_status_id] => 1
        [date_added] => 2017-03-18
    )
[1] => Array
    (
        [value] => 1
        [order_status_id] => 1
        [date_added] => 2017-03-21
    )

)
Как сделать что бы даты выводились по порядку ,
пример
 Array
    (
        [18] => Array
        (
            [label] => 2017-03-18
            [value] => 1
        )

        [20] => Array
    (
        [label] => 2017-03-21
        [value] => 1
    )............

Так весь массив а value было только там где даты совпадают

A: Нашел решения может кому то пригодиться
      $begin = mktime(0, 0, 0, date('m'), 1, date("Y"));
    $end = mktime(0, 0, 0, date('m'), date("t"), date("Y"));

    $day = array();
    $format_day = array();
    for($i = $begin; $i <= $end; $i += 86400)
    {
        $day[] = array(
            'label' =>   date("Y-m-d", $i),
        );
        $format_day[] = array(
            'label' => date("d/m", $i)
        );
    }

    // new
    $array_date = $day;

    // второй массив из базы
    $orders_status_new = $this->model_account_order->getOrdersCountStatusNew();

    $array_new = array();
    foreach ($orders_status_new as $status_order){
        $array_new[] = array(
            'value' => $status_order['order_status_id'],
            'label' =>$status_order['date_added']
        );
    }

    foreach($array_date as $index => $value){
        $array_date[$index]['value'] = null;
    }

    $searchArray = array_column($array_date,'label');

    foreach($array_new as $value){

        $key = array_search($value['label'],$searchArray);
        if(!$key){
            echo sprintf("value %s not found<br/>",$value['label']);
            continue;
        }

        $array_date[$key]['value']=$value['value'];
    }

    echo "<pre>";
    print_r($array_date);


text:
Q: Laravel 5: How to handle nested objects in json request I just started working on Laravel 5. I am sending json request to my controller. It works fine for simple json. Now I have a scenario where json will be something like this
{
"orders":[
        {
          "user_id":"1",
          "product_id":"10"
        },
        {
            "user_id":"1",
          "product_id":"15"
        },
    ]
}

It can get more complex with nested objects. Inside my controller what I have been doing is simply like
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ordersController extends Controller
{
    public function __construct( Request $request)
    {
      //$this->middleware('products.prodcutsList');
    }

    public function makeOrder(Request $request)
    {
        $order_data= $request->only('orders');
        print_r($order_data);
    }
}

response I get is looks like this
Array
(
    [orders] =>
)

Please guide how can I get this in an array.

A: I'm not sure that will resolve you problem but your json is not correct you have to remove extra comma in the end :
{
"orders":[
        {
          "user_id":"1",
          "product_id":"10"
        },
        {
            "user_id":"1",
          "product_id":"15"
        }, //remove this comma
_________^
    ]
}

Note : You can use the following pretty website to validate you JSON jsonformatter.
Hope this helps.

A: You send your data as form data. Use the php input wrapper:
$input = file_get_contents('php://input'); // json
print_r(json_decode($input)); // decode to php array


text:
Q: add a node to specific child node I can add a node to a treeview add method.But I want to add a node to specific child node.
For example want to add a node to node5
|___node0
|___node1
|     |___node3
|     |___node4
|           |___node5
|___node2

How do I can do this?
Thanks.

A: TreeNode[] tn = treeView.Nodes[0].Nodes.Find(search.Text, true);
if (tn.Count>0)
   tn[0].Nodes.Add(node);
else
   //handle node not found

A: If you have the child node reference , you can simply access its Nodes Collection and add new child into its collection as shown below
node5.Nodes.Add(New TreeNode("temp"));

A: Basic recursive tree node searcher, of the top of my head. If you only need to search by key, the answer by weismat is the easiest, however if you need to search by the data on the nodes, you should consider this solution as you can replace the name search with whatever you might like to find.
private TreeNode FindNode(TreeNode root, String name)
{
    foreach (TreeNode node in root.Nodes)
    {
        if (node.Nodes.Count > 0)
            return FindNode(root, name);
        if (node.Name == name)
            return node;
    }
    return null;
}

A: William was right, but the method should look like this:
private TreeNode FindNode(TreeNode root, String name)
        {
            foreach (TreeNode node in root.Nodes)
            {
                if (node.Name == name)
                    return node;
                else
                {
                    if (node.Nodes.Count > 0)
                        return FindNode(node, name);
                }
            }
            return null;
        }

tested this and works just fine,
Cheers!


text:
Q: How to get the full URL of the current page using PHP What is the "less code needed" way to get parameters from an URL query string which is formatted like the following?
My current url
www.mysite.com/category/subcategory/#myqueryhash

I put this code
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

It returns only www.mysite.com/category/subcategory/
Output should be :
www.mysite.com/category/subcategory/#myqueryhash

A: You can use this for HTTP request
<?php $current_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>

You can use this for HTTPS request
<?php $current_url="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>

You can use this for HTTP/HTTPS request
<?php $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>


text:
Q: Why does this DFS code only work calling it within a generator? I would really appreciate your assistance. I am studying DFS paths and I understand the code but what I do not understand is the last line. Why can't I just call the function as dfs_paths(graph, 'A', 'F') and not list(dfs_paths(graph, 'A', 'F')) for the code below to work? Thank you.
graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])}

def dfs_paths(graph, start, goal):
    stack = [(start, [start])]
    while stack:
        (vertex, path) = stack.pop()
        for next in graph[vertex] - set(path):
            if next == goal:
                yield path + [next]
            else:
                stack.append((next, path + [next]))

dfs_paths(graph, 'A', 'F')

A: Because dfs_paths isn't a regular function; it's a generator function. When you run the function, it only returns a generator, and doesn't actually execute any of the code in the body until you start to iterate over the return value. That iteration can be explicit via a for loop:
for path in dfs_paths(graph, 'A', 'F'):
    ...

or implicit via a function like list that consumes an iterator:
paths = list(dfs_paths(graph, 'A', 'F'))

A: It's the yield statement in the function.
Methods with a yield in them are generators. Generators return an iterator when invoked. If you want to get the full return value (the whole path) you have to finish iteration over the iterator. Hence the need for the list() - that implicitly iterates over the iterator giving you the whole path.


text:
Q: Tweepy twitter oauth authentication not returning oauth_verifier I am using a python library called "tweepy" for twitter. When I try to authorize the user, twitter is supposed to redirect to a callback url with auth_token and oauth_verifier. I am  getting only auth_token in the url. Anyone else had the same problem?

A: Twitter only uses oauth_verifier (PINs) for desktop applications. For web applications, Twitter bypasses this and does not use it. You can re-check your application settings at http://dev.twitter.com/apps


text:
Q: MySQL Understanding Connections I have MySQL workbench installed so I can view live connections. When I have my browser closed and I am not viewing my web application, the connection is 4.
When I open my browser and go to my website on a page where a connection is required the connection stays at 4. If I open a second browser and do the same thing, the connection is still 4.
I am using PHP PDO to always connect to the same database. Why is my connection always staying at 4? I'm having trouble understanding this, In my mind expect this number to increase when I visit my website.


text:
Q: pthread_mutex_lock issue in synchronization I have been working on code that uses pthread library in C. The code does the following:

*

*Main create two threads each of which has it own thread routines(functions)

*One thread (thread 1) generate a random number and assign it to a global variable x

*Then the other thread (thread 2) basically prints the value of the global variable

*This operation of generating and printing the random value of x is repeated 5 times

The expected output:
generator thread >> x = 5
printer thread >> x = 5
generator thread >> x = 9
printer thread >> x = 9
generator thread >> x = 7
printer thread >> x = 7
generator thread >> x = 3
printer thread >> x = 3
generator thread >> x = 2
printer thread >> x = 2

However, the output comes in a random order where sometimes the printer gets executed first or one of the threads gets executed multiple times before the other thread gets executed.
For example:
$ ./mutex.out
generator >> x = 7
generator >> x = 10
generator >> x = 4
generator >> x = 7
generator >> x = 10
printer >> x = 7
printer >> x = 10
printer >> x = 10
printer >> x = 10
printer >> x = 10
$ ./mutex.out
printer >> x = 0
printer >> x = 0
printer >> x = 0
printer >> x = 0
printer >> x = 0
generator >> x = 9
generator >> x = 2
generator >> x = 1
generator >> x = 3
generator >> x = 7

The code I have written for this problem:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define NUMTHRDS 2
pthread_t t [ NUMTHRDS];
pthread_mutex_t m1, m2;
int x = 0;

void *thread1(void *arg){
    for(int i = 0 ; i < 5 ; i++){
        pthread_mutex_lock(&m2);
        pthread_mutex_lock(&m1);
        x = (rand() % 10) + 1; // generates a random number between 1 and 10
        printf("generator >> x = %d\n" , x);

        pthread_mutex_unlock(&m1);
        pthread_mutex_unlock(&m2);
    }
}

void * thread2(void * arg){
    for(int i = 0 ; i < 5 ; i++){
        pthread_mutex_lock(&m1);
        pthread_mutex_lock(&m2);
        printf("printer >> x = %d\n" , x);
        pthread_mutex_unlock(&m2);
        pthread_mutex_unlock(&m1);
    }
}

int main(void)
{
    srand(time(NULL));

    pthread_mutex_init(&m1, NULL);
    pthread_mutex_init(&m2, NULL);

    pthread_create(&t[1], NULL, thread1, NULL);
    pthread_create(&t[0], NULL, thread2, NULL);

    pthread_mutex_destroy(&m1);
    pthread_mutex_destroy(&m2);

    pthread_exit(NULL);

    return 0;

}

My problem is how to use mutexes correctly in order to maintain the order between these two threads without using anything else.

A: Two problems at first sight:

*

*The serialization of the threads do not work with the mutex

*The call to pthread_mutex_destroy() before waiting for the end of the threads makes the latter probably use destroyed mutexes

Here is a proposal to serialize the threads with condition variables and to terminate properly using pthread_join():
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define NUMTHRDS 2
pthread_t t [ NUMTHRDS];
pthread_mutex_t m1, m2;
int x = 0;
pthread_cond_t cond1, cond2;
int gen, prt;

void *thread1(void *arg){
  for(int i = 0 ; i < 5 ; i++){
    pthread_mutex_lock(&m1);
    if (!gen) {
      pthread_cond_wait(&cond1, &m1);
    }

    x = (rand() % 10) + 1; // generates a random number between 1 and 10
    printf("generator >> x = %d\n" , x);

    gen = 0;
    pthread_mutex_unlock(&m1);

    // Wake up printer
    pthread_mutex_lock(&m2);
    prt = 1;
    pthread_cond_signal(&cond2);
    pthread_mutex_unlock(&m2);

  }
}

void * thread2(void * arg){
  for(int i = 0 ; i < 5 ; i++){
    pthread_mutex_lock(&m2);
    if (!prt) {
      pthread_cond_wait(&cond2, &m2);
    }
    printf("printer >> x = %d\n" , x);
    pthread_mutex_unlock(&m2);

    prt = 0;
    pthread_mutex_unlock(&m2);

    // Wake up generator
    pthread_mutex_lock(&m1);
    gen = 1;
    pthread_cond_signal(&cond1);
    pthread_mutex_unlock(&m1);
  }
}

int main(void)
{
  srand(time(NULL));

  pthread_mutex_init(&m1, NULL);
  pthread_mutex_init(&m2, NULL);

  pthread_cond_init(&cond1, NULL);
  pthread_cond_init(&cond2, NULL);

  pthread_create(&t[1], NULL, thread1, NULL);
  pthread_create(&t[0], NULL, thread2, NULL);

  // Wake up generator
  printf("Waking up generator...\n");
  pthread_mutex_lock(&m1);
  gen = 1;
  pthread_cond_signal(&cond1);
  pthread_mutex_unlock(&m1);

  pthread_join(t[0], NULL);
  pthread_join(t[1], NULL);

  pthread_mutex_destroy(&m1);
  pthread_mutex_destroy(&m2);

  pthread_cond_destroy(&cond1);
  pthread_cond_destroy(&cond2);

  return 0;

}

A: Not a complete answer, but I just wanted to explicitly say something that is implicit in other answers.

...how to use mutexes correctly in order to maintain the order between these two threads...

That is not the purpose of mutexes. Mutexes are the wrong tool for that.
The lowest-level tool that you can use when you want one thread to wait for another to do something is called a condition variable. In the posix threads library (pthreads), you use a pthread_cond_t variable, and various pthread_cond_...(...) functions that operate on it:
https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread.h.html

But also note: There are well-established, higher level patterns that people usually use for solving your type of problem. E.g., Google for "blocking queue."

A: According to most of the answers and comments to this question I believe that mutexes are not the correct tool for maintaining the order between two threads. However, by the help of my instructor he shown me a trick that would work with such problem and the trick is by initially locking one of the critical sections ( critical section to be executed by thread 2 ) then unlock that one within the other thread ( thread 1 )
and this how the new code looks like
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define NUMTHRDS 2
pthread_t t [ NUMTHRDS];
pthread_mutex_t m1, m2;
int x = 0;

void *thread1(void *arg){
        pthread_mutex_lock(&m1);
        x = (rand() % 10) + 1; // generates a random number between 1 and 10
        printf("generator >> x = %d\n" , x);
        // 2- unlock the critical section of the printing thread
        pthread_mutex_unlock(&m2);
}

void * thread2(void * arg){
        pthread_mutex_lock(&m2);
        printf("printer >> x = %d\n" , x);
        pthread_mutex_unlock(&m1);
}

int main(void)
{
    srand(time(NULL));

    pthread_mutex_init(&m1, NULL);
    pthread_mutex_init(&m2, NULL);
    // 1- locking the critical section of the printing thread
    pthread_mutex_lock(&m2);
    for(int i = 0 ; i < 5 ; i++) {
        pthread_create(&t[1], NULL, thread1, NULL);
        pthread_create(&t[0], NULL, thread2, NULL);
    }

    pthread_exit(NULL);

    pthread_mutex_destroy(&m1);
    pthread_mutex_destroy(&m2);

    return 0;

}


text:
Q: zoom jpeg image on canvas with mousewheel event in javascript I have written simple code in java script which adds JPEG image on canvas & add line on that image with simple mousedown & mouseup event. Now i wanted to add zoom-in & zoom-out effect on that image.can anybody help me out?
my js file looks as below.
var canvas;
var context;
var width;
var height;
var finalPos = {x: 0, y: 0};
var startPos = {x: 0, y: 0};

function main() {

    canvas = document.getElementById('imageCanvas');
    context = canvas.getContext('2d');
    loadImage();

    width = canvas.width;
    height = canvas.height;

    var canvasOffset = $('#imageCanvas').offset();
    function line(cnvs) {
        cnvs.beginPath();
        cnvs.moveTo(startPos.x, startPos.y);
        cnvs.lineTo(finalPos.x, finalPos.y);
        cnvs.stroke();
    }

    $('#imageCanvas').mousedown(function (e) {
        context.strokeStyle = 'blue';
        context.lineWidth = 5;
        context.lineCap = 'round';
        context.beginPath();
        startPos = {x: e.pageX - canvasOffset.left, y: e.pageY - canvasOffset.top};
    });

    $('#imageCanvas').mouseup(function (e) {
        // Replace with var that is second canvas
        finalPos = {x: e.pageX - canvasOffset.left, y: e.pageY - canvasOffset.top};
        line(context);
    });
}
;

function loadImage() {
    system_image = new Image();
    system_image.src = 'img/Google_OH_406TwentySecondStreet.jpg';

    system_image.onload = function () {
        context.drawImage(system_image, 0, 0, width, height);
    };
}

A: You can use scale function on mousewheel
context.scale(scaleValue, scaleValue);

You must do that before drawimage on context.
I have created the example here: [link]: http://jsfiddle.net/itsjawad/5wohz3r1/


text:
Q: PHP Delete record from database MySql I need to delete a record, in this case a categories from my forum, from the database based on its id.
<?php
    if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
    {
?>

        <form method="post">
            <input type="hidden" value="<?= ['cat_id']; ?>">
            <input type="submit" name="submit" value="Remover" />
        </form>
    <?php
        if(isset($_POST['submit']))
        {
            mysql_query("DELETE FROM categories where cat_id = 'cat_id'");
        }
    ?>

<?php
}
?>

i cant get a "good" way to do it... :(
EDIT: This is for a programming lesson not a real forum!!

A: Your HTML Input Field needs a name so it can be identified by your PHP.
Then, in your Code Block where you attempt to delete the category, you need to acces the category id using the $_POST array.
Another thig you want to do is read up onj the dangers of SQL injections.
If you're just playing around with PHP and MySQL at the moment: Go Ahead. But if you actually want to develop, maybe you should read up on a few other things as well, even if it seems like overkill at first: PHP The Right Way.
Nontheless, try this:
    <?php
        if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
        {
    ?>

            <form method="post">
                <input type="hidden" name="hid_catid" id="hid_catid" value="<?php  echo $cat_id; ?>">
                <input type="submit" name="submit" value="Remover" />
            </form>
        <?php
            if(isset($_POST['submit']))
            {

$query = "DELETE FROM categories where cat_id = '".(int)$_POST['hid_catid']."'";
mysql_query($query);
            }
        ?>

    <?php
    }
    ?>

--> hidden field should have name and id to use
--
Thanks

A: Your hidden input field needs a name to be accessable after the post. Also I am not sure if ['cat_id'] is the correcty way to reference this variable. Where does it come from?
<form method="post">
    <input type="hidden" name="cat_id" value="<?= $cat_id ?>">
    <input type="submit" name="submit" value="Remover" />
</form>

Then your query has to look like this to correctly grab the id from the post.
mysql_query("DELETE FROM categories where cat_id = " . mysql_real_escape_string($_POST['cat_id']));


text:
Q: Ruby Hash deeply nested hash with arrays traversal I have a deeply nested hash with arrays mixed in. the hash represent a graph like relationship. each node can have one or more connections to the next.
Inputs/output:
examples:
Given {'id' => biology}
results_should_be: {'biology' => {'id' => biology, 'paths' => [[{'id' => biology}]]}}

    Given {'id'=> biology, 'children' =>[{'id' => microbiology}, {'id' => physicalbio}]}
    results_should_be:
            {'biology' => {'id' => biology, 'paths' => [['id' => biology]]},
             "microbiology"=>{"id" => "microbiology", "paths" => [[{"id" => "biology"}, {"id" => "microbiology"}]]},
             "physicalbio"=>{"id" => "physicalbio", "paths" => [[{"id" => "biology"}, {"id" => "physicalbio"}]]}

    Given {'id'=> biology, 'children' =>[{'id' => microbiology, 'children' => [{'id' => physicalbio},{"id" => "physicalbio"}]}}
    results_should_be:
            {'biology' => {'id' => biology, 'paths' => [['id' => biology]]},
             "microbiology"=>{"id" => "microbiology", "paths" => [{"id" => "biology", "id" => "microbiology"}]},
             "physicalbio"=>{"id" => "physicalbio", "paths" => [[{"id" => "biology"}, {"id" => "physicalbio"}][{"id" => "biology"}, {"id" => "microbiology"},{"id" => "physicalbio"}]]}

My failing test result
 {"biology"=>{"id"=>"biology", "paths"=>[[{"id"=>"biology"}]]},
 "microbiology"=>
         {"id"=>"microbiology",
          "children"=>[{"id"=>"physicalbio", "paths"=>[[{"id"=>"microbiology"}, {"id"=>"physicalbio"}], [{"id"=>"biology"}, {"id"=>"microbiology"}, {"id"=>"physicalbio"}]]}],
          "paths"=>[[{"id"=>"biology"}, {"id"=>"microbiology"}]]},
 "physicalbio"=>{"id"=>"physicalbio", "paths"=>[[{"id"=>"biology"}, {"id"=>"physicalbio"}]]}}

code block
 def build_concept_with_paths(concept,parent_id=nil)
    concept['paths'] = []
    parent_id.nil? ? concept['paths'] << [concept['id']] : concept['paths'] << [{'id' => parent_id}, {'id' =>concept['id']}]
    concept
end

 def build_concept_data(concepts)
  concepts.keys.first(2).each_with_object({}) do |k,data|
      if k == 'children'
            concepts[k].each do |concept|
                child = build_concept_with_paths(concept,concepts['id'])
                data[child['id']] = child
                if concept['children']
                    build_concept_data(child)
                end
            end
            concept_id = concepts[k]
            concept = {'id' => concept_id,'paths' => [[{'id' => concept_id }]] }
            data[concepts[k]] = concept
      end
  end
end

My recursive call, doesn't seem to affect the final results, Im unable to return the results from the recursion. Any help would be great.