text:
Q: Reactive - Improve Mono syntax I have this block of code that works fine:
return isBlacklistedToken(refreshToken, Boolean.TRUE).flatMap(isBlacklisted -> {
    if (isBlacklisted)
        return Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username)));
    else
        return isBlacklistedToken(accessToken, Boolean.FALSE).flatMap(isABlacklisted -> {
            if (isABlacklisted)
                return Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username)));
            else
                return blacklistTokens(username, refreshToken, accessToken);
        });
});

To summarize it:

*

*calls the isBlacklistedToken function (returns a Mono<Boolean> with the result of the refresh token)

*If the refresh token is blacklisted, throws an UnauthorizedException

*If the refresh token is not blacklisted, does the same process for the access token

*If both tokens are not blacklisted, finally blacklists them.

This syntax, while it works, seems a bit sloppy. Is there a way to improve that? I wrote this piece of code, and while it throws an exception, the last part (blacklisting the tokens) always executes - peraphs my knowledge of reactive programming is a bit off.
return isBlacklistedToken(refreshToken, Boolean.TRUE)
                .flatMap(isBlacklisted -> isBlacklisted ? Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))) : Mono.empty())
                .then(isBlacklistedToken(accessToken, Boolean.FALSE))
                .flatMap(isBlacklisted -> isBlacklisted ? Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))) : Mono.empty())
                .then(blacklistTokens(username, refreshToken, accessToken));

Edit: adding the isBlacklistedToken method
private Mono<Boolean> isBlacklistedToken(final String token, final Boolean type) {

        return blacklistService.isBlacklisted(token, type);
    }

and the respective blacklistService call (just a repository call, really simple)
public Mono<Boolean> isBlacklisted(final String token, final Boolean isRefresh) {
        return Mono.just(this.blacklistRepository.existsBlacklistByTokenAndIsRefresh(token, isRefresh));
    }

A: I would suggest the following:
return isBlacklistedToken(refreshToken, Boolean.TRUE)
    .filter(isBlacklisted -> !isBlacklisted)
    .flatMap(isBlacklisted -> isBlacklistedToken(accessToken, Boolean.FALSE))
    .filter(isBlacklisted -> !isBlacklisted)
    .flatMap(isBlacklisted -> blacklistTokens(username, refreshToken, accessToken))
    .switchIfEmpty(Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))));

Sorry if there is some compile error but I tried this in Kotlin and needed to translate it to Java, which is become less and less easy.


text:
Q: How to exclude posts by ID within a category/archive loop I would like to exclude the current "page" (not post) from a categroy loop :
files :
archive.php,
content.php,
content-top-page.php (page template)
I have created 2 categories (archive.php) and releated 2 posts to each category. I have included "content-top-page.php" at the top of the category. Those are "pages" and I don't want them to change (a title, a post thumbnail and a specific text, that's all).
The problem :
The template pages are being displayed within the loop with the other posts. The current template page of each category is being included in. I am using specific ACF variables in the template pages.
Thanks if you have some ideas.
Archive.php
$exclude_ids = array( 45, 36 );

$my_query = new WP_Query(array(
    'exclude' => $exclude_ids,
    'post_type' => 'post',
    'post_status' => 'publish',

));

    if ( have_posts() ) : ?>

            <?php
                get_template_part('content','top-page');

            ?>

            <?php while ( $my_query->have_posts() ) : $my_query->the_post();

                    <?php get_template_part( 'template-parts/content',
  get_post_format() );
                    ?>

            <?php endwhile; ?>

    <?php endif;

    wp_reset_postdata(); ?>

content-top-page.php (template page)
<?php if ( has_category('my_category_1') ): ?>

<?php the_title(); ?>

        <img src="<?php get_field('top_profil_featured_image'); ?>" />

        <?php echo get_field('top_profil_content'); ?>

<?php endif ?>

<?php if ( has_category('my_category_2') ): ?>

<?php the_title(); ?>

        <img src="<?php get_field('top_profil_featured_image'); ?>" />

        <?php echo get_field('top_profil_content'); ?>

<?php endif ?>

content.php
<article id="post-<?php the_ID(); ?>" class="" <?php post_class(); ?> style="border:1px solid #6f3fa5;">

<?php
    if ( !is_single() && has_post_thumbnail() ) { ?>

            <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('blog-way-common'); ?>

    <?php
}
?>

        <?php

            if( is_single() ){

                the_content( sprintf(
                    /* translators: %s: Name of current post. */
                    wp_kses( __( 'Continue reading %s →', 'blog-way' ), array( 'span' => array( 'class' => array() ) ) ),
                    the_title( '"', '"
 ', false )) );

                wp_link_pages( array(
                    'before' => '
' . esc_html__( 'Pages :', 'blog-way' ),
                    'after'  => '
',
                ) );

            } else {

                echo excerpt_custom_length(20);

            }

        ?>

A: Use pre_get_posts to exclude the categories you don't want to display in the loop.
function exclude_posts_from_specific_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-2' );
    }
}
add_action( 'pre_get_posts', 'exclude_posts_from_specific_category' );

Or create a new WP_Query and use the Category Parameters.
$args = array(

'category__not_in' => 2 ,

'category__in' => 4

);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
        echo '
';
        while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '
' . get_the_title() . '
';
    }
        echo '
';
} else {

}

wp_reset_postdata();

If you only want to display posts from one category, you would use the category archive.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot import PIL into Python Shell, but can into Terminal I have installed Pillow on may Macintosh using sudo pip install Pillow in Terminal. I know it is installed because whenever I run import PIL in the Terminal window after typing python, this is my output:
Terminal output:
Python 3.5.1 |Anaconda 2.4.1 (x86_64)| (default, Dec  7 2015, 11:24:55)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>>

However, the weird thing is that in the Python Shell, when i do the same thing, I get this:
Python Shell (IDLE) output:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> import PIL
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import PIL
ImportError: No module named 'PIL'

Why is it that I can import the Python Imaging Library (PIL) in the Macintosh Terminal, but not in the Python Shell, and how would I fix this issue?

A: You should never use sudo to install a python module.
When you have multiple versions of python installed, each one has its own name, its own pip, and its own IDLE. The command you issue on the command line determines which python will launch. One of the versions of python that you installed will be linked to the name python while other versions will have a name that includes the version, e.g. python3.5.
To keep straight which version of python you are launching, you can launch python with its version name, python3.5, execute pip with its version name, pip3.5, and start IDLE with its version name, idle3.5.
Here are some commands that will help you figure out where pip install Pillow is installing modules:
~$ which pip
/usr/local/bin/pip

~$ cd /usr/local/bin

/usr/local/bin$ ls -al pip*
    lrwxrwxr-x  1 root  admin  65 Apr 10  2015 pip ->
 ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip
    lrwxrwxr-x  1 root  admin  66 Apr 10  2015 pip2 ->
 ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip2
    lrwxrwxr-x  1 root  admin  68 Apr 10  2015 pip2.7 ->
 ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip2.7
    lrwxrwxr-x  1 root  admin  66 Apr  7  2015 pip3 ->
 ../../../Library/Frameworks/Python.framework/Versions/3.4/bin/pip3
    lrwxrwxr-x  1 root  admin  68 Apr  7  2015 pip3.4 ->
 ../../../Library/Frameworks/Python.framework/Versions/3.4/bin/pip3.4

The syntax pip -> means that the name pip is linked to the file after the arrow.  You can see where those names are pointing and therefore which python that pip is installing modules into.
===
You have Anaconda installed, and Anaconda hijacks the names python and pip for its own use, so you will see something like this:
~$ which python
/Users/7stud/anaconda/bin/python

~$ which pip
/Users/7stud/anaconda/bin/pip

Anaconda does not hijack the name idle, so idle points to another python install:
~$ which idle
/usr/local/bin/idle

~$ cd /usr/local/bin

/usr/local/bin$ ls -al idle*
    lrwxr-xr-x  1 root  wheel  66 Apr 10  2015 idle ->
 ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/idle
    lrwxr-xr-x  1 root  wheel  67 Apr 10  2015 idle2 ->
 ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/idle2
    lrwxr-xr-x  1 root  wheel  69 Apr 10  2015 idle2.7 ->
 ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/idle2.7
    lrwxr-xr-x  1 root  wheel  67 Apr  7  2015 idle3 ->
../../../Library/Frameworks/Python.framework/Versions/3.4/bin/idle3
    lrwxr-xr-x  1 root  wheel  69 Apr  7  2015 idle3.4 ->
../../../Library/Frameworks/Python.framework/Versions/3.4/bin/idle3.4

Anaconda hijacks the names python and pip by adding the following line to the end of the file ~/.bash_profile:
export PATH="/Users/7stud/anaconda/bin:$PATH"

When you issue a command on the command line, the terminal window searches for that command in the directories specified in your PATH environment variable--in order.  Because the Anaconda path is on the front of the PATH variable, the Anaconda directory is searched first for the commands python and pip and idle.  The python command is found in that directory:
~$ which python
/Users/7stud/anaconda/bin/python

~$ cd /Users/7stud/anaconda/bin/

~/anaconda/bin$ ls -al python*
lrwxr-xr-x  1 7stud  staff     9 Dec 22 05:29 python -> python3.5
-rwxrwxr-x  1 7stud  staff   272 Dec 22 05:29 python-argcomplete-check-easy-install-script
-rwxrwxr-x  1 7stud  staff   129 Dec 22 05:29 python.app
lrwxr-xr-x  1 7stud  staff     9 Dec 22 05:29 python3 -> python3.5
lrwxr-xr-x  1 7stud  staff    17 Dec 22 05:29 python3-config -> python3.5m-config
-rwxrwxr-x  1 7stud  staff  9096 Dec  7 10:27 python3.5

(In addition to the name python, you can also see the names python3 and python3.5.  Because python and python3 both point to python3.5, the commands python, python3, and python3.5 all execute the same python.)
The pip command is also found in the Anaconda directory:
$ which pip
/Users/7stud/anaconda/bin/pip

$ cd /Users/7stud/anaconda/bin

~/anaconda/bin$ ls -al pip*
-rwxrwxr-x  1 7stud  staff  125 Dec 22 05:29 pip

There's only one name for pip.
But, the idle command is not found in the Anaconda directory:
~$ which idle
 /usr/local/bin/idle

Double checking:
~$ cd ~/anaconda/bin

~/anaconda/bin$ ls -al idle*
lrwxr-xr-x  1 7stud  staff    7 Dec 22 05:29 idle3 -> idle3.5
-rwxrwxr-x  1 7stud  staff  108 Dec 22 05:29 idle3.5

The name idle is not the same as idle3 or idle3.5, so the search for idle continues on in the other directories in the PATH variable.  If you want to launch the Anaconda idle, you can use either the name idle3 or idle3.5.
Because I hate the way Anaconda hijacks all those python names, which prevents me from using those names to run my other python versions, when I'm not using Anaconda I comment out the following line in ~/.bash_profile:
# export PATH="/Users/7stud/anaconda/bin:$PATH"

To get changes you make in ~./bash_profile to take effect, you need to either close the terminal window and launch a new window, or issue the command:
$ source ~/.bash_profile

Another way to keep Anaconda from hijacking all those python names is by doing the following:
~/anaconda/bin$ mv python xpython  #change the name to xpython
~/anaconda/bin$ mv python3 xpython3
~/anaconda/bin$ cp python3.5 pyana  #copy to a new name
~/anaconda/bin$ mv python3.5 xpython3.5

That preserves all the original names under pseudonyms (in case something goes wrong you can change the x-names back to the originals), and it also creates the name pyana for your Anaconda python.  Now the names python, python3, etc. will still point to the same python versions they did before you installed Anaconda:
~/anaconda/bin$ which python
/usr/local/bin/python

~/anaconda/bin$ which python3
/usr/local/bin/python3

~/anaconda/bin$ which pyana
/Users/7stud/anaconda/bin/pyana

~/anaconda/bin$ pyana --version
Python 3.5.1 :: Anaconda 2.4.1 (x86_64)

~/anaconda/bin$ pyana
Python 3.5.1 |Anaconda 2.4.1 (x86_64)| (default, Dec  7 2015, 11:24:55)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Edit: Some time later I found that openssl is found in Anaconda's directory as well, so I've gone back to commenting out the line in .bash_profile when I'm not using Anaconda--Anaconda just hijacks too many names.


text:
Q: Status update post I'm building a social media website and I'm getting this error with my code when users type in to add a new post it'll show up and stay is there a way to fix this issue? I've been dealing with this for several days and can't figure it out. My friend can't figure it out either what are we doing wrong.

var main = function() {
  $('.btn').click(function() {
    var post = $('.status-box').val();
    $('
').text(post).prependTo('.posts');
    $('.status-box').val('');
    $('.counter').text('140');
    $('.btn').addClass('disabled');
  });

  $('.status-box').keyup(function() {
    var postLength = $(this).val().length;
    var charactersLeft = 140 - postLength;
    $('.counter').text(charactersLeft);

    if(charactersLeft < 0) {
      $('.btn').addClass('disabled');
    }
    else if(charactersLeft == 140) {
      $('.btn').addClass('disabled');
    }
    else {
      $('.btn').removeClass('disabled');
    }
  });

  $('.btn').addClass('disabled');
}

$(document).ready(main);
html,
body {
  font-family: 'Roboto', sans-serif;
  color: #404040;
  background-color: #eee;
}

.container {
  width: 520px;
  margin-top: 20px;
}

.button-group {
  margin-bottom: 20px;
}

.counter {
  display: inline;
  margin-top: 0;
  margin-bottom: 0;
  margin-right: 10px;
}

.posts {
  clear: both;
  list-style: none;
  padding-left: 0;
  width: 100%;
}

.posts li {
  background-color: #fff;
  border: 1px solid #d8d8d8;
  padding-top: 10px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 10px;
  margin-bottom: 10px;
  word-wrap: break-word;
  min-height: 42px;
}

      <form>

          <textarea class="form-control status-box" rows="2" placeholder="Blurt to friends?..."></textarea>

      </form>

140

        Blurt


text:
Q: AzureDevops Nuget Pack I have a .net class library project (4.7.2) which will be built on an AzureDevops instance. In the build pipeline one step is to create a nuget package based on the corresponding *.csproj file. Within the class library project there are folders. Now when the nuget package is created the nuget package also contains the folders of the project and not only the created *.dll file. How can I avoid having the folders of the project in the created Nuget package?

A: To explicitly control which files are included in a package, you can specify files tag in .nuspec fule.
<files>
    <file src="bin\Debug\*.dll" target="lib" />
    <file src="bin\Debug\*.pdb" target="lib" />
    <file src="tools\**\*.*" exclude="**\*.log" />
</files>

Check here for more information


text:
Q: Remove country billing and shipping fields on admin add order in Woocommerce In the admin, when you click Add Order, I can't figure out how to remove the billing & shipping country fields.  I don't want to use CSS to just hide the fields because I need the country hidden when viewing the order on the frontend (form-pay.php).
I tried the following normal way of removing those fields from checkout but it has no effect here.
function custom_checkout_fields( $fields ) {
    unset($fields['billing']['billing_country']);
    return $fields;
}

add_filter('woocommerce_checkout_fields' , 'custom_checkout_fields');

A: To remove shipping and billing country fields on admin add new order page, you will use the following:
// Admin billing fields
add_filter( 'woocommerce_admin_billing_fields', 'custom_admin_billing_fields', 10, 1 );
function custom_admin_billing_fields( $billing_fields ) {
    global $pagenow;
    if( $pagenow === 'post-new.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order' ){
        unset($billing_fields['country']); // remove billing country field
    }
    return $billing_fields;
}

// Admin shipping fields
add_filter( 'woocommerce_admin_shipping_fields', 'custom_admin_shipping_fields', 10, 1 );
function custom_admin_shipping_fields( $shipping_fields ) {
    global $pagenow;
    if( $pagenow === 'post-new.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order' ){
        unset($shipping_fields['country']); // remove shipping country field
    }
    return $shipping_fields;
}

This code goes on function.php file of your active child theme (or theme). Tested and works.


text:
Q: Adding attribute on object during run time not happening I try to add attributes on a certain object. This object can be int, string, List or whatever.
I try to use
TypeDescriptor.AddAttributes(object, attrList.ToArray());
but this list of attributes do not show up when I do:
object.GetType().GetCustomAttributes(false)
How come?
Best regards,
Gabriel Paulsson

A: Unfortunately this method does not dynamically change the metadata of the type, ultimately it only gives you back a TypeDescriptor which includes the attributes you added.
You need to keep the return value of the AddAttributes method and query from there instead...
var myObject = { ... }

var typeDescriptionProvider = TypeDescriptor.AddAttributes(myObject, attrList.ToArray());

var attributes = typeDescriptionProvider.GetTypeDescriptor(myObject).GetAttributes();

You can think of the type descriptor as a union of the type metadata itself (fixed), and any meta data you added at runtime (dynamic).


text:
Q: HIve subquery in where clause i am new to hive please help me, i have a table name prac and i need to
find the products which give more profit(price-cost) than product Mouse. I have tried the below query but it is not working.
select product_name,price-cost
from   prac
where  price-cost > (select price-cost from prac where product_name='mouse')

and my data is
id,product_name,product_type,price,cost,date
100,maker,stationary,25,22,2008-01-15
101,mouse,computer,450,350,2009-04-16
102,white  board,stationary,450,375,2010-06-25
103,sony viao,computer,35000,42000,2010-09-21

A: I got the Answer
select a.*,a.price-a.cost profit
from prac a
join (select price-cost p from prac where p_name='Maker') b
where a.price-a.cost>b.p;


text:
Q: Set collection object property when deserializing XML in C# I have XML in the following format:
<LocationHierarchy>
    <Location name="Argentina" id="3">
        <Location name="Buenos Aires" id="4"/>
        <Location name="Cordoba" id="5"/>
        <Location name="Mendoza" id="6"/>
    </Location>
    ...
</LocationHierachy>

I have C# code that is deserializing this XML into the following classes:
[XmlRoot("LocationHierarchy")]
[Serializable]
public class LocationHierachy
{
    [XmlElement("Location", typeof(Country))]
    public List<Country> CountryList { get; set; }
}
public class Country
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("id")]
    public int Id { get; set; }
    [XmlElement("Location", typeof(City))]
    public List<City> CityList { get; set; }
}
public class City
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("id")]
    public int Id { get; set; }
    public int CountryId { get; set; }
}

I have this working fine. However, I would like to automatically set the CountryId of each City object to the Id of the Country object that contains its collection. Any thoughts as to how this could be achieved?

A: public class LocationHierachy
    {
        [XmlElement("Location", typeof(Country))]
        public List<Country> CountryList { get; set; }

        [OnDeserialized()]
        internal void OnDeserializedMethod(StreamingContext context)
        {
            foreach (var country in CountryList)
            {
                foreach (var city in country.CityList) {
                    city.CountryId = country.Id;
                }
            }
        }
    }


text:
Q: csscript - catch runtime errors I'm using CSScript (www.csscript.net) which works wonderful to easily compile and run scripts. In my case I use the LoadCode method:
ClassInstance = CSScript.Evaluator.LoadCode<IRandomInterface>(sometext);

I use a try-catch block around this line and I can easily catch/display compiler errors. But what about runtime errors? I there a way to catch them, too?
Many thanks

A: Don't worry. I found out that I have to handle an TargetInvocationException seperatly. In this case the InnerException included the exception I wanted to catch.


text:
Q: Can i define constructor and private variables in Observer? I have two methods in my observer defined in config.xml.
If i want to add other methods in the observer.php that they will not catch any event:
Should i define them to config.xml?
And If i put some variables like private $myvar will I be able to use them?
Can I use a constructor?

A: An observer in Magento is a class like any other. You can add constructors, private variables or any other class element that takes your fancy and you do not have to add these to the config.xml.
For example, you could make an observer class like this:
<?php
class Companyname_Modulename_Model_Observer {

  private $monkey = 'hi, I am a monkey';

  public function __construct() {
    $this->monkey = 'hi, I am still a monkey';
  }

  public function myObserverFunction($observer) {
    var_dump($this->showMonkeyString());
  }

  private function showMonkeyString() {
    return $this->monkey;
  }
}

In config.xml, you only add the function that you want to execute when your event occurs, something like:
  <frontend>
        <events>
            <catalog_category_load_after>
                <observers>
                    <does_not_matter_what_we_call_this_tag>
                        <type>singleton</type>
                        <class>Companyname_Modulename_Model_Observer</class>
                        <method>myObserverFunction</method>
                    </does_not_matter_what_we_call_this_tag>
                </observers>
            </catalog_category_load_after>
        </events>
    </frontend>

The output when you load a random category in your store will be 'hi, I am still a monkey'.

A: An observer is a PHP class.
Only constraint is that function(Method) name you have entered while associating it with an event should be there.
Apart from that you can do whatever PHP allows.

A: You can use constructor in Observer
See following Observer classes in Magento1
class Mage_CatalogIndex_Model_Observer extends Mage_Core_Model_Abstract
{
    protected $_parentProductIds = array();
    protected $_productIdsMassupdate = array();

    protected function _construct() {}

and
class Mage_Rss_Model_Observer
{
    /**
     * Factory instance
     *
     * @var Mage_Core_Model_Abstract
     */
    protected $_factory;

    /**
     * Application instance
     *
     * @var Mage_Core_Model_App
     */
    protected $_app;

    /**
     * @param array $args
     */
    public function __construct(array $args = array())
    {
        $this->_factory = !empty($args['factory']) ? $args['factory'] : Mage::getSingleton('core/factory');
        $this->_app = !empty($args['app']) ? $args['app'] : Mage::app();
    }


text:
Q: How to get min max day in a week every month? I want to make something a value that outputs a date of first day in the week and last one in the week respectively. For example:
In february a week one from monday to sunday there will be a date 1 - 7, and week two from monday to sunday there will be date 8 - 14, and so on until the last day of month.
Here for example is the result that I want as list

Here is my code that I tried to produce but it's giving wrong output:
                ListWeek week;
                List<ListWeek> listWeek =new  List<ListWeek>();

                var mins = listCrews[0].days;
                var maxs = 0;

                for (int rows = 0; rows < listCrews.Count; rows++)
                {
                    week = new ListWeek();
                    var weeknumbers = listCrews[rows].weeks;
                    var dayNumbers = listCrews[rows].days;

                    week.weeknumber = weeknumbers;
                    if(rows == 0)
                    {
                        week.days_min =  dayNumbers;
                        week.days_max = dayNumbers;
                    }else{
                        if(dayNumbers < mins)
                        {
                            mins = dayNumbers;
                            week.days_min = mins;
                            week.days_max = maxs;
                        }else if(dayNumbers > maxs)
                        {
                            maxs = dayNumbers;
                            week.days_min = mins;
                            week.days_max = maxs;
                        }
                        else{
                            week.days_min = dayNumbers;
                            week.days_max = dayNumbers;
                        }
                    }

                    week.month = listCrews[rows].month_name;
                    week.year = listCrews[rows].year;

                    if(!listWeek.Contains(week))
                    {
                        listWeek.Add(week);
                    }
                }

               // i tried to check it
               foreach (var weekly in listWeek)
               {
                    Console.WriteLine("here "  + weekly.weeknumber + " " + weekly.days_min+ " " + + weekly.days_max);
               }

and here is the example json (I have just included one because it's too long)
 [
   {
    "days": 1,
    "days_name": "Monday",
    "weeks": 1,
    "month": 2,
    "month_name": "February",
    "year": 2021,
   },
   {
    "days": 2,
    "days_name": "Thursday",
     ....
   }
 ]

every list crews has a json from days, listcrews 0 days is 1 and listcrews 1 days is 2 and so on, according to february days because it's started from monday
and through my code i only produce this

How can i complete this??

A: As I suggested in my comment, this is much easier if you use DateTime objects. Anytime you have to deal with dates or times… Use a DateTime object. I posted a couple of links in my comment.
The code below simply loops through each day of the given month/year. If the "day of the week" for that date is either a StartingDayOfWeek or EndingDayOfWeek then print that day. Some additional code for checking end and boundary cases.
Edit...
An additional check is needed if the last day of the month falls on the StartingDayOfWeek. In which case the last day would be both the min and max.
private const DayOfWeek StartingDayOfWeek = DayOfWeek.Monday;
private const DayOfWeek EndingDayOfWeek = DayOfWeek.Sunday;

static void Main(string[] args) {
  DisplayWeekDatesFromGivenMonthYear(2, 2021);
  Console.ReadKey();
}

private static void DisplayWeekDatesFromGivenMonthYear(int month, int year) {
  DateTime tempDT = new DateTime(year, month, 1);
  Console.WriteLine("Date " + tempDT.ToShortDateString() + "----");
  int curWeek = 1;
  while (tempDT.Month == month) {
    // is this day the 1st or any date that is the starting day of the week
    if (tempDT.Date.Day == 1 || tempDT.DayOfWeek == StartingDayOfWeek) {
      Console.WriteLine("Week " + curWeek + "----");
      Console.Write("  min: " + tempDT.Day);
      if (tempDT.DayOfWeek == EndingDayOfWeek ||
          tempDT.Date.Day == DateTime.DaysInMonth(year, month)) {
        Console.WriteLine("  max: " + tempDT.Day);
        curWeek++;
      }
    }
    else {
      // is this day at the end of the week
      if (tempDT.DayOfWeek == EndingDayOfWeek) {
        Console.WriteLine("  max: " + tempDT.Day);
        curWeek++;
      }
      else {
        // check for last day in month
        if (tempDT.Date.Day == DateTime.DaysInMonth(year, month)) {
          Console.WriteLine("  max: " + tempDT.Day);
        }
      }
    }
    tempDT = tempDT.AddDays(1);
  }
}

A: I solved it but, i hope there is someone who can make my code shorter
here is my code
               var mins = listCrews[0].days;
                var maxs = 0;

                for (int rows = 0; rows < listCrews.Count; rows++)
                {
                    week = new ListWeek();
                    var weeknumbers = listCrews[rows].weeks;
                    var dayNumbers = listCrews[rows].days;

                    week.weeknumber = weeknumbers;
                    if (rows == 0)
                    {
                        week.days_min = dayNumbers;
                        week.days_max = dayNumbers;
                    }
                    else
                    {
                        if (weeknumbers != listCrews[rows - 1].weeks)
                        {
                            mins = maxs + 1;
                            if (dayNumbers < mins)
                            {
                                mins = dayNumbers;
                                week.days_min = mins;
                                week.days_max = maxs;
                            }
                            else if (dayNumbers > maxs)
                            {
                                maxs = dayNumbers;
                                week.days_min = mins;
                                week.days_max = maxs;
                            }
                            else
                            {
                                week.days_min = dayNumbers;
                                week.days_max = dayNumbers;
                            }
                        }
                        else
                        {
                            if (dayNumbers < mins)
                            {
                                mins = dayNumbers;
                                week.days_min = mins;
                                week.days_max = maxs;
                            }
                            else if (dayNumbers > maxs)
                            {
                                maxs = dayNumbers;
                                week.days_min = mins;
                                week.days_max = maxs;
                            }
                            else
                            {
                                week.days_min = dayNumbers;
                                week.days_max = dayNumbers;
                            }
                        }
                    }

                    week.month = listCrews[rows].month_name;
                    week.year = listCrews[rows].year;

                    if (!listWeek.Contains(week))
                    {
                        listWeek.Add(week);
                    }
                }
                NewListWeek:

                for (int rows = 0; rows < listWeek.Count; rows++)
                {
                    if(rows != 0)
                    {
                        if(listWeek[rows -1].weeknumber == listWeek[rows].weeknumber && listWeek[rows -1].days_max < listWeek[rows].days_max)
                        {
                            listWeek.Remove(listWeek[rows-1]);
                            goto NewListWeek;
                        }
                    }
                }

                foreach (var weekly in listWeek)
                {
                    Console.WriteLine("here " + weekly.weeknumber + " " + weekly.days_min + " " + +weekly.days_max + " " + weekly.month + " " + weekly.year);
                }

and here is the result


text:
Q: Is it possible to make a div that is not rounded or square shaped with html and css? I have received a design which i am pretty sure is a flash website yet the company is convinced that it is doable in html, the design
Any feedback would be nice.

A: It is doable indeed, but if you intend to support older browsers, like IE8, you will have to make use of transparent PNG-images that you use as backgrounds on the elements, in order to create the tilted effect on the elements.
If you don't need to support older browsers, you can have a look att CSS3 transform.

A: make images for those backgrounds, and make them background images of the divs on which you wish to present content.

A: Could you do something like this:
   #parallelogram {
      width: 130px;
      height: 75px;
      background: pink;
      /* Skew */
      -webkit-transform: skew(20deg);
      -moz-transform: skew(20deg);
      -o-transform: skew(20deg);
      transform: skew(20deg);
   }

==edit==
Ok, so unskew the text part:

inner text

A: You could also do something like this: http://jsfiddle.net/vYU7N/2/
It's using different sized borders to create the diagonals.
#left{
  position:absolute;
  border-right:200px solid #0080bf;
  border-top:500px solid transparent;
  left:-200px;
  top:0;
}

#right{
  position:absolute;
  border-left:200px solid #0080bf;
  border-bottom:500px solid transparent;
  right:-200px;
  top:0;
}

#container{
  position:relative;
  width:400px;
  height:460px;
  margin-left:250px;
  background:#0080bf;
  padding:20px;
  color: white;
}

It takes a little bit of adjustment.  Tested and works in Chrome/IE8

A: I'd use http://raphaeljs.com/ very versatile and shouldn't add too much 'weight' to your site

A: You can use "clip-path" to shape special elements.
See more: https://sarasoueidan.com/blog/css-shapes/


text:
Q: getting JSON string into Knockout observable multiselectlist I am trying to get my JSON string passed through the ViewBag into my knockout observable and use that to populate a multiselectlist.  I'm not sure what I am doing wrong, but right now it is taking each individual character in the JSON string and sticking it in it's own line in the select list.
Here is my C# controller code:
Dictionary<string, string> salesReps = new Dictionary<string, string>();
        foreach ( var rep in salespeople.Salesperson )
        {
            salesReps.Add( rep.Code, rep.Code + " - " + rep.fullName );
        }
        //ViewBag.salespeople = salespeople.Salesperson.Select( x => x.Code ).Distinct().ToList();
        ViewBag.salespeople = JsonConvert.SerializeObject( salesReps );

And here is the Knockout code:
var cSource = function (data) {
        var self = this;

        .....
        self.salesPeople = ko.observableArray();
};

$(document).ready(function () {

        var modelData = @Html.Raw( Json.Encode( Model ) );

        mySource = new cSource(modelData);

        //var salesRepList = Html.Raw( Json.Encode( ViewBag.salespeople ) );
        var salesRepList = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.salespeople));
        console.log(salesRepList);

        mySource.salesPeople = salesRepList;

And here is the HTML select code:
<select data-bind="
options: salesPeople,
selectedOptions: chosenReps,
optionsCaption: 'Choose rep(s)'
"></select>

And a small snippet of what my console.log spits out:
{"USERNAME1":"USERNAME1 - Full Name 1","USERNAME2":"USERNAME2 - Full Name 2","USERNAME3":"USERNAME3 - Full Name 3",..... }

UPDATE
I changed the c# code to create named variables in the JSON now.  Here is my new console.log output:
{"username":"BOBC","fullname":"Bob Cottin"},{"username":"JIMT","fullname":"Jim Thorpe"},{"username":"LUKEP","fullname":"Luke Peppin"}, ....}

A: The options binding is expecting an array of objects or values, but according to your console log salesPeople is a single dictionary style object. You may need to convert that to an array so the binding knows how to parse it into select options.
If you only need the value property and can disregard the "Username1", "Username2", etc then you could use a loop like this to grab the value properties of the object:
for (var x in salesRepList) {
    if (salesRepList.hasOwnProperty(x)) {
        mySource.salesPeople.push(salesRepList[x]);
    }
}

If you need the more complex types then you'll have to create an array of objects, or (per your last edit) have your json pass them with standard parameter names. Then you can use knockout's optionsText binding to tell the select which property on the object to use as the display text.
Per example:3 of the knockout docs
<select data-bind="options: availableCountries,
                   optionsText: 'countryName',
                   value: selectedCountry,
                   optionsCaption: 'Choose...'"></select>

Here's a jsFiddle with some of that adapted to your example: fiddle


text:
Q: C++ memory semantics and globals that are set at the start of a program If I have one thread, the "main" thread, initialize a global variable and that thread later spawns some threads that access that variable, do I need to do any work, such as a call to std::atomic_thread_fence(memory_order_seq_cst), to guarantee that the variable appears initialized to the new threads? I suspect that the fact that the main thread creates the new threads establishes a "synchronized-with" relationship that is sufficient to prevent any races, but I'm not certain.
Here's some pseudocode for what I'm describing:
class MyApi {
public:
    static void init(Foo *foo) {
        MyApi::foo = foo;
    }

    static Foo* getSharedFoo() {
        return foo;
    }

private:
    static Foo* foo;
};

void main() {
    Foo* foo = new Foo();
    MyApi::init(foo);
    // Spawn threads that will call MyApi::getSharedFoo() and expect
    // to receive the same foo that is created above.
}

A: No, you don't have to do anything special. New threads see all memory changes up to the point where they were constructed.

A:
30.3.1.2 thread constructors
[ ... ] template  explicit thread(F&& f,
  Args&&... args);
[ ... ]
Synchronization: The completion of the invocation of the constructor
  synchronizes with the beginning of the invocation of the copy of f.

This specifies that f sees everything that occurred prior to the construction of the std::thread object that spawned the thread.


text:
Q: Testing a hypothesis with significance level Prove the hypothesis that the average content of containers of a particular lubricant is $10$ liters, if the contents of a random sample of $10$ containers are:
\begin{array}{|c|c|c|c|c|} \hline
 10,2 & 9,7 & 10,1 & 10,3 & 10,1 \\\hline
 9,8 & 9,9 & 10,4 & 10,3 & 9,8 \\\hline
\end{array}
Use a significance level of $0.01$ and assume that content distribution is normal.
I started with the following:
In this case, use $t=\dfrac{\overline{x}-\mu_0}{s/\sqrt{n}}$, because I do not know anything about $\sigma$.

*

*$H_0: \mu= 10$.

*$H_1: \mu \neq 10$.

*$\alpha = 0,01$.

*How can I find the critical region?

*How I can decide if the hypothesis is correct?

Thank you very much.

A: Your test statistic is $\dfrac{\bar x - 10}{s/\sqrt{10}}$.  The "10" in the numerator comes from the null hypothesis; the "10" in the denominator is the sample size.
You need the number $c$ such that $\Pr(-c<T<c)=0.99$, when $T$ has a Student's t-distribution with $9$ degrees of freedom.  In this case the number of degrees of freedom is one less than the sample size because if you subtract $\bar x$ from each observed number, you get a set of numbers that must add up to $0$; hence if you know $9$ of them, you know all of them.  You can get that number $c$ from a table or from software.  You reject $H_0$ if $T>c$ or $T<-c$, or equivalently, if $|T|>c$.  That's the critical region.
The null hypothesis is presumed correct unless it is rejected, but you can never prove by such means that it is exactly correct.


text:
Q: CLT and almost sure convergence Let $S_n$ = $X_1+\dots+X_n$ be a sum of i.i.d. mean zero random variables with a finite, positive variance. How can I show that $\lim_{n\rightarrow\infty}$ $S_n/\sqrt n$ = $\infty$ a.s.? Also there is no limit $S_n/\sqrt n \rightarrow Y$ , even if we allow $Y$ to take values ±$\infty$.

A: Using Fatou's lemma and the CLT for any $K>0$ we have
$$
\mathsf{P}(S_n/\sqrt{n}>K \text{ i.o.}) \ge \limsup_{n\to\infty} \mathsf{P}(S_n/\sqrt{n}>K)= 1-\Phi(K)>0.
$$
Thus, $\mathsf{P}(\limsup S_n/\sqrt{n}\ge K)>0$. Since $A_K=\{\limsup S_n/\sqrt{n}\ge K\}$ is an exchangeable event, by the Hewitt-Savage 0-1 law $\mathsf{P}(A_K)=1$.
$\therefore \limsup S_n/\sqrt{n}=\infty$ a.s. Similarly, $\liminf S_n/\sqrt{n}=-\infty$ so that $S_n/\sqrt{n}$ does not converge a.s.


text:
Q: C# Windows Application - Many threads using the same connection? I've got a c# WINDOWS Application that is multi-threaded. It is my understanding that in a web environment, connections are pooled automatically. It is also my understanding that in a Windows app, this is not the case. Therefore, for a Windows app, the same connection should be used and not closed after each call, but instead closed when the app shuts down.
I'm curious though - is my correct? If it is, can two threads use the same connection to get a dataset from the DB at the same time or is that functionality queued up?
Thanks

A: The Connection Pooling is one feature of ADO.NET. Therefore the connections are already pooled. Not only in the web environment.
http://www.ondotnet.com/pub/a/dotnet/2004/02/09/connpool.html

A:
It is my understanding that in a web
  environment, connections are pooled
  automatically. It is also my
  understanding that in a Windows app,
  this is not the case.

No, this is wrong, as m3rLinEz pointed out.  Connections are always pooled.

Therefore, for a Windows app, the same
  connection should be used and not
  closed after each call, but instead
  closed when the app shuts down.

You could keep a connection open for the duration of the application in a monolithic WinForms app.  But it's better to use the standard pattern of opening/closing connections whenever you need them.  Connection pooling means you won't notice a performance difference.  And your data access code will be compatible with server applications such as ASP.NET.

If it is, can two threads use the same
  connection to get a dataset from the
  DB at the same time or is that
  functionality queued up?

No. The ADO.NET classes (connection, command etc) are not thread-safe and should not be shared between threads without synchronisation.  But as noted above, you should prefer the standard pattern for data access.

A: ok - so this assumption of mine was brought on by observation: When I tried a win app setup in the typical pool fashion, I always experience a 3-5 second delay while a real connection is established to the remote server. Even when I did an open, then a close, the next query would always have this delay.
When the server connects, it obviously doesn't establish a connection for each connection in the pool. Also, is the pooling mechanism smart enough to grab a connection that it knows is already open or is it possible for it to simply grab any random connection?
What is the default max connections in the pool?


text:
Q: For loops to send info to a constructor in Java I'm trying to use a for loop to allow a user to set objects of my class.
To be honest this is a homework project, but we haven't gotten to for loops yet, I just thought it would be cool to be a little advanced.
But, when I type the part where the input is sent to the method, it says that non-static variable cannot be used in static context.
Is there a way to do this, or do I have to use 2X's as many variables and lines of code to set up these objects?
Here's the part with the for loops
 for (int x=1; x<=2; x++)
   {
    //get input before setting up 2 objects of Employee
    Scanner input = new Scanner ( System.in);
    System.out.print("\nPlease enter the employee's name");
    name = input.nextLine();

    Scanner input1 = new Scanner ( System.in);
    System.out.print("\nPlease enter the employee's department");
    dept = input1.nextLine();

    Scanner input2 = new Scanner ( System.in);
    System.out.print("\nPlease enter the employee's name");
    wage = input2.nextdouble();

    // set Employee objects
    if (x == 1) {
        Employee_irishRodger employee1 = new Employee_irishRodger(name, dept, wage);
    } else {
        Employee_irishRodger employee2 = new Employee_irishRodger(name, dept, wage);
    }

}

A: I'm assuming name, dept and wage are the non-static fields of some class. The reason you are receiving an error is because the method in which you are using the for-loop is in fact static (not associated with each instance of your class) and hence your non-static fields can not be accessed through it. Try removing the static keyword from your method header.
You can read more about the static keyword here.

On another note, you don't need to create a new Scanner each time, you can just keep using input. Furthermore, you can instantiate this Scanner outside the scope of the for loop:
Scanner input = new Scanner(System.in);
for (int x = 1 ; x <= 2 ; x++) {
    System.out.print("\nPlease enter the employee's name");
    name = input.nextLine();

    System.out.print("\nPlease enter the employee's department");
    dept = input.nextLine();

    System.out.print("\nPlease enter the employee's name");
    wage = input.nextdouble();

    ...
}
input.close();  // don't forget to close the scanner when you're done

We've gone from 6 Scanner instantiations to 1.

A: I'd do it more like this.  You can have as many employees as you like:
Scanner input = new Scanner(System.in);
int numEmployees = 5;
List<Employee_irishRodger> employees = new List<Employee_irishRodger>();
for (int i = 0; i < numEmployees; ++i) {
    System.out.print("\nPlease enter the employee's name");
    String name = input.nextLine();
    System.out.print("\nPlease enter the employee's department");
    String dept = input.nextLine();
    System.out.print("\nPlease enter the employee's wage");
    String wage = input.nextLine();
    employees.add(new Employee_irishRodger(name, dept, wage));
}

I don't know where the class name Employee_irishRodger comes from.  Why not just Employee?

A: Make name, dept and wage local.


text:
Q: How to fetch songs from ipodlibrary and play using AVPlayer i want to select songs from ipod Library and play it using avplayer i want the music to continue playing even after the app goes to background i am new to iOS programming can anyone help me out ..
Thanks

A: To allow the user to pick a song (or songs) from their music library, use the MPMediaPickerController class.
-(void) pickSong {

    // Create picker view
    MPMediaPickerController* picker = [[MPMediaPickerController alloc] init];
    picker.delegate = self;

    // Check how to display
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {

        // Show in popover
        [popover dismissPopoverAnimated:YES];
        popover = [[UIPopoverController alloc] initWithContentViewController:picker];
        [popover presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

    } else {

        // Present modally
        [self presentViewController:picker animated:YES completion:nil];

    }

}

Change self.navigationItem.rightBarButtonItem if you're not showing it from a button on the right side of title bar.
Then you need to listen for the result by implementing the delegate:
Called when the user cancelled the selection:
-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {

    // Dismiss selection view
    [self dismissViewControllerAnimated:YES completion:nil];
    [popover dismissPopoverAnimated:YES];
    popover = nil;

}

Called when the user chose something:
-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {

    // Dismiss selection view
    [self dismissViewControllerAnimated:YES completion:nil];
    [popover dismissPopoverAnimated:YES];
    popover = nil;

    // Get AVAsset
    NSURL* assetUrl = [mediaItemCollection.representativeItem valueForProperty:MPMediaItemPropertyAssetURL];
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];

    // Create player item
    AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:asset];

    // Play it
    AVPlayer* myPlayer = [AVPlayer playerWithPlayerItem:playerItem];
    [myPlayer play];

}

You'll need a UIPopoverController* popover; in your class .h file. Also you should retain myPlayer somewhere...
To allow music to continue in the background, add an audio string to the array in your Info.plist under the UIBackgroundModes key.


text:
Q: xcode 7.0 have segue issue I am newbie for Xcode.
When I click on the button to navigate table view app just hang and its navigate me to AppDelegate page,
Here is my code
import UIKit

class ViewController: UIViewController {

let bookPicker = ["Book 1","Book 2","Book 3","Book 4" ]

@IBOutlet private weak var tableView: UITableView?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell =
    tableView.dequeueReusableCellWithIdentifier("customcell") as UITableViewCell!

    if (indexPath.item % 2 == 0){
        cell.backgroundColor = UIColor.clearColor()
    }
    else{
        cell.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.2)
        cell.textLabel!.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0)
    }
        cell.textLabel!.textColor = UIColor.whiteColor()
        cell.textLabel!.text = bookPicker[indexPath.item]

        return cell
    }
}

attaching storyboard pics
when i run app and click on button its just take me on following page


text:
Q: Forward HttpServletRequest to a different server I got a HttpServletRequest request in my Spring Servlet which I would like to forward AS-IS (i.e. GET or POST content) to a different server.
What would be the best way to do it using Spring Framework?
Do I need to grab all the information and build a new HTTPUrlConnection? Or there is an easier way?

A: @RequestMapping(value = "/**")
public ResponseEntity route(HttpServletRequest request) throws IOException {
    String body = IOUtils.toString(request.getInputStream(), Charset.forName(request.getCharacterEncoding()));
    try {
        ResponseEntity<Object> exchange = restTemplate.exchange(firstUrl + request.getRequestURI(),
                HttpMethod.valueOf(request.getMethod()),
                new HttpEntity<>(body),
                Object.class,
                request.getParameterMap());
        return exchange;
    } catch (final HttpClientErrorException e) {
        return new ResponseEntity<>(e.getResponseBodyAsByteArray(), e.getResponseHeaders(), e.getStatusCode());
    }
}

A: Discussions of whether you should do forwarding this way aside, here's how I did it:
package com.example.servlets;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.servlets.GlobalConstants;

@SuppressWarnings("serial")
public class ForwardServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        forwardRequest("GET", req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        forwardRequest("POST", req, resp);
    }

    private void forwardRequest(String method, HttpServletRequest req, HttpServletResponse resp) {
        final boolean hasoutbody = (method.equals("POST"));

        try {
            final URL url = new URL(GlobalConstants.CLIENT_BACKEND_HTTPS  // no trailing slash
                    + req.getRequestURI()
                    + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method);

            final Enumeration<String> headers = req.getHeaderNames();
            while (headers.hasMoreElements()) {
                final String header = headers.nextElement();
                final Enumeration<String> values = req.getHeaders(header);
                while (values.hasMoreElements()) {
                    final String value = values.nextElement();
                    conn.addRequestProperty(header, value);
                }
            }

          //conn.setFollowRedirects(false);  // throws AccessDenied exception
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(hasoutbody);
            conn.connect();

            final byte[] buffer = new byte[16384];
            while (hasoutbody) {
                final int read = req.getInputStream().read(buffer);
                if (read <= 0) break;
                conn.getOutputStream().write(buffer, 0, read);
            }

            resp.setStatus(conn.getResponseCode());
            for (int i = 0; ; ++i) {
                final String header = conn.getHeaderFieldKey(i);
                if (header == null) break;
                final String value = conn.getHeaderField(i);
                resp.setHeader(header, value);
            }

            while (true) {
                final int read = conn.getInputStream().read(buffer);
                if (read <= 0) break;
                resp.getOutputStream().write(buffer, 0, read);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // pass
        }
    }
}

Obviously this could use a bit of work with regard to error handling and the like but it was functional.  I stopped using it, however, because it was easier in my case to make calls directly to the CLIENT_BACKEND than to deal with cookies, auth, etc. across two distinct domains.

A: If you are forced to use spring, please check the rest template method exchange to proxy requests to a third party service.
Here you can find a working example.

A: I also needed to do the same, and after some non optimal with Spring controllers and RestTemplate, I found a better solution: Smiley's HTTP Proxy Servlet. The benefit is, it really does AS-IS proxying, just like Apache's mod_proxy, and it does it in a streaming way, without caching the full request/response in the memory.
Simply, you register a new servlet to the path you want to proxy to another server, and give this servlet the target host as an init parameter. If you are using a traditional web application with a web.xml, you can configure it like following:

<servlet>
    <servlet-name>proxy</servlet-name>
    <servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
    <init-param>
      <param-name>targetUri</param-name>
      <param-value>http://target.uri/target.path</param-value>
    </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>proxy</servlet-name>
  <url-pattern>/mapping-path/*</url-pattern>
</servlet-mapping>

or, of course, you can go with the annotation config.
If you are using Spring Boot, it is even easier: You only need to create a bean of type ServletRegistrationBean, with the required configuration:
@Bean
public ServletRegistrationBean proxyServletRegistrationBean() {
    ServletRegistrationBean bean = new ServletRegistrationBean(
            new ProxyServlet(), "/mapping-path/*");
    bean.addInitParameter("targetUri", "http://target.uri/target.path");
    return bean;
}

This way, you can also use the Spring properties that are available in the environment.
You can even extend the class ProxyServlet and override its methods to customize request/response headers etc, in case you need.
Update: After using Smiley's proxy servlet for some time, we had some timeout issues, it was not working reliably. Switched to Zuul from Netflix, didn't have any problems after that. A tutorial on configuring it with Spring Boot can be found on this link.

A: Unfortunately there is no easy way to do this. Basically you'll have to reconstruct the request, including:

*

*correct HTTP method

*request parameters

*requests headers (HTTPUrlConnection doesn't allow to set arbitrary user agent, "Java/1.*" is always appended, you'll need HttpClient)

*body

That's a lot of work, not to mention it won't scale since each such proxy call will occupy one thread on your machine.
My advice: use raw sockets or netty and intercept HTTP protocol on the lowest level, just replacing some values (like Host header) on the fly. Can you provide more context, why so you need this?

A: Use Spring Cloud Gateway
pom.xml
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-gateway-mvc</artifactId>
    </dependency>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2020.0.2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Controller
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

@RestController
public class Proxy extends BaseController {

    private String prefix="/proxy";
    private String Base="localhost:8080/proxy";  //destination

    void setHeaders(ProxyExchange<?> proxy){
        proxy.header("header1", "val1"); //add additional headers
    }

    @GetMapping("/proxy/**")
    public ResponseEntity<?> proxyPath(@RequestParam MultiValueMap<String,String> allParams, ProxyExchange<?> proxy) throws Exception {
        String path = proxy.path(prefix); //extract sub path
        proxy.header("Cache-Control", "no-cache");
        setHeaders(proxy);

        UriComponents uriComponents =  UriComponentsBuilder.fromHttpUrl(Base + path).queryParams(allParams).build();
        return proxy.uri(uriComponents.toUri().toString()).get();
    }

    @PutMapping("/proxy/**")
    public ResponseEntity<?> proxyPathPut(ProxyExchange<?> proxy) throws Exception {
        String path = proxy.path(prefix);
        setHeaders(proxy);
        return proxy.uri(Base + path).put();
    }


text:
Q: How do I connect c# console to database? I am making a c# console application and would like to add a login system.
I have this code already:
Start:
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.Cyan;

        Console.WriteLine("Enter Username.");
        string strUsername = Console.ReadLine();
        string strTUsername = "Test";

        if (strUsername == strTUsername)
        {
            Console.Clear();
            Console.WriteLine("Enter Password");
            Console.ForegroundColor = ConsoleColor.Gray;
            string strPassword = Console.ReadLine();
            string strTPassword = "Test";
            if ( strPassword == strTPassword)
            {
                Console.Write("Logging in.");
                Thread.Sleep(1000);
            }

            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("The password you entered is wrong.");
                Thread.Sleep(2000);
                goto Start;
            }
        }

        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("The username you entered is wrong.");
            Thread.Sleep(2000);
            goto Start;
        }

I would like to make it allow multiple username and passwords that you can enter that will work.
So far it just accepts the username and password 'Test' but I would like to link it to another file filled with username and passwords that I can use instead of just 'Test'.
Any help you can give me or provide is useful thanks!

A: You have two ways of doing it:
1: Database to store username and password
2: Save the username and password in file in a uniform format(like comma,tab separated)

1:Database
->Select a database to use
->create a table with columns such as username and password
->connect to database from your app
->get username from console and compare it with the rows of database and check if the password given is correct.

2:File
->Save a file with username and password with a certain format(comma,space or tab separated)
->Import those from the file to a Dictionay<users>.
->compare the entered password and user name with the dictionary items.

You can use encryption to make the file or database more secure.
static void Main(string[] args)
        {
            List<User> usersList = new List<User>();
            string[] lines = System.IO.File.ReadAllLines("users.txt");
            foreach ( var line in lines)
            {
                User user = new User();
                user.user = line.Split(' ')[0];
                user.password = line.Split(' ')[1];
                usersList.Add(user);
            }
            foreach (var item in usersList)
            {
                Console.WriteLine(item.user);
                Console.WriteLine(item.password);
            }
            Console.ReadLine();
        }

}
public class User
{
   public string user { get; set; }
   public  string password { get; set; }
}

In this I have added a simple code to read a space separated password file and use it as per your requirement. For a more secure way you can encript the file. Thank you


text:
Q: How can I make Mono show multiple lines of a Label with Winforms? I have a method that creates a label on the window. This method works fine in Windows under .Net but when I run it on my RPi using mono only one line appears.
Is there any mono specific code I can use to force mono to show all of the text on the label?
private void ShowMessageRight(string strMessage, Color backColor, Color foreColor, Single fontSize = 24f)
{
    if (_lblMessageRight == null)
    {
        _lblMessageRight = new Label();
        this.Controls.Add(_lblMessageRight);
    }
    _lblMessageRight.Text = strMessage;
    _lblMessageRight.BackColor = backColor;
    _lblMessageRight.ForeColor = foreColor;
    _lblMessageRight.Font = new Font(new FontFamily("Microsoft Sans Serif"), fontSize, FontStyle.Bold);
    _lblMessageRight.TextAlign = ContentAlignment.MiddleCenter;
    _lblMessageRight.MaximumSize = new Size(500, 0);
    _lblMessageRight.AutoSize = true;
    _lblMessageRight.Left = (int)((this.ClientSize.Width * 0.75) - (_lblMessageRight.Width / 2));
    _lblMessageRight.Top = (this.ClientSize.Height - _lblMessageRight.Height) / 2;
    _lblMessageRight.BringToFront();
    _lblMessageRight.Show();
}

The result of identical calls to the method.
On Windows with .net

On Linux with Mono (On RPi)

EDIT:
So I tried using TextRenderer.MeasureText this seems to work but I am very confused as to why. TextRenderer.MeasureText will sometimes return a width that is less than 500 when I know the string is longer than that. It will return a height that is twice the height that the font should be. if I use that value as the label height I get two lines.  TextRenderer.MeasureText some how magically knows how long wide I want my label.
    Size SingleLineSize = TextRenderer.MeasureText(strMessage, _lblMessageLeft.Font, new Size(Int32.MaxValue, Int32.MaxValue));
    strMessage = SingleLineSize.Width + strMessage;
    int numberOfLines = (int)Math.Ceiling(SingleLineSize.Width / 500f);
    int lineHeight = SingleLineSize.Height;
    int height = numberOfLines * lineHeight;


text:
Q: Is the Gamma function defined for complex numbers like so? I know $\Gamma (x)$ can be defined as...
$$\Gamma (x) = (x-1)!$$
And as...
$$\Gamma (x) = \int_{0}^{\infty} u^{x-1} e^{-u} \space du$$
But assuming we had a Complex variable $z$ and had the following...
$$(z-1)!$$
Would it be correct for me to say...
$$\Gamma (z) = (z-1)!$$
Or is that only defined for Natural values?

A: $\Gamma(z)$ is a function of a complex variable $z$ so that $\Gamma(n) = (n-1)!$ for $n = 1,2,...$, the positive integers.  Just writing $\Gamma(z) = (z-1)!$ does not give a definition for $\Gamma(z)$.  However, sometimes the notation $z!$ is used to denote the value of $\Gamma(z+1)$.  If you define the symbol $z!$ to mean $\Gamma(z+1)$ then the statement $\Gamma(z) = (z-1)!$ is true.  You can use the symbol $!$ this way if you want, but you should probably clarify your definitions beforehand.


text:
Q: Correct way of accessing a file with name Ok I need someone to clear things up for me.
I saw a hundred different ways of accessing a file to read in it (FileReader).
I tried all of them and can't find a way to do it correctly.
If I try :
String path = Engine.class.getResource("Words.txt").toString();

or
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);

I go directly to :
dispatchUncaughtException

I just don't know where to look anymore since no one seems to agree on the good way to do it. Also, what is that kind of exception ?There must be an easy way to do this since it is such an easy task. I just want my program to see my Words.txt file that is in the SRC folder of my project.

Full code if it helps :
public String GetWord()
{
 String [] Words = new String [10];
 int random = (int)(Math.random() * 10);
 URL url = getClass().getResource("Words.txt");
 String path = url.getFile();
 File myFile = new File(path);

  try
  {
       FileReader myReader = new FileReader(myFile);
       BufferedReader textReader = new BufferedReader(myReader);

        for(int i = 0; i < 10; i++)
        {
           Words[i] = textReader.readLine();
        }
   }
  catch(Exception e)
  {
        System.out.println(e.getMessage());
  }

  return Words[random];
  }

A: String path = Engine.class.getResource("Words.txt").toString();

For that to work, your file has to be in the same package as the Engine class. So, you probably want to move your file to the package where the class is at.
If you want to move the file into some other package then you need to specify the location starting from the root of the classpath. e.g. /some/other/pkg/Words.txt.

For a file which is not in the classpath, you need the full path along with the file name, to be able to read the file. The SRC folder itself is not a package and not in the classpath.
In that case, you can do something as follows:
FileInputStream fis = new FileInputStream("C:\\path\\to\\file\\Words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));

A: If you use Java 7 I recommend using newBufferedReader. It's more efficient and easier to use than the BufferedReader. I also modified your code to match the Java Code Conventions.
Working exmaple:
public String getWord() {
    String[] words = new String[10];
    int random = (int) (Math.random() * 10);
    Path path = Paths.get("src" + System.getProperty("file.separator")
            + "Words.txt");

    try {
        BufferedReader textReader = Files.newBufferedReader(path,
                StandardCharsets.UTF_8);

        for (int i = 0; i < 10; i++) {
            words[i] = textReader.readLine();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return words[random];
}


text:
Q: Perl Script, look at windows folder while executing on unix I have a perl script that runs on a unix machine (Linux01) and does a variety of things. I want to add something to the script that will allow me to run a system command on a windows machine (Wdinows01) that is on my network that I have permission/access to.
I want to do something like this:
my $result = `cat \\Windows01\tmp\test\fileinfo.txt`;

Obviously the above code is missing a lot but, is this possible at all or is this more complicated then I think?

A: Backticks follow the same coding rules as double-quoted strings, which means that
`...`

is the same thing as
readpipe(qq`...`)

So let's see the string you're passing to the shell:
$ perl -E'say qq`cat \\Windows01\tmp\test\fileinfo.txt`'
cat \Windows01  mp      est
ileinfo.txt

Oops! \\ produces a backslash, \t produces a tab, and \f produces a form feed. Fixed:
my $result = `cat \\\\Windows01\\tmp\\test\\fileinfo.txt`;

(That's assuming your cat takes Windows paths.)


text:
Q: PostgreSQL Index not used when data rows are large Hi I'm curious about why index doesn't work when data rows are large even 100.
Here's select for 10 data:
mydb> explain select * from data where user_id=1;
+-----------------------------------------------------------------------------------+
| QUERY PLAN                                                                        |
|-----------------------------------------------------------------------------------|
| Index Scan using ix_data_user_id on data  (cost=0.14..8.15 rows=1 width=2043) |
| Index Cond: (user_id = 1)                                                         |
+-----------------------------------------------------------------------------------+
EXPLAIN

Here's select for 100 data:
mydb> explain select * from data where user_id=1;
+------------------------------------------------------------+
| QUERY PLAN                                                 |
|------------------------------------------------------------|
| Seq Scan on data  (cost=0.00..44.67 rows=1414 width=945) |
| Filter: (user_id = 1)                                      |
+------------------------------------------------------------+
EXPLAIN

How can index work when data rows are 100?

A: 100 is not a large amount of data.  Think 10,000 or 100,000 rows for a respectable amount.
To put it simply, records in a table are stored on data pages.  A data page typically has about 8k bytes (it depends on the database and on settings).  A major purpose of indexes is to reduce the number of data pages that need to be read.
If all the records in a table fit on one page, there is no need to reduce the number pages being read.  The one page will be read.  Hence, the index may not be particularly useful.


text:
Q: Trick for listing authors I wrote the following code:
\makeatletter
 \newtoks\author@toks\newcounter{author@counter}%
 \setcounter{author@counter}{0}%
 \newcommand{\authorAdd}[1]{%
 \ifnum\theauthor@counter>0\author@toks=\expandafter{\the\author@toks,    #1}%
 \else\author@toks=\expandafter{\the\author@toks\@author{#1}}%
 \fi\stepcounter{author@counter}%
 }
 \newcommand{\printauthor}{{\sc Authors:}\the\authors@toks}
\makeatother

that is, I can add an author with the command \authorAdd{} and then the command \printauthor list all the author, separating them with a comma. I would like tu replace the last comma with the word "and". How can I do?
Thanks

A: A 'traditional' way with the \@elt splitting feature:
Counter reset lists use the \@elt splitting, i.e. the counters that should be reset by foo counter are stored this way:
foobar\@elt otherfoobar\@elt. The list is named cl@foo and is called each time in stepping command, whereas \@elt is a 'volatile' macro, being defined to do some action.
The same approach can be applied here, using \@elt instead of , as name separator.
The \printauthor command just uses \the\author@toks and defines a special \@elt (in a group) that displays the correct , or and separator finally.
\documentclass{article}

\makeatletter
 \newtoks\author@toks\newcounter{author@counter}%
 \setcounter{author@counter}{0}%
 \newcommand{\authorAdd}[1]{%
 \ifnum\theauthor@counter>0\author@toks=\expandafter{\the\author@toks\@elt\relax #1}%
 \else\author@toks=\expandafter{\the\author@toks\@author{#1}}%
 \fi\stepcounter{author@counter}%
 }

\newcounter{dummycounter}
\newcommand{\printauthor}{%
  \textsc{Authors:}%
  \begingroup
  \setcounter{dummycounter}{0}%
  \def\@elt##1{%
    \ifnum\c@dummycounter < \numexpr\c@author@counter - 2\relax%
    ,
    \else
    { and }%
    \fi
    \stepcounter{dummycounter}%
  }
  \the\author@toks%
  \endgroup
}

\makeatother

\begin{document}
\authorAdd{Shakespeare}
\authorAdd{Tolkien}
\authorAdd{Groucho Marx}
\authorAdd{Harpo Marx}
\authorAdd{Gummo Marx}
\authorAdd{Zeppo Marx}
\authorAdd{Chico Marx}

\printauthor
\end{document}

A \clist - splitting way with expl3.
\documentclass{article}

\usepackage{xparse}

\makeatletter
 \newtoks\author@toks\newcounter{author@counter}%
 \setcounter{author@counter}{0}%
 \newcommand{\authorAdd}[1]{%
 \ifnum\theauthor@counter>0\author@toks=\expandafter{\the\author@toks,    #1}%
 \else\author@toks=\expandafter{\the\author@toks\@author{#1}}%
 \fi\stepcounter{author@counter}%
 }
 \newcommand{\printauthor}{{\sc Authors:}\the\author@toks}

\ExplSyntaxOn

\newcommand{\splitauthorlist}[1]{%
  \clist_set:Nx \l_tmpa_clist {#1}
  \clist_use:Nnnn \l_tmpa_clist {,\space} {,\space} {\space and\space}
}
\ExplSyntaxOff

 \newcommand{\printauthors}{%
   {\scshape Authors}:
   \splitauthorlist{\the\author@toks}
}
\makeatother

\begin{document}
\authorAdd{Shakespeare}
\authorAdd{Tolkien}
\authorAdd{Groucho Marx}

\printauthors
\end{document}


text:
Q: Can use Blend SDK classes in code but not XAML (Prism Desktop) I'm trying to use a CallMethodAction bound to a control in a WPF Window, using the method from the Prism library samples and documentation. For some reason, the XAML compiler refuses to acknowldge that the Microsoft.Expression.Interactivity.Core namespace even exists. However, I have no problem using the same classes from the same namespace in the code-behind for that view.
In XAML I've tried both the canonical namespaces:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ic="http://schemas.microsoft.com/expression/2010/interactions"

as well as the CLR namespace:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ic="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"

The namespace Intellisense pop-up browser displays the first namespace but neither the XML nor CLR namespaces for the second. In either case, the following XAML fails to compile:
<Button HorizontalAlignment="Right" Content="Cancel">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <ic:CallMethodAction />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

It has no problem finding the Interaction.Triggers tag, but complains that the CallMethodAction tag doesn't exist in the specified namespace. In fact, Intellisense on the ic namespace tag acts as if there is no such namespace. However, I do not get the error that the CLR namespace could not be found, which I do if I try to use a non-existant namespace.
However, in the constructor for this window, I can do this:
var x = new Microsoft.Expression.Interactivity.Core.CallMethodAction();

That compiles and runs fine. How is that even possible?

A: Try removing and re-adding reference to Microsoft.Expression.Interactions.dll and *.Interactivity.dll
It happened to me once but I don't know why. This is the way I solved it.


text:
Q: How to start a gen_server or gen_fsm on demand in Erlang without race conditions? I need to spawn several independent instances of the same gen_fsm on demand, and then be able to route calls to the correct instance.
Gproc library seems to be a great way of registering processes with arbitrary names. It has a function gproc:reg_or_locate/3 for spawning things on demand without race conditions. This way I don't even need a supervisor - if they crash they'll just get spawned on demand again. But I can't figure out how to apply gproc:reg_or_locate/3 to spawning a gen_fsm or gen_server.
What I've tried so far:
I just call gen_server:start() through that function, it will create an intermediate process, give the name to the intermediate process, the intermediate process will spawn a gen_server and terminate, and I end up with a nameless gen_server.
Both gen_server and gen_fsm export an enter_loop function that seems to do what I need if I feed it to gproc:reg_or_locate/3, but the documentation reads:

The process must have been started using one of the start functions in
  proc_lib, see proc_lib(3).

And the docs for gproc:reg_or_locate/3 do not mention that they do anything through proc_lib.
Alternatively I could make the intermediate process acquire the name and then atomically transfer it to the gen_server or gen_fsm that it spawned, but that creates a race condition: the intermediate process would have gen_fsm's name and any messages intended for the gen_fsm would go to the intermediate process and get lost.
I feel like I'm missing something simple here. It's not an uncommon pattern, so there should be a good way to do this. What did I miss?

A: For your purposes I don't think gproc:reg_or_locate/3 really gives you anything useful. If it returns a PID (due to spawning a new process, or locating an existing one) the process could still die before you send a message to it, so unless you have a mechanism on top of the basic Erlang messaging you'll never know this didn't happen. The server could also die before receiving the message or die processing it even if it was alive when you sent the message, so given you express some concern for messages getting lost, one component of the solution must be a reliable message mechanism. The sensible and ready available solution to that is gen_server:call and gen_fsm:sync_send_event in your case, rather than just sending a message.
This eliminates the problem of messages getting lost from any spawning solution you care to implement. That is, you will know the message was lost, or failed, and then you can take whatever action is appropriate.
Now, for the actual spawning of your servers, there is always going to be a race condition where multiple processes might try and spawn the same server (a server with a given name) no matter how you implement it; anything you to to lookup the name (e.g. erlang:whereis/1) could be out of date before you do anything else (it could return a PID, but the PID could die before you message it, or it could return undefined but some other process could register the name before you try to) so the only point at which the race is won (or lost) is when erlang:register/2 is called.
You know then that there might be a race, but that there can be at most one winner. It might not be you, some other process might beat you to the spawning, but since you are naming your processes that doesn't matter, you can simply spawn your gen_server, giving it the name to register itself as, and then message it by name:
gen_server:start({local, Name}, ?MODULE, [], []),
gen_server:call(Name, Message)

It doesn't matter who won the race (the gen_server:start/4 call might return {error,{already_started, Pid}}) but so what, all that's important is someone should have won, and the call to gen_server:call has every chance of success thereafter.
You obviously do need to make sure the call returned a suitable success result, technically you could check for a noproc exception and try to spawn it again, but then you'd have to make sure this doesn't become an infinite loop.
To be honest, although you don't care about supervision, I'd probably have it supervised anyway. In this case a simple_one_to_one supervisor with a restart strategy set to temporary so it doesn't respawn fits. Your servers will be collected in one place then, not just floating in limbo, and you'll get supervisor reports, which can't be a bad thing. Sadly you won't get run away restart protection because there are no restarts here so you still need to worry about that (unless you change temporary to transient). Your effective point of arbitration would then be supervisor:start_child/2 and you would pass the desired name of the process as a parameter.

A: As Michael suggested, I would also go for supervision.
You can use the {via,Module,ViaName} in your gen_server:start_link to use other names than atoms. See here for details: http://erlang.org/doc/man/gen_server.html#start_link-4
For example, with gproc
gen_server:start_link({via, gproc, {n, l, {?MODULE, Name}}, ?MODULE, [], []).

Don't forget to use the same {via, gproc, ...} structure when calling the gen_server, in stead of just using the Name:
gen_server:call({via, gproc, {n, l, {?MODULE, Name}}, {execute_command, Command}).

I tend to define the via like this:
-define(SERVER(Name), {via, gproc, {n, l, {?MODULE, Name}}}).

And then use it like:
gen_server:start_link(?SERVER("Testing"), ?MODULE, [], []).
gen_server:call(?SERVER("Testing"), {execute_command, Command}).

You can then start it in a supervisor with a simple_one_for_one strategy and a temporary child specifitation, like this:
Supervisor
-module(my_cool_sup).

-behaviour(supervisor).

%% API
-export([start_link/1, start_child/1]).
%% Supervisor callbacks
-export([init/1]).

-define(SERVER, ?MODULE).

%% Helper macro for declaring children of supervisor
-define(CHILD(ChildName, Type, Args), {ChildName, {ChildName, start_link, Args}, temporary, 5000, Type, [ChildName]}).

%%====================================================================
%% API functions
%%====================================================================

start_link() ->
    supervisor:start_link({local, ?SERVER}, ?MODULE, []).

start_child(Name) ->
    supervisor:start_child(?SERVER, [Name]).

%%====================================================================
%% Supervisor callbacks
%%====================================================================

init([]) ->
    RestartStrategy = {simple_one_for_one, 1, 5},

    Children = [?CHILD(my_cool_server, worker, [])],

    {ok, { RestartStrategy, Children} }.

gen_server
-module(my_cool_server).

-behavior(gen_server).

%% API
-export([start_link/3, execute_command/3]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
     terminate/2, code_change/3]).

-define(SERVER(Name), {via, gproc, {n, l, {?MODULE, Name}}}).

%%%===================================================================
%%% API
%%%===================================================================

start_link(Name) ->
    gen_server:start_link(?SERVER(Name), ?MODULE, [], []).

execute_command(Name, Command) ->
    gen_server:call(?SERVER(Name), {execute_command, Command}).

%%%===================================================================
%%% gen_server callbacks
%%%===================================================================

%% Your normal gen_server callbacks here...

Now you can use my_cool_sup:start_child("My cool name"). to start you child processes. They will be supervised and if they are already started it will return already_started but not throw an error.
Check start_child for more details: http://erlang.org/doc/man/supervisor.html#start_child-2


text:
Q: Django error on admin site entry when deployed on Heroku I have had success in the past hosting a website using the django-heroku package outlined here, but now when I try to run just a basic shell of a Django project as the start of a new project I am hit with the following error message:
ProgrammingError at /admin/login/
relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...
                                                             ^
Request Method: POST
Request URL:    https://hockamer2018.herokuapp.com/admin/login/?next=/admin/
Django Version: 2.1
Exception Type: ProgrammingError
Exception Value:
relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...
                                                             ^
Exception Location: /app/.heroku/python/lib/python3.6/site-
packages/django/db/backends/utils.py in _execute, line 85
Python Executable:  /app/.heroku/python/bin/python
Python Version: 3.6.6
Python Path:
['/app/.heroku/python/bin',
 '/app',
 '/app/.heroku/python/lib/python36.zip',
 '/app/.heroku/python/lib/python3.6',
 '/app/.heroku/python/lib/python3.6/lib-dynload',
 '/app/.heroku/python/lib/python3.6/site-packages']

It runs fine when I run this locally so I must have forgotten to set up something on the database on Heroku. I have thoroughly researched this question and all of the fixes seem to be to run
    python manage.py makemigrations
    python manage.py migrate
but I have done that through the heroku remote ssh and "heroku run" command both to no avail.
I am running a completely fresh Django installation where all I have done is added the two django-heroku lines to settings.py. I have tried this on both django-2.0.8 and 2.1.

A: I just finished battling with this problem and I figured out that there are some operation that you have to do through the heroku cli especially when it comes to your database,
Firstly, you want to ensure that your requirements.txt is up to date so that any field in your models that is dependent on any of the third-party apps can be made (e.g models.ImageField depends on pillow).
Run the following and make sure that when committing changes, it detects the change in your migrations if any were made :
python manage.py makemigrations
git add .
git commit -m "message"
git push heroku master

heroku run python manage.py migrate
heroku run python manage.py createsuperuser

The last two lines of code are responsible for solving your problem. My guess is that, heroku by default doesn't track the changes made to your db.sqlite (as defined in .gitignore) so it doesn't run the migrate line so you need to do that manually so when you deploy it doesn't detect the tables you've created afterwards. Hope this helps you though.


text:
Q: Linux: access mounted volumes as normal folders/files I have a closed source software (client) running on a Linux machine (Debian) to deliver files to a backup machine.
This works fine except this client software does not access the mounted volumes (either NFS or SMB). So far I don't know why, as the rights are pretty open to those folders and any other user can access it...
Anyway, this client can access/send other folders and files, so would there be a way to make the mounted volumes appear to that client as "normal folders"?

A: This is one of those "I'd need to be there with you debugging it" sort of problems, especially since you haven't said which proprietary client you're using.
The answer to your question as asked is "yes and no"; if your NFS mount is /nfs/, and a program interacts with /nfs/foo, that's a normal file as far as that program can tell, period.  Unless it asks.  If it actually specifically asks the OS "What sort of filesystem is /nfs/foo a part of?", it'll get told that it's NFS.  You can't change either of these things, basically; in particular, you can't get the OS to tell the client that the NFS mount isn't an NFS mount, at least as far as I know.
However, it's very unlikely that the client is actually asking.
Here's what I'd check:

*

*The most likely issue is that the client is running against / (the root file system) and is refusing to cross file system boundaries; that's fairly typical.  Again, you can't fix that directly, but what you can probably do is give it other places to look.  Try adding your NFS or SMB shares to the client as backup locations explicitly.

*NFS at least (and I think SMB) by default prevents root on a client host from doing a lot of things; if #1 doesn't work, try adding no_root_squash to your NFS exports (make sure it worked by running "exportfs -v" on the master and looking for the option) and see if that helps.

*If those both fail, I would strace the client (using -ff -o /tmp/strace.out or so) and grep for one of the filesystems it's not picking up, and see what errors it's getting, or if it's even trying. If it's not even trying and you've explicitly listed that FS as something to backup, you'd best talk to the vendor.

-Robin


text:
Q: SPFX corrupted solution We are thinking of leveraging SPFx for our business.
I have created a solution with an SPFx web part. The hello world solution worked as expected.
After a couple of days I returned  to the solution to add a second web-part.
While running yo @microsoft/sharepoint I get an error

C:\Users\vasileios.kantartzis\AppData\Roaming\npm\node_modules\@microsoft\generator-sharepoint\node_modules\pad-component\index.js:28

What is wrong here? I have seen the same behavior on multiple boxes
If I create a new solution in a new folder I do not have this issue
Thank you in advance for the help.

A: it might cause by version differences. You can try to check the version and update your existing solution package version if necessary.
https://docs.microsoft.com/en-us/sharepoint/dev/spfx/toolchain/update-latest-packages
After updated, try to add the second web part again.


text:
Q: Active Record is not displaying correct query Can anybody tell me why im not able to display the following query using active record in codeigniter. I suppose there is something wrong with TIMEDIFF in my select statement as theres no space between TOTAL and FROM
This is my active record query
$this->db->select('s.id, s.person_id, p.first_name, p.last_name, sch.id, sch.start_date, sch.start_hour, sch.end_hour, TIMEDIFF(sch.end_hour, sch.start_hour) AS total');
$this->db->join('staff s', 'sch.staff_id = s.id', 'left');
$this->db->join('persons p', 's.person_id = p.id', 'left');
$this->db->where('sch.start_date >=', $start);
$this->db->where('sch.start_date <=', $end);
$this->db->limit(10);

$query = $this->db->get('work_schedule sch');

And this is how is printed out
SELECT `s`.`id`,
   `s`.`person_id`,
   `p`.`first_name`,
   `p`.`last_name`,
   `sch`.`id`,
   `sch`.`start_date`,
   `sch`.`start_hour`,
   `sch`.`end_hour`,
TIMEDIFF(sch.end_hour,`sch`.`start_hour)` AS totalFROM (`work_schedule` sch)
LEFT JOIN `staff` s ON `sch`.`staff_id` = `s`.`id`
LEFT JOIN `persons` p ON `s`.`person_id` = `p`.`id`
WHERE `sch`.`start_date` >= '2014-02-19'
  AND `sch`.`start_date` <= '2014-02-20'LIMIT 10

A: You can try it.
$query = $this->db->select('s.id, s.person_id, p.first_name, p.last_name, sch.id, sch.start_date, sch.start_hour, sch.end_hour, TIMEDIFF(sch.end_hour, sch.start_hour) AS total', FALSE)
                  ->from('work_schedule sch')
                  ->join('staff s', 'sch.staff_id = s.id', 'left')
                  ->join('persons p', 's.person_id = p.id', 'left')
                  ->where('sch.start_date >=', $start)
                  ->where('sch.start_date <=', $end)
                  ->limit(10)
                  ->get();

$result = $query->result();


text:
Q: Iteration Function I am trying to write a function that will calculate the value for pi. I want to return the new values of C and I (as well as π) from the function, and then use the new C and I as inputs for the next iteration.
Here is my code:
def pi_func(I_i,C_i):

    C = (2*C_i*I_i)/(C_i+I_i)
    I = sqrt(C*I_i)
    pi = (C+I)/2

    print C
    print I

    return pi

I_3 = ((sqrt(3)/2)/(.5))*1.5
C_3 = (.5/(sqrt(3)/3))*6

print pi_func(I_3,C_3)

Okay, below is my newest code.
def pi_func(I_i,C_i):

    new_C = (2*C_i*I_i)/(C_i+I_i)
    new_I = sqrt(new_C*I_i)
    pi = (new_C+new_I)/2

    print "C = ", new_C
    print "I = ", new_I

    return (pi,new_I,new_C)

I_3 = ((sqrt(3)/2)/(.5))*1.5
C_3 = (.5/(sqrt(3)/3))*6
print "I = %r" %I_3
print "C = %r" %C_3

for i in xrange(100):
    x = pi_func(I_3,C_3)
    print "PI = %r" %x[0]
    I_3 = x[1]
    C_3 = x[2]

print "Here is the machine accuracy for pi: %r" % np.pi

I want to get machine accuracy which is:
Here is the machine accuracy for pi: 3.141592653589793
But my program gives me: PI = 3.141592653589792
And since I am telling my program to do 100 iterations, it does stop until then. But the value for pi is calculated well before the 100th iteration.

A: This seems to do the job iteratively:
from math import sqrt

def pi_func(I_i,C_i):

    C = (2*C_i*I_i)/(C_i+I_i)
    I = sqrt(C*I_i)
    pi = (C+I)/2

    print "C  = ", C
    print "I  = ", I

    return (pi, I, C)

I_3 = ((sqrt(3)/2)/(.5))*1.5
C_3 = (.5/(sqrt(3)/3))*6
print "C3 = ", C_3
print "I3 = ", I_3

for i in xrange(10):
    x = pi_func(I_3,C_3)
    print "PI = ", x[0]
    I_3 = x[1]
    C_3 = x[2]

Sample output:
C3 =  5.19615242271
I3 =  2.59807621135
C  =  3.46410161514
I  =  3.0
PI =  3.23205080757
C  =  3.21539030917
I  =  3.10582854123
PI =  3.1606094252
C  =  3.1596599421
I  =  3.13262861328
PI =  3.14614427769
C  =  3.14608621513
I  =  3.13935020305
PI =  3.14271820909
C  =  3.14271459965
I  =  3.14103195089
PI =  3.14187327527
C  =  3.14187304998
I  =  3.14145247229
PI =  3.14166276113
C  =  3.14166274706
I  =  3.14155760791
PI =  3.14161017748
C  =  3.1416101766
I  =  3.14158389215
PI =  3.14159703438
C  =  3.14159703432
I  =  3.14159046323
PI =  3.14159374877
C  =  3.14159374877
I  =  3.141592106
PI =  3.14159292739

If you want to do it recursively, it is not very much harder — the main issue is when to stop recursing.


text:
Q: ClickOnce and mageUI adding custom file folder problems What I do: Publishing .Net 3.5 application via VS, or msbuild (whatever), and now I need to insert to the published application separate directory (Modules - not added as a reference to the project - our project architecture does not allow this). So I'm copying the folder to published location then runs mageUI.exe select the application manifest and then the problems starts. As I press the populate button it's adding also hidden directory? So I remove the directory, after I want to save the manifest file I get the
"Warning MSB3110: Assembly 'NAME.Shell.application.deploy' has mismatched identity 'NAME.Shell.application', expected file name: 'NAME.Shell.application.application'".
Did you have the same problems, according to http://smartclient.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=5060 it should be easy as 1-2-3 but it's not.

A: On the irony side, I am currently updating the SCSF documentation for ClickOnce deployment for .NET 4.0, and now I know exactly what the problem it.
First, you want to publish to a disk location, not directly to the webserver. So do that, and then copy the dll's you want to add to the deployment into the version folder with the application manifest (.manifest). Rename them yourself -- just add .deploy on the end.
Bring up MageUI and open the application manifest in that folder, then uncheck the box that says "add .deploy to the file names". Click "populate".
Then remove the deployment manifest from the list; it's called something like appname.application. You don't want it to be included in the manifest's list of files.
Now you can save and sign the application manifest. Then without exiting mageUI, open the deployment manifest that is in the root folder (NOT the one in the version folder). Click on "Application Reference", then click Select Manifest. Dig down to the application manifest in the version folder that you just signed and select it. Then just save and sign the deployment manifest. It puts a relative path in there, so if you modify the .application file in the version folder, it won't work right when deployed.
Now take that .application file from the root folder and copy it into the version folder (replacing the one that's there) so you have the right copy for that version in case you need it later.
Now copy the whole shebang out to the webserver. it should work.

A: I think you are saying you need to add a folder of stuff to your ClickOnce deployment? What exactly are you adding? You say modules -- are they going to be compiled in, or is it something else?
If you want to add files to the deployment you have already created, you need to use MageUI to edit the application manifest, which is called something like appname.exe.manifest. (The appname.application is actually called the deployment manifest, which is confusing but true.) After adding the files, you will need to re-sign the deployment manifest as well (assuming you signed it in the first place).
It would be easier just to add what you want included to your project and re-publish. Depending on what it is, you can set the build action to 'content' (jpegs, html, etc) or 'none' (dll's) and then set "copy to output directory" to true, and it will include it in your deployment.
I'm not sure exactly what you are including. Give me more info, and I can provide more specific help.
RobinDotNet