text:
Q: Python: Evaluation of all/any vs spelling them out Let's consider two ways to check for all conditions to be true
Option 1
if all([cond1, cond2, cond3]):
  return true

Option 2
if (cond1 and cond2 and cond3):
  return true

Do both evaluate the same way? AFAIR that all will fail as soon as one statement fails, making it possible, that a condition can presume that all previously listed conditions evaluated to true. E.g. making it safe in Option 1 to access a variable in cond3, that was previously (in cond1 or cond2) tested to be accessible. Does that hold true also for Option 2? Also, are there performance differences?

A: Option 1 has extra performance overhead, needing to create a list, and then iterate over the list. There's also a problem where each condition put into the iterable used in all() would have to be computed before checking truthness.
A fine example by @StefanPochmann proves the problems which arise:
a = [3, 1, 4, 1, 5, 9]

if a and a[0] > 5:
    pass

if all((a, a[0] > 5)):
    pass

a = []

if a and a[0] > 5:
    pass

if all((a, a[0] > 5)):
    pass

Traceback (most recent call last):
  File "/tmp/execpad-b1260aab7279/source-b1260aab7279", line 14, in <module>
    if all((a, a[0] > 5)):
IndexError: list index out of range

You can see the snippet run here
Using option 2 is the better choice, unless you are actually validating a list of booleans. Using the and operator prevents the checking of contitions past the first one failing, as demonstrated above.
Apart from performance reasons, the code is much easier to read if you use the and operator between your conditions. With proper syntax hilighting in an editor, it will become very clear what is going on.


text:
Q: StreamWriter.Write is not writing all the data I am trying to  create a text file by a loop data .each loop data i have send to another method and creating the text file as blow .
//another method each and every for loop time this method will run.
public void  TextFileGen1(string pdate, string oPno, string supCode, string supName, string cur, string docTotal, string glAct, string glName, string pType, string jRemark, string rmk)
{
    if (pType == "CEFT")
    {
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"E:\filename.txt", true))
        {
            file.Write(pdate, oPno, supCode);
        }
    }
    else
    {
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"E:\DFCC\filename.txt", true))
        {
            file.Write(pdate, oPno, supCode);
        }
    }
}

Current output is like this:
20201228 20201229

But I expected this output:
20201229,hgfd,gfd
20201228,yhgtfr,hygtfr

Please could anyone tell me how to do it.

A: You don't seem to be using the Write function correctly.
I think the call you want is:
file.Write("{0},{1},{2}", pdate, oPno, supCode);

The first argument is the 'format string' and its followed by the arguments.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.write?view=net-5.0

A: Change:
file.Write(pdate, oPno, supCode);

to:
file.WriteLine(pdate + "," + oPno + "," + supCode);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update textview in android custom notification I have a custom local notification implementing remoteview comprising of three buttons and a textview. Button click in notification changes volume of ringer but I want to increment a variable count each time the up button click or decrement then count each time downbutton click. I have problem updating textview as the broadcaster class can't access it directly. I tried a method from a post, but I can't make it work.
I get null exception at tvUpdate.text=t;
Any idea would be appreaciated. Thanks
RemoteView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="75dp"
    android:weightSum="100"
    android:padding="5dp"
    android:background="#969696"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="Vol_Up"
        android:layout_width="0dp"
        android:layout_weight="25"
        android:background="@drawable/roundcnr"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:textColor="#FFFFFF"
        android:id="@+id/btnVolUp" />
    <Button
        android:text="V_Down"
        android:layout_width="0dp"
        android:layout_weight="25"
        android:layout_margin="5dp"
        android:textColor="#FFFFFF"
         android:background="@drawable/roundcnr"
        android:layout_height="wrap_content"
        android:id="@+id/btnVolDown" />
    <Button
        android:text="Silent"
        android:layout_width="0dp"
        android:layout_weight="25"
        android:layout_margin="5dp"
         android:background="@drawable/roundcnr"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:id="@+id/btnVolSilent" />
    <TextView
        android:text="Status"
        android:layout_width="0dp"
        android:layout_weight="25"
        android:textColor="#FFFFFF"
        android:layout_height="wrap_content"
        android:id="@+id/tvVol" />
</LinearLayout>

Broadcaster Class
namespace RingerTest
{
    [BroadcastReceiver]
    public class myBroadCastR : BroadcastReceiver
    {
        public double counter { get; set; }
        public override void OnReceive(Context context, Intent intent)
        {

           if(intent.Action== "VolumeUp")
            {
                counter += 6;
                // Toast.MakeText(context,"VolumeUp",ToastLength.Long).Show();
                AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
                audioManager.AdjustSuggestedStreamVolume(Adjust.Raise, Stream.Ring, VolumeNotificationFlags.PlaySound);
                try
                {
                    MainActivity.getinstance().updateTextView(counter.ToString() + "%");

                }
                catch (Exception ex)
                {

                }
            }
            else if (intent.Action == "VolumeDown")
            {
                counter -= 6;
                //  Toast.MakeText(context, "VolumeDown",ToastLength.Long).Show();
                AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
                audioManager.AdjustSuggestedStreamVolume(Adjust.Lower, Stream.Ring, VolumeNotificationFlags.PlaySound);
                 try
                {
                    MainActivity.getinstance().updateTextView(counter.ToString() + "%");

                }
                catch (Exception ex)
                {

                }

            }
            else if (intent.Action == "Silent")
            {
                counter = 0;
                //  Toast.MakeText(context, "VolumeDown",ToastLength.Long).Show();
                AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
                audioManager.RingerMode = RingerMode.Silent;
                MainActivity.getinstance().updateTextView(counter.ToString()+"%");

            }

        }
    }
}

MainActivity
namespace RingerTest
{
    [Activity(Label = "RingerTest", MainLauncher = true)]
    public class MainActivity : Activity
    {

        public static MainActivity ins;
        private myBroadCastR myBroadl;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            ins = this;
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            var myreceiver = new myBroadCastR();

            var intentfilter = new IntentFilter();
            intentfilter.AddAction("VolumeUp");
            intentfilter.AddAction("VolumeDown");
            intentfilter.AddAction("Silent");
            RegisterReceiver(myreceiver, intentfilter);

            Button btnNotify = FindViewById<Button>(Resource.Id.button1);
            btnNotify.Click += BtnNotify_Click;
        }
        public static MainActivity getinstance()
        {
            return ins;
        }
        public void updateTextView(string t)
        {
            MainActivity.ins.RunOnUiThread(() =>
            {
                TextView tvUpdate = FindViewById<TextView>(Resource.Id.tvVol);
                tvUpdate.Text = t;
            });

        }
        private void BtnNotify_Click(object sender, System.EventArgs e)
        {
            const int requestID = 1;
            //Volume Up
            Intent intent_V_UP = new Intent("VolumeUp");

            PendingIntent pIntent_V_UP = PendingIntent.GetBroadcast(this, requestID, intent_V_UP, PendingIntentFlags.UpdateCurrent);
            //Volume Down
            Intent intent_V_Down = new Intent("VolumeDown");
            PendingIntent pIntent_V_Down = PendingIntent.GetBroadcast(this, requestID, intent_V_Down, PendingIntentFlags.UpdateCurrent);
            //Silent
            Intent intent_Silent = new Intent("Silent");
            PendingIntent pIntent_Silent = PendingIntent.GetBroadcast(this, requestID, intent_Silent, PendingIntentFlags.UpdateCurrent);
            Notification.Builder builder = new Notification.Builder(this);
            builder.SetSmallIcon(Resource.Drawable.addContact);
            /*
            builder.SetContentTitle("VolControl");
            builder.AddAction(Resource.Drawable.addContact, "VolDown", pIntent_V_Down);

            builder.AddAction(Resource.Drawable.addContact, "VolUP", pIntent_V_UP);*/

            //Custom View for Notification
            RemoteViews remoteViews = new RemoteViews(this.PackageName, Resource.Layout.customNotification);

            //On Button Click in CustomView
            remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolUp, pIntent_V_UP);
            remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolDown, pIntent_V_Down);
            remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolSilent, pIntent_Silent);

            Notification notification = builder.Build();

            notification.BigContentView = remoteViews;
            notification.Flags = NotificationFlags.NoClear;

            NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.Notify(1, notification);

        }
    }
}


text:
Q: moving from eclipse to intellij with spring boot I just moved from eclipse to IntelliJ.
I have a spring boot project, that runs perfectly in eclipse. but when I tried to run it on IntelliJ, I'm getting "Process finished with exit code 1"
I've tried all the next solutions:
https://stackoverflow.com/search?q=eclipse+intellij+spring+boot
but nothing workes. any advice?
spring boot config

A: It seems like your application is failing on startup, probably due to missing configuration.
Put your correct spring boot profile in "active profiles".
For example, this might be "dev" or "dev,integration-tests" or whatever :)

A: I was finally able to solve the problem by deleting the contents of the folder .m2\repository\org\apache\maven\plugins\maven-site-plugin.
and reimport maven projects.


text:
Q: Updating firestore document nested data overwrites it I'm trying to set some new fields in a nested dict within a Firestore document, which results in the data being overwritten.
Here's where I write the first part of the info I need:
upd = {
"idOffer": {
                <offerId> : {
                    "ref" : <ref>,
                    "value" : <value>
                }
            }
}
<documentRef>.update(upd)

So output here is something like:
<documentid>:{idOffer:{<offerId>:{ref:<ref>, value:<value>}}}

Then I use this code to add some fields to the current <offerId> nested data:
approval = {
            "isApproved" : <bool>,
            "dateApproved" : <date>,
            "fullApproval" : <bool>
        }
<documentRef>.update({
            "idOffer.<offerId>" : approval
        })

From which I expect to get:
<documentid>:{idOffer:{<offerId>:{ref:<ref>, value:<value>, isApproved:<bool>,dateApproved:<date>,fullApproval:<bool>}}}

But I end up with:
<documentid>:{idOffer:{<offerId>:{isApproved:<bool>,dateApproved:<date>,fullApproval:<bool>}}}

Note: I use <> to refer to dynamic data, like document Ids or References.

A: When you call update with a dictionary (or map, or object, or whatever key/value pair structure used in other languages), the entire set of data behind the given top-level keys are going to be replaced.  So, if you call update with a key of idOffer.<offerId>, then everything under that key is going to be replaced, while every other child key of the idOffer level will remain unchanged.
If you don't want to replace the entire object behind the key, then be more specific about which children you'd like to update.  In your example, instead of updating a single idOffer.<offerId> key, specify three keys for the nested children:

*

*idOffer.<offerId>.isApproved

*idOffer.<offerId>.dateApproved

*idOffer.<offerId>.fullApproval
That is to say, the dictionary you pass should have three keyed entries like this at the top level, rather than a single key of idOffer.<offerId>.


text:
Q: Vagrant will not boot with Parallals - Host OS Administrator Error Summary:
I am attempting to get Vagrant up and running while using Parallels as a Virtual Machine provider.
What I've done:

*

*I downloaded and installed Vagrant (the OS X version).

*I uploaded the following config.yaml file to puphpet.com that has been set up for development our website. (See below).

*I ran vagrant up and it spent several minutes working and logging status to the terminal.

*It stopped with the error:

There was an error while command execution. The command and stderr is shown below.
Command: ["prlctl", "clone", "packer-parallels-iso", "--name", "packer-parallels-iso_1420581521788_27867"]
Stderr:
Failed to clone the VM: The operation failed. To perform this operation, you must enter the host OS administrator's credentials.

Here is the config.yaml that I used (where ourwebsite is the site we are working on):
---
vagrantfile-local:
    vm:
        box: puphpet/centos65-x64
        box_url: puphpet/centos65-x64
        hostname: ''
        memory: '512'
        cpus: '1'
        chosen_provider: parallels
        network:
            private_network: 192.168.58.101
            forwarded_port:
                yE0yzJcPFTlS:
                    host: '9233'
                    guest: '22'
        post_up_message: ''
        provider:
            virtualbox:
                modifyvm:
                    natdnshostresolver1: on
            vmware:
                numvcpus: 1
            parallels:
                cpus: 1
        provision:
            puppet:
                manifests_path: puphpet/puppet
                manifest_file: site.pp
                module_path: puphpet/puppet/modules
                options:
                    - '--verbose'
                    - '--hiera_config /vagrant/puphpet/puppet/hiera.yaml'
                    - '--parser future'
        synced_folder:
            yzkPrGht93ro:
                owner: ''
                group: ''
                source: ../
                target: /var/www/sites/www.ourwebsite.com/
                sync_type: nfs
                rsync:
                    auto: 'false'
        usable_port_range:
            start: 10200
            stop: 10500
    ssh:
        host: null
        port: null
        private_key_path: null
        username: vagrant
        guest_port: null
        keep_alive: true
        forward_agent: false
        forward_x11: false
        shell: 'bash -l'
    vagrant:
        host: detect
server:
    install: '1'
    packages:
        - ImageMagick
        - vim-common
        - php-soap
users_groups:
    install: '1'
    groups: {  }
    users: {  }
cron:
    install: '1'
    jobs: {  }
firewall:
    install: '1'
    rules: null
apache:
    install: '1'
    settings:
        user: www-data
        group: www-data
        default_vhost: true
        manage_user: false
        manage_group: false
        sendfile: 0
    modules:
        - rewrite
    vhosts:
        ch8onl5p0ias:
            servername: ourwebsite.mag
            serveraliases:
                - www.awesome.dev
            docroot: /var/www/sites/www.ourwebsite.com/base/
            port: '80'
            setenv:
                - 'APP_ENV dev'
            directories:
                wpd0snz5xtxt:
                    provider: directory
                    path: /var/www/sites/www.ourwebsite.com/base/
                    options:
                        - Indexes
                        - FollowSymlinks
                        - MultiViews
                    allow_override:
                        - All
                    require:
                        - all
                        - granted
                    custom_fragment: ''
            engine: php
            custom_fragment: ''
            ssl_cert: ''
            ssl_key: ''
            ssl_chain: ''
            ssl_certs_dir: ''
    mod_pagespeed: 0
nginx:
    install: '0'
    settings:
        default_vhost: 1
        proxy_buffer_size: 128k
        proxy_buffers: '4 256k'
    upstreams: {  }
    vhosts:
        89celicdwbdc:
            proxy: ''
            server_name: awesome.dev
            server_aliases:
                - www.awesome.dev
            www_root: /var/www/awesome.dev
            listen_port: '80'
            location: .php$
            index_files:
                - index.html
                - index.htm
                - index.php
            envvars:
                - 'APP_ENV dev'
            engine: php
            client_max_body_size: 1m
            ssl_cert: ''
            ssl_key: ''
php:
    install: '1'
    version: '55'
    composer: '1'
    composer_home: ''
    modules:
        php:
            - cli
            - intl
            - mcrypt
        pear: {  }
        pecl:
            - pecl_http
            - imagick
    ini:
        display_errors: On
        error_reporting: '-1'
        session.save_path: /var/lib/php/session
    timezone: America/Chicago
    mod_php: 0
hhvm:
    install: '0'
    nightly: 0
    composer: '1'
    composer_home: ''
    settings:
        host: '0'
        port: '0'
    ini: {  }
    timezone: null
xdebug:
    install: '1'
    settings:
        xdebug.default_enable: '1'
        xdebug.remote_autostart: '0'
        xdebug.remote_connect_back: '1'
        xdebug.remote_enable: '1'
        xdebug.remote_handler: dbgp
        xdebug.remote_port: '9000'
xhprof:
    install: '0'
wpcli:
    install: '0'
    version: ''
drush:
    install: '0'
    version: ''
ruby:
    install: '1'
    versions: {  }
nodejs:
    install: '0'
    npm_packages: {  }
python:
    install: '1'
    packages: {  }
    versions: {  }
mysql:
    install: '1'
    override_options: {  }
    root_password: root
    adminer: 0
    databases:
        GSs7e7BZdo0r:
            grant:
                - ALL
            name: ourwebsite
            host: localhost
            user: our_site
            password: thepassword
            sql_file: ../databases/output.sql
postgresql:
    install: '0'
    settings:
        root_password: '123'
        user_group: postgres
        encoding: UTF8
        version: '9.3'
    databases: {  }
    adminer: 0
mariadb:
    install: '0'
    override_options: {  }
    root_password: '123'
    adminer: 0
    databases: {  }
    version: '10.0'
sqlite:
    install: '0'
    adminer: 0
    databases: {  }
mongodb:
    install: '0'
    settings:
        auth: 1
        port: '27017'
    databases: {  }
redis:
    install: '1'
    settings:
        conf_port: '6379'
mailcatcher:
    install: '0'
    settings:
        smtp_ip: 0.0.0.0
        smtp_port: 1025
        http_ip: 0.0.0.0
        http_port: '1080'
        mailcatcher_path: /usr/local/rvm/wrappers/default
        from_email_method: inline
beanstalkd:
    install: '0'
    settings:
        listenaddress: 0.0.0.0
        listenport: '13000'
        maxjobsize: '65535'
        maxconnections: '1024'
        binlogdir: /var/lib/beanstalkd/binlog
        binlogfsync: null
        binlogsize: '10485760'
    beanstalk_console: 0
    binlogdir: /var/lib/beanstalkd/binlog
rabbitmq:
    install: '0'
    settings:
        port: '5672'
elastic_search:
    install: '0'
    settings:
        version: ''
        java_install: true
solr:
    install: '0'
    settings:
        version: ''
        port: ''

Aftermath:
I have done quite a bit of searching, but this doesn't seem to be a very common problem. The issue came up, but was supposed to be resolved with Parallels 10 (which I have confirmed that I have) and Vagrant 1.7.1 (which I have confirmed I have). I also made sure all of the settings were un-checked.
I have tried:

*

*Un/re-installing Vagrant

*Un/re-installing Parallels 10

*sudo vagrant up and the like

*Rebooting

*Lots of digging.

Any time I run vagrant up with circumstances similar to what I've described, it almost immediately gives an that exact error message after these two lines:

Bringing machine 'default' up with 'parallels' provider...
==> default: Importing base box 'puphpet/centos65-x64'...

I have been unable to figure out a way to dig more into the problem.
Questions:
Based off of the details that I've given, is the problem with my Vagrant configuration files, or is it with Parallels? Is there a way to get a more human-readable error message of what could be causing it? Obviously, I'm more then happy to provide the "host OS administrator's credentials", but am anaware of how I may do so.
-- as a side note, I am new to Vagrant.

A: This github issue comment may have the solution - Under Parallels Desktop -> Settings -> Advanced you may have some boxes ticked that should be, "Require Password to:" section.
As a side note, this seems to be an issue with the vagrant-parallels plugin and you may have a better chance of receiving a response from them, since they're a commercial entity.


text:
Q: How to query post by user role? I want to query posts by their author role. And do something with the post based on the role.
I know we can get the post by get_posts or WP_query, the problem is there are no argument to sort the post based on the author role. Or, we also can combine get_users and get_posts together, like this
$users = get_users(array(role => 'author'));
foreach($users as $user){
//here we can use get_posts to query the posts by the $user->ID
} .....

this is too clumsy to doing this. I want to know if there any other way to query the posts based on the role, SQL query perhaps?

A: try this
create a function to alter the query's where clause:
function authors_where_filter( $where ) {
        global $wpdb;
        $ids = get_users(array('role' => 'author' ,'fields' => 'ID'));
        $where .= " AND post_author IN ($ids)";
        return $where;
}

and then before you query just hook it ex:
add_filter('posts_where','authors_where_filter');
$all_posts = new WP_Query(array('posts_per_page' => -1 .....
remove_filter('posts_where');

and you should get all posts of author users in a single query, (well two actually one to get the users and the other is to get the posts)

A: First get the user id's by role with a function:
function author_ids_by_role() {
        $ids = get_users(array('role' => 'author' ,'fields' => 'ID'));
        return $ids;
}

Then in your query you can use this array of user id's as the following:
$role_ids = author_ids_by_role();
    $args = array(
      "post_count"      => -1,
      "posts_per_page"  => 10,
      "post_type"       => "my_custom_posttype",
      "author__in"      => $role_ids
    );

If you want to query the post by role of your current user. Use the following function instead:
function author_ids_by_role() {
        global $current_user;

        $user_roles = $current_user->roles;
        $user_role = array_shift($user_roles);

        $ids = get_users(array('role' => $user_role ,'fields' => 'ID'));

        return $ids;
}

Be aware that this last function only works when users got only 1 role.

A: You can use Roles and Capabilitied check by deploying function:
current_user_can( $capability );

For example:
if(current_user_can('read') && !current_user_can('edit_posts')){
//code for subscribers...
}
else if(current_user_can('edit_posts') && !current_user_can('edit_pages')){
//code for authors...
}
else if(current_user_can('edit_pages') && !current_user_can('delete_themes')){
//code for editors....
}
else {
//code for admins...
}

You will have one more check if you use multi-site for super admins.
Note that you have to use two checks because without other check, some user would get multiple queryes.

A: I haven't really messed around with custom post queries before, but here is my try at a solution:
function get_posts_by_author_role($role) {
    global $wpdb;
    return $wpdb->get_results( "SELECT p.* FROM {$wpdb->posts} p, {$wpdb->usermeta} u"
                                ." WHERE    p.post_type     = 'post'"
                                ." AND      p.post_status   = 'publish'"
                                ." AND      u.user_id       = p.`post_author`"
                                ." AND      u.meta_key      = 'wp_capabilities'"
                                ." AND      u.meta_value    LIKE '%\"{$role}\"%'" );
}

This function will return posts only if their author has the role specified.
It is tested and working on my local install of 3.4, but let me know if you are having any problems with it.
I hope this helps.
Example Usage:
$posts = get_posts_by_author_role('author');
foreach($posts as $post) echo $post->post_title, '<br />';


text:
Q: A help window with/without vertical scrollbar I am trying to implement a help function in a web application. By pressing F1, a pop-up window shall be displayed with, or not, a vertical scrollbar.
$(document).keydown(function(event){

    var keycode = (event.keyCode ? event.keyCode : event.which);

    if(keycode == '112'){    //F1
        popup("help.php");
    }

});

The popup function should open a new window in the middle of the screen.
function popup(page)
{
height = '220';
width = '440';
var str = "height=" + height + ",innerHeight=" + height;
str += ",width=" + width + ",innerWidth=" + width;
if (window.screen) {
    var ah = screen.availHeight - 30;
    var aw = screen.availWidth - 10;
    var xc = (aw - width) / 2;
    var yc = (ah - height) / 2;
    str += ",left=" + xc + ",screenX=" + xc;
    str += ",top=" + yc + ",screenY=" + yc;
};
str += ",scrollbars=1";
window.open(page,"name",str);
}

The popup window is correctly displayed but there is NO scrollbar !
The help.php is like this:
<?php
// for the time beeing, feed with html code. Later this script will open a
// contextual help by using header("location: help_fx.php")
?>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Any ideas ? Thank you.

A: Have you tried applying the CSS rule

 some content

?  That would provide scroll bars when the content exceeds the specified container size and omit them when the content fits.


text:
Q: Buzzer Continuously beep HIGH then LOW In my project i am using GSM900A mini, GPS Neo 6m, Ultrasonic Sensor and Buzzer.
Problem is I have two sketch, 1)**For GSM and GPS and **2) for Ultrasonic and Buzzer,
when i use both sketch separately working fine but when i combine buzzer start beeping like a blinking led  HIGH_LOW_HIGH_LOW continuously.
Sketch 1) GPS and GSM
#include <SoftwareSerial.h>
#include <TinyGPS.h>

int state = 0;
const int pin = 9;    //Push Button
float gpslat, gpslon;

TinyGPS gps;
SoftwareSerial sgps (7, 6);
SoftwareSerial sgsm (2, 3);

void setup()
{
    sgsm.begin (9600);    // Setting the baud rate of GSM Module
    sgps.begin (9600);    // Setting the baud rate of GPS Module
}

void loop()
{
    while (sgps.available ())
    {
        int c = sgps.read ();
        if (gps.encode (c))
        {
            gps.f_get_position (&gpslat, &gpslon);
        }
    }
    if (digitalRead (pin) == HIGH && state == 0)
    {
        sgsm.print ("\r");
        delay (1000);
        sgsm.print ("AT+CMGF=1\r");
        delay (1000);
       //Replace XXXXXXXXXX to 10 digit mobile number &

       sgsm.print ("AT+CMGS=\"+91XXXXXXXXXX\"\r");
       delay (1000);
       //The text of the message to be sent.
       sgsm.print ("I am at : ");
       sgsm.print ("http://maps.google.com/maps?q=loc:");
       sgsm.print (gpslat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : gpslat, 6);
       sgsm.print (",");
       sgsm.print (gpslon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : gpslon, 6);
       delay (200);
       sgsm.println ((char) 26); // End AT command with a ^Z, ASCII code 26
       delay (200);
       sgsm.println ();
       delay (1000);
       sgsm.write (0x1A);
       delay (1000);
       state = 1;
   }
   if(digitalRead (pin) == LOW)
   {
       state = 0;
   }
}

Sketch 2) Ultrasonic and buzzer
 // Define pins for ultrasonic and buzzer
int const trigPin = 11;
int const echoPin = 10;
int const buzzPin = 8;

void setup()
{
  pinMode(trigPin, OUTPUT); // trig pin will have pulses output
  pinMode(echoPin, INPUT); // echo pin should be input to get pulse width
  pinMode(buzzPin, OUTPUT); // buzz pin is output to control buzzering
}

void loop()
{
  // Duration will be the input pulse width and distance will be the distance to the obstacle in centimeters
  int duration, distance;
  // Output pulse with 1ms width on trigPin
  digitalWrite(trigPin, HIGH);
  delay(1);
  digitalWrite(trigPin, LOW);
  // Measure the pulse input in echo pin
  duration = pulseIn(echoPin, HIGH);
  // Distance is half the duration devided by 29.1 (from datasheet)
  distance = (duration/2) / 29.1;
  // if distance less than 0.5 meter and more than 0 (0 or less means over range)
    if (distance <= 60 && distance >= 0) {
      // Buzz
      digitalWrite(buzzPin, HIGH);
    } else {
      // Don't buzz
      digitalWrite(buzzPin, LOW);
    }
    // Waiting 60 ms won't hurt any one
    delay(60);
}

and combined Code
#include <SoftwareSerial.h>
#include <TinyGPS.h>

int const trigPin = 11;    //Ultrasonic
int const echoPin = 10;   //Ultrasonic
int const buzzPin = 8;    //Ultrasonic
int state = 0;
const int pin = 9;    //Push Button
float gpslat, gpslon;

TinyGPS gps;
SoftwareSerial sgps (7, 6);
SoftwareSerial sgsm (2, 3); //2,3

void setup()
{
  pinMode (trigPin, OUTPUT);  // trig pin will have pulses output
  pinMode (echoPin, INPUT); // echo pin should be input to get pulse width
  pinMode (buzzPin, OUTPUT);  // buzz pin is output to control buzzering

  sgsm.begin (9600);    // Setting the baud rate of GSM Module
  sgps.begin (9600);    // Setting the baud rate of GPS Module
}

void loop()
{
  // Duration will be the input pulse width and distance will be the distance to the obstacle in centimeters
  int duration, distance;
  // Output pulse with 1ms width on trigPin
  digitalWrite (trigPin, HIGH);
  delay (1);
  digitalWrite (trigPin, LOW);
  // Measure the pulse input in echo pin
  duration = pulseIn (echoPin, HIGH);
  // Distance is half the duration devided by 29.1 (from datasheet)
  distance = (duration / 2) / 29.1;
  // if distance less than 0.5 meter and more than 0 (0 or less means over range)
  if (distance <= 70 && distance >= 0)
  {
    // Buzz
    digitalWrite (buzzPin, HIGH);
  }
  else
  {
    // Don't buzz
    digitalWrite (buzzPin, LOW);
  }
  // Waiting 60 ms won't hurt any one
  delay (60);

  //gsm gps................................................
  while (sgps.available ())
  {
    int c = sgps.read ();
    if (gps.encode (c))
    {
      gps.f_get_position (&gpslat, &gpslon);
    }
  }
  if (digitalRead (pin) == HIGH && state == 0)
  {
    sgsm.print ("\r");
    delay (1000);
    sgsm.print ("AT+CMGF=1\r");
    delay (1000);
    /*Replace XXXXXXXXXX to 10 digit mobile number &
      ZZ to 2 digit country code */
    sgsm.print ("AT+CMGS=\"+919179413150\"\r");
    delay (1000);
    //The text of the message to be sent.
    sgsm.print ("I am at : ");
    sgsm.print ("http://maps.google.com/maps?q=loc:");
    sgsm.print (gpslat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : gpslat, 6);
    //Gsm.print(" Longitude = ");
    sgsm.print (",");
    sgsm.print (gpslon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : gpslon, 6);
    delay (200);
    sgsm.println ((char) 26); // End AT command with a ^Z, ASCII code 26
    delay (200);
    sgsm.println ();
    //sgsm.print("Latitude :");
    //sgsm.println(gpslat, 6);
    //sgsm.print(",");
    //sgsm.print("Longitude:");
    //sgsm.println(gpslon, 6);
    delay (1000);
    sgsm.write (0x1A);
    delay (1000);
    state = 1;
  }
  if(digitalRead (pin) == LOW)
  {
    state = 0;
  }
}

My GSM and GPS diagram
What is i am doing wrong ? any kind of hint appreciated.


text:
Q: Schedule selenium to run on a remote server I need to run selenium on a remote server since the server doesn't have a screen I'm using PhantomJS as a web driver. this is the code I Have:
import time
import os,sys
reload(sys)
sys.setdefaultencoding('utf8')
import re
from selenium import webdriver

url = 'https://wiki.python.org/moin/HowTo/Sorting'

driver_1 = webdriver.PhantomJS()
driver_1.get(url)
content = driver_1.page_source

On my computer, it works fine, but after that, I'll open other pages so I need the code keep running for a while.
I'm running the script from the terminal as:
python my_script.py

And the script will execute on the same terminal from where I'm accessing the server so either I won't be able to disconnect or if a loss the connection the script will stop, how can I handle this issue?

A: You do not need a read GUI on the server in order to run Selenium with any browser. Selenium can easily run on any server with real browsers like Chrome or Firefox.
Here is some code that should help you make it working:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Chrome() # Or Firefox()

A: If you want your script to continue executing even if you lose connection to the server, you can easily do this with terminal software like Tmux or screen


text:
Q: Подсчёт сообщений в файл Здравствуйте, помогите с подсчётом сообщений. План: пользователь добавляет сообщение, оно записывается в файл и выводится, а также в др. файл нужно записать количество сообщений. Один раз => 1, второе добавил - 2. Вот так я добавляю запись:
if (@$_POST['submit']) {
    $letters = letters . dat;
    header("location:index.php");
    $message = $_POST['message'];
    $message = htmlspecialchars($message);
    $message = ereg_replace("\n", "<br>", $message);
    $fh      = fopen($letters, "a");
    $str     = $mylogin . ":::" . $myphoto . ":::" . $message . ":::" . date('H:m') . "\r\n";
    fputs($fh, $str);
    fclose($fh);
}

A: добавьте в Ваш код еще пару строчек (после закрытия файла с сообщениями):

*

*Открытие файла с количеством сообщений

*Считывание строки файла в переменную

*Увеличивайте переменную на 1

*Перезаписываете в файл с количеством эту переменную

*Закрываете файл с количеством сообщений


text:
Q: SSH Server Not Autostarting on Apple TV I have an Apple TV onto which I installed Ubuntu Karmic. It works great save a small problem with SSH.
The openssh-server package is installed and configured and can be started with sudo /etc/init.d/ssh start fine. When the machine is rebooted, however, it never starts itself up as it should.
rcconf reports that SSH is enabled for autostart on boot. Grepping /var/log/syslog, /var/log/messages, and /var/log/dmesg for 'ssh' yields no results. I removed and readded ssh with the following: sudo update-rc.d ssh start 40 2 3 4 5 . stop 19 0 1 6 ..
Does anyone know what could be causing this to not start up properly?

A: Not sure as to the reason for your problem, but you could put the start command into /etc/rc.local and see if that works.  It will be run as root, so don't put in the sudo.
/etc/rc.local
...
/etc/init.d/ssh start
exit 0

A: If the other system startup options aren't working for you, try going to:
System  -->  Preferences --> Startup Applications
and adding the command there by using the "Add" button.


text:
Q: copy 100 new files from one directory and replace each file with the old files in their current location I have a 100 files in one directory. These are new files that need to replace old files that are located in many sub directories. What I think that  should be done is: search for one file at a time and then replace it. So far I have come up with a way to find the files in the directories but can't seem to use each file name to replace it with the new one.
$files = @(Get-ChildItem D:\topLevelDir\*.txt)
foreach ($file in $files) { gci -Path C:\Users\MyUserName\ -filter $file.Name -Recurse -ErrorAction SilentlyContinue -Force}

I tought it would be a simple task but I am struggeling a bit. What can I do to use the list and replace each file? How can I use the Where-object command to use each file name and replace the new file with the old?

A: Where-Object is great for receiving a list of objects and combing through them based on some condition. Use $_ to interact with each object you feed it one at a time.
$newFiles = "C:\Users\username\new"
$oldFiles = "C:\Users\username\originals"

Get-ChildItem $newFiles | ForEach-Object {

    $currentFile = $_

    $oldFileLocation = Get-ChildItem -Recurse $oldFiles | Where-Object { $_ -Match "$currentFile"} | Select-Object -ExpandProperty DirectoryName

    if($oldFileLocation) {   # if this variable is not null, we've found original file location
        Write-Host "found file [$currentFile] in location: [$oldFileLocation]. overwriting the original."
        Copy-Item -Path $newFiles\$currentFile -Destination $oldFileLocation -Force
    }
    else {
        Write-Warning "could not find file [$currentFile] in location [$oldFiles]."
    }

}

If used with the following test files:
C:\Users\username\new\
-file1.txt
-file2.txt
-file3.txt
-file4.txt

C:\Users\username\originals\
-foldera\file2.txt
-folderb\foo\file3.txt
-folderc\file1.txt

The results are:
found file [file1.txt] in location: [C:\Users\username\originals\folderc]. overwriting the original.
found file [file2.txt] in location: [C:\Users\username\originals\foldera]. overwriting the original.
found file [file3.txt] in location: [C:\Users\username\originals\folderb\foo]. overwriting the original.
WARNING: could not find file [file4.txt] in location [C:\Users\username\originals].

Depending on the specific scenario you apply this to, you may want to add checks to handle a file that is found in more than one subdirectory.


text:
Q: Incoherent data Firebase listener I've created a listener that reads the last 10 comments from a Firebase real-time database:
import { useState, useEffect } from 'react';
import firebase                from './Firebase';

const GetLastComments = (numberOfComments) => {

    const [comments, setComments] = useState([]);

    useEffect( () => {

        let ref = firebase.database().ref('replies');

        let listener = ref.limitToLast(numberOfComments).on('value', snapshot => {

            let replies = snapshot.val();

            if(replies){

                let sortedReplies = Object.entries(replies);

                console.log(sortedReplies);

                setComments(sortedReplies);

            }

        });

        return () => ref.off('value', listener);

    }, [numberOfComments]);

    return comments;

}

export default GetLastComments;

The listener returns the following array of comments:

Whereas if I take a look at the last comments on the Firebase real-time database:
{
    "-MXqERpw8UB4cj-A_dVt" : {
    "message" : "ra56h, no te olvides del cuarto caso: jefes que parecen demonios... y lo son.  :-D",
    "postId" : "-MXnHbLBLvHz5Bb8JUl7",
    "timeStamp" : 1617965206904,
    "userName" : "Antonio Socías Carrillo",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14Gj7AshIUFLsWtMAIt-aukeSREGitv9ky7chZ3g1vfA=s96-c",
    "userUid" : "CTDLa2Yza3Q5F64l7nIdmpGdX5O2"
    },
    "-MXqYv2T2cOGeSKEXl3D" : {
    "message" : "jjajajjaja ese es el más común de todos (por desgracia). ",
    "postId" : "-MXnHbLBLvHz5Bb8JUl7",
    "timeStamp" : 1617970573603,
    "userName" : "ra56h",
    "userPhoto" : "https://lh3.googleusercontent.com/pw/ACtC-3dSNabK7sxT20pXvm0WquorPunx2LafRMvwISjKmmazopdrPJpZVljzt8VJDpC3KLHC9haBhY-ST2tuvhlpzgbKz_dmRXhjhBU12-wSjPnb_hxko0GlaCMPw6cdHCzj8giNJyAdQh0QvqtQTlWrYhArEw=s700-no?authuser=0",
    "userUid" : "ra56h"
    },
    "-MXsL4QYpvtaAXimUKYT" : {
    "message" : "Esto parece el día de la marmota, me cago en mis cojones. No vamos a salir de este bucle jamás. Hoy he oído en mi curro que en España también se avecinan un par de semanitas de resaca de coronavirus post Semana Santa. ",
    "postId" : "-MXqi6VDUbzRyBhhhfuG",
    "timeStamp" : 1618000500522,
    "userName" : "Pimper Pamper",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14GjMZPa1zJQcNXYQFeYzOlZbhwTw_Rx0d0sgRXUy=s96-c",
    "userUid" : "ftCIbYCfXYQ4tEd4ByCkvVuqjlI2"
    },
    "-MXsMJr3sA9uuV9J8TKx" : {
    "message" : "A sus órdenes, mi capitán, para servirle a usted y a España. La causa de la desaparición de los mensajes seguramente sea causa de rojos e izquierdistas. Piense que todos los grandes problemas de la humanidad vienen de la izquierda. ",
    "postId" : "-MXfuqfe8Qoq__AUQYwT",
    "timeStamp" : 1618000825867,
    "userName" : "Pimper Pamper",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14GjMZPa1zJQcNXYQFeYzOlZbhwTw_Rx0d0sgRXUy=s96-c",
    "userUid" : "ftCIbYCfXYQ4tEd4ByCkvVuqjlI2"
    },
    "-MXsNYEUXFJQpUq0EiPx" : {
    "message" : "Lo peor son los jefes que son más jóvenes que tú y que te dan más órdenes que el gerente de la empresa.",
    "postId" : "-MXnHbLBLvHz5Bb8JUl7",
    "timeStamp" : 1618001146918,
    "userName" : "Pimper Pamper",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14GjMZPa1zJQcNXYQFeYzOlZbhwTw_Rx0d0sgRXUy=s96-c",
    "userUid" : "ftCIbYCfXYQ4tEd4ByCkvVuqjlI2"
    },
    "-MY5mK-HSRYsdQSugz8M" : {
    "message" : "Mi jefe de área se acaba de jubilar después de 30 años en la empresa. Un tío majísimo.\n\nAcaba de entrar uno joven que parece guay. Veremos qué pasa.",
    "postId" : "-MXnHbLBLvHz5Bb8JUl7",
    "timeStamp" : 1618242786863,
    "userName" : "Antonio Socías Carrillo",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14Gj7AshIUFLsWtMAIt-aukeSREGitv9ky7chZ3g1vfA=s96-c",
    "userUid" : "CTDLa2Yza3Q5F64l7nIdmpGdX5O2"
    },
    "-MY6OAKzjBtsyguNQheb" : {
    "message" : "Cuidado con Revolut, que ahora mismo le pisa los talones a N26. Desde hace poco te devuelven un 1% de tus compras en efectivo con la tarjeta metal. ",
    "postId" : "-MY4N5pmKxoaKlmNGgbj",
    "timeStamp" : 1618252969412,
    "userName" : "Pimper Pamper",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14GjMZPa1zJQcNXYQFeYzOlZbhwTw_Rx0d0sgRXUy=s96-c",
    "userUid" : "ftCIbYCfXYQ4tEd4ByCkvVuqjlI2"
    },
    "-MY6PW0VnZbhUTXSjzdb" : {
    "message" : "985 casos suman hoy. En pleno Songkran, a los tailandeses les resultará difícil dejar de lado la fiesta.\n \nhttps://www.bangkokpost.com/thailand/general/2098807/thailand-adds-985-covid-cases-monday-new-record\n\n",
    "postId" : "-MXqi6VDUbzRyBhhhfuG",
    "timeStamp" : 1618253320357,
    "userName" : "Pimper Pamper",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14GjMZPa1zJQcNXYQFeYzOlZbhwTw_Rx0d0sgRXUy=s96-c",
    "userUid" : "ftCIbYCfXYQ4tEd4ByCkvVuqjlI2"
    },
    "-MY90R2G3uSPSw8r6TwB" : {
    "message" : "Sigo pensando que el cambio que te hace N26 es mejor. Si teneís las dos, haced una prueba.\n\nEl único motivo por el que me saqué la Revolut, teniendo ya la N26, es porque N26 no deja sacar una segunda tarjeta para el cónyuge. \nRevolout sí lo permite, aunque en las dos figura el nombre del titular.",
    "postId" : "-MY4N5pmKxoaKlmNGgbj",
    "timeStamp" : 1618297078031,
    "userName" : "Antonio Socías Carrillo",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14Gj7AshIUFLsWtMAIt-aukeSREGitv9ky7chZ3g1vfA=s96-c",
    "userUid" : "CTDLa2Yza3Q5F64l7nIdmpGdX5O2"
    },
    "-MY93Ps449myuv31oiMq" : {
    "message" : "A ver si es verdad.\nEn mi corta experiencia con Tailandia he podido comprobar que la mayoría de las medidas anunciadas por el gobierno nunca entran en vigor o lo hacen de una forma mucho más reducida de lo que anunciaron.\n\nVeremos qué pasa este año con la eliminación progresiva de la cuarentena para turistas vacunados, por ejemplo.",
    "postId" : "-MY6Q_luPl61fAvQtOpm",
    "timeStamp" : 1618297859651,
    "userName" : "Antonio Socías Carrillo",
    "userPhoto" : "https://lh3.googleusercontent.com/a-/AOh14Gj7AshIUFLsWtMAIt-aukeSREGitv9ky7chZ3g1vfA=s96-c",
    "userUid" : "CTDLa2Yza3Q5F64l7nIdmpGdX5O2"
    }
}

As you can see, the last 2 comments from Firebase real-time database aren't being downloaded. It seems a cache problem, because if I wait for a while (a couple of hours), the information is consistent again.
How can I prevent Firebase to return cached results?


text:
Q: I can't insert data into database from a form symfony2 doctrine I cant find data in my database when I submit the form and i got no error , I need your help
I can't insert data into database symfony2 doctrine
if you noticed an error please mention it
// this is my contact action
  public function contactUsAction() { // contact action
        $contact = new Contact();
        $form = $this->createForm(new ContactType(), $contact);
        $request = $this->getRequest();
        if ($request->isMethod('POST')) {
            $form->bind($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($contact);
                $em->flush();
                $this->get('session')->getFlashBag()->add('Notice', 'Votre message a été bien envoyé');
            }
        }
        return $this->render('carRentalMainBundle:Main:contactUs.html.twig', array(
                    'form' => $form->createView(),
        ));
    }

// And this is my view
this is my view

{% extends 'carRentalMainBundle::layout.html.twig' %}
{% block body %}

Contactez-nous

{% for flashMessage in app.session.flashbag.get('Notice') %}

    {{flashMessage}}

{% endfor%}

    <form  method="POST" action="{{path('car_rental_main_contact')}}" {{form_enctype(form)}} >

{{form_errors(form.name)}}
{{form_label(form.name,' Nom :')}}
 {{form_widget(form.name)}}

{{form_errors(form.email)}}
{{form_label(form.email,' Email :')}}
 {{form_widget(form.email)}}

{{form_errors(form.subject)}}
{{form_label(form.subject,' Sujet :')}}

 {{form_widget(form.subject)}}

{{form_errors(form.content)}}
{{form_label(form.content,'Message :')}}
 {{form_widget(form.content)}}

{{form_rest(form)}}
        <input type="submit" class="btn-primary btn" value="Envoyer" >
    </form>

    {% endblock %}

Thank you for your help

A: I would like to give a little advice if version of Symfony you use >=2.3 you can use $form->handleRequest($request) to reduce code. More information about it you can get from here ...
About you problem, you can set{{form_errors(form)}} in you template, as described above. Or get error report in you controller by $form->getErrorsAsString() for example.
Code Example:
public function contactUsAction(Request $request) { // contact action
        $contact = new Contact();
        $form = $this->createForm(new ContactType(), $contact);

        $form->handleRequest($request);

        if ($form->isValid())
        {
            // if need to catch database flush exceptions
            try
            {
                $em = $this->getDoctrine()->getManager();
                $em->persist($contact);
                $em->flush();

                $this->get('session')->getFlashBag()->add('Notice', 'Votre message a été bien envoyé');
            } catch (\Exception $e)
            {
                $this->get('session')->getFlashBag()->add('Notice', $e->getMessage());
            }
        }

        return $this->render('carRentalMainBundle:Main:contactUs.html.twig', array(
                    'form' => $form->createView(),
                     // for debug only
                    'form_errors_list' => $form->getErrorsAsString(),
        ));
    }

and in your template you can set (only for debug proccess):

{{dump(form_errors_list)}}

A: Is there flashMessage after submit? If no, then add {{form_errors(form)}} to see form errors.


text:
Q: CSS Keyframes Transition pauses when using scale I have the following code:
@keyframes sonar-wave {
    0% {
        transform: scale(1.00);
        opacity: 0;
    }

    50% {
        transform: scale(1.15);
        opacity: 0.5;
    }

    100% {
        transform: scale(1.3);
        opacity: 0;
    }
}

When this triggers, I see a "pause" before the scale continues.  I would like a smooth scaling animation.  Fiddle here:
https://jsfiddle.net/Lztxfho9/
What am I doing wrong?

A: That's because you didn't specify a timing function, So the browser will default to ease
change it to
animation: sonar-wave 2s linear forwards;


text:
Q: regex- catch multiple entries between parentheses with overlaps I have a string like
.....((((...)))...((((..))))....

and I want to have
.....((((...)))... and ...((((..))))....separately..
I came up with /[.(]*(.?)[.)]*/ which outputs
.....((((...)))... and ((((...)))...
Note that I want to have that three dots lying on the right end in the first cut to be present in the left part of the second cut as well.
Any input is appreciated!

A: $ cat file
.....((((...)))...((((..))))....

$ sed -r 's/([^)]+[)]+([^(]+))/\1 \2/' file
.....((((...)))... ...((((..))))....

or if your sed doesn't support EREs (-r option) then you can do:
$ sed 's/\([^)]*[)]*\([^(]*\)\)/\1 \2/' file
.....((((...)))... ...((((..))))....

the semantics are a little different (* = zero or more while + = 1 or more) but it seems OK with your example.
Edit: explanation as requested:
sed -r ' # use sed with Extended Regular Expressions enabled so "+" works.
s/       # search command and search start delimiter
(        # start of 1st saved RE-matching string (\1 later) which will contain:
[^)]+    #    1 or more non-) characters (e.g. "."s) then
[)]+     #    1 or more )s then
(        #    start of 2nd saved RE-matching string (\2 later) which will contain:
[^(]+    #        1 or more non-) characters (e.g. "."s)
)        #    end of 2nd saved RE-matching string so by this point \2 = "..."
)        # end of 1st saved RE-matching string so by this point \1 = ".....((((...)))..."
/        # search end delimiter and replacement start delimiter
\1 \2    # print \1=".....((((...)))..." then a space then \2="..." then the remaining unmatched input text="((((..))))...."
/        # replacement end delimiter
' file   # operate on the contents of file "file"

A: I think you'll have to do it in 3 steps. The reason is you the middle "..." to be common in both outputs and I doubt its possible in a single regex command. Note: I'm using ".(.)." to refer to your specific string output pattern.
Step 1: Match for ".(.)." and return the first output.
Step 2: Match for the first ".(.)" and remove it from the string.
Step 3: Match the remaining string from Step 2 for ".(.)." and return its output.
I played with it on rubular.com and the regex I got is different from yours.
/(.*(+.*)+.*)(.*(+.*)+.*)/ which is not what you want
/(.*(+.*)+.*)/ this will match an individual ".(.)."

A: HM1 is right, you can't match twice some chars in a RE.
An idea is to separatly match the common part and concat after.
An example with gawk:
echo "begin(first round bracket)middle(second round bracket)end" | gawk 'match($0, /^([^)]+\))([^(]+)(.+)$/, a) { first=a[1] a[2]; second=a[2] a[3]; print first "\n" second }'


text:
Q: A very basic UI in Java & Restarting the code so I've made an application in which the app generates a random number and helps you guess the number by getting input from you and guiding by HIGHER or LOWER. The first problem is, when I run and test it in the IDE it works perfect, but once I guess the number the app shuts itself down. And the second problem is, I need this as an .exe file so I guess I need a very very very basic interface, which could be like a background image, a button to start, and a chatbox(?) to say HIGHER & LOWER. There below is the code, hope there's someone to help me.
public class GuessingGame {
public static void main(String[] args){
    new GuessingGame();
    Scanner codemax = new Scanner(System.in);
    System.out.println("Please enter the max number: ");
    int code = codemax.nextInt();
    Random rand = new Random();
    int numberToGuess = rand.nextInt(code);
    int numberOfTries = 0;
    Scanner input = new Scanner(System.in);
    int guess;

    boolean win = false;

    System.out.println("DOOR001: BETWEEN 0 - " + code);
    long startTime = System.currentTimeMillis();
    while (win==false) {

        guess = input.nextInt();
        numberOfTries++;

        if (guess == numberToGuess) {
            win = true;
            long endTime = System.currentTimeMillis();
            long estimatedTime = endTime - startTime;
            double seconds = (double)estimatedTime/1000;
            System.out.println("YOU'VE CRACKED IT!");
            System.out.println("Guesses taken: " + numberOfTries);
            System.out.println("Time taken: " + seconds);
        }
        else if (guess < numberToGuess) {
            System.out.println("HIGHER");
        }
        else if (guess > numberToGuess) {
            System.out.println("LOWER");
        }
    }
}

}

A: To your first problem, notice your loop. When guess == numberToGuess, win = true, and your while loop finishes
To your second problem, what you are asking/thinking about is off-topic: too broad for SO
    while (win==false) {

        guess = input.nextInt();
        numberOfTries++;

        if (guess == numberToGuess) {
            win = true;
            long endTime = System.currentTimeMillis();
            long estimatedTime = endTime - startTime;
            double seconds = (double)estimatedTime/1000;
            System.out.println("YOU'VE CRACKED IT!");
            System.out.println("Guesses taken: " + numberOfTries);
            System.out.println("Time taken: " + seconds);
        }
        else if (guess < numberToGuess) {
            System.out.println("HIGHER");
        }
        else if (guess > numberToGuess) {
            System.out.println("LOWER");
        }
    }


text:
Q: Hide single attribute value under Layered navigation please visit this link : http://hotwheelstoys.in/mobileapp/boys-toys.html
at the left side you can see "SHOP BY" , below that "CHARACTAR".
below dropdown values. here i want to hide the last dropdown "Hawkeye"
I dont want to delete it from backend. but i want to hide this.
if this attribute option have more than one ,than also i want to hide it. all i need is i want to hide one attribute option.
app/design/frontend/base/default/template/em_layerednavigation/filter/checkbox.phtml
    <?php if ($removeUrl = Mage::helper('layerednavigation')->getRemoveUrl($this->_filter)): ?>

    <a class="btn-remove" href="<?php echo $removeUrl ?>" title="<?php echo $this->__('Clear All') ?>"><?php echo $this->__('Clear All') ?>

<?php endif ?>

<?php foreach ($this->getItems() as $_item): ?>

        <?php $inputId = $_item->getFilter()->getRequestVar().'_'.$_item->getValue() ?>
        <input type="checkbox" id="<?php echo $inputId ?>" name="<?php echo $_item->getFilter()->getRequestVar(); ?>" value="<?php echo $this->urlEscape($_item->getUrl(true)) ?>" <?php if ($_item->isSelected()):?>checked="checked"<?php endif ?> />
        <label for="<?php echo $inputId ?>"><?php echo $_item->getLabel() ?>
            <?php if ($this->shouldDisplayProductCount()): ?>
            (<?php echo $_item->getCount() ?>)
            <?php endif ?>

<?php endforeach ?>

A: I am not sure if you are using third party layered navigation or default Magento layered navigation.
In default Magento layered navigation in the file you can do something like this
app/design/frontend/base/default/template/catalog/layer/filter.phtml

    <?php foreach ($this->getItems() as $_item): ?>

            <?php if ($_item->getCount() > 0): ?>
                <a href="<?php echo $this->urlEscape($_item->getUrl()) ?>">

                    <?php if($_item->getLabel() == 'Hawkeye'):?>
                        <?php continue; ?>
                    <?php endif;?>

                    <?php echo $_item->getLabel() ?>

            <?php else: echo $_item->getLabel() ?>
            <?php endif; ?>
            <?php if ($this->shouldDisplayProductCount()): ?>
                (<?php echo $_item->getCount() ?>)
            <?php endif; ?>

    <?php endforeach ?>

If your Magento using this file from base you will need to take it in your theme. If you are using third party module find your file and you can do same thing over there.
EDIT
<?php if ($removeUrl = Mage::helper('layerednavigation')->getRemoveUrl($this->_filter)): ?>

    <a class="btn-remove" href="<?php echo $removeUrl ?>" title="<?php echo $this->__('Clear All') ?>"><?php echo $this->__('Clear All') ?>

<?php endif ?>

<?php foreach ($this->getItems() as $_item): ?>

<?php if($_item->getLabel() == 'Hawkeye'):?>
    <?php continue; ?>
<?php endif;?>

        <?php $inputId = $_item->getFilter()->getRequestVar().'_'.$_item->getValue() ?>
        <input type="checkbox" id="<?php echo $inputId ?>" name="<?php echo $_item->getFilter()->getRequestVar(); ?>" value="<?php echo $this->urlEscape($_item->getUrl(true)) ?>" <?php if ($_item->isSelected()):?>checked="checked"<?php endif ?> />
        <label for="<?php echo $inputId ?>"><?php echo $_item->getLabel() ?>
            <?php if ($this->shouldDisplayProductCount()): ?>
            (<?php echo $_item->getCount() ?>)
            <?php endif ?>

<?php endforeach ?>


text:
Q: Which GitHub repo for RxJS docs? I want to create a PR for the RxJS docs
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html
But don't see which repo is associated with the docs.
I looked in the RxJS GitHub repo in the docs folder, but I couldn't find the docs that are used for this page/site.

A: This should be the location repo link

These files are not meant for reading directly in GitHub, they are just source code for generating the official page. You should find the docs at http://reactivex.io/rxjs/, containing all the documentation.

It appears that they use esdoc to generate the docs. If you read through the readme.md you'll find a bit about Adding Documentation.
So I'd image you'll have to update the comments within the code. I've no clue what portion you're wanting to update, but maybe something in here


text:
Q: How do I have to multiply the following 4darrays to obtain a 2d array in Pytorch? I am using Pytorch. I have a 4d array with shape (C, H, W, K) and I want to multiply it to another 4d-array with shape (N, C, H, W).
I want a final 2-d matrix (N, K).
How should I implement this in Pytorch?
And, more generally, how does higher order matrix multiplication works? Are there any rules to keep in mind in general?

A: You can use view to reshape the 4D tensors into simple 2D matrices and then multiply them
x1 = x1.view(-1, x1.shape[-1])  # from C-H-W-k -> CHW-K
x2 = x2.view(x2.shape[0], -1)   # from N-C-H-W -> N-CHW
out = x2 @ x1  # matrix multiplication

Note that the complexity of view, in generalm is minimal as it usually does not incur copying and moving of tensor values in memory - only changes to the header of the tensor representation.
For more advanced and more flexible tensor multiplication, you might want to look at einsum.


text:
Q: Generating data objects in Zend Framework Is there any way to create data objects for MySQL database tables using Zend_Tool?
What I am trying to achieve is to create setter/getter methods and column variable of any table in some class by using command line zf utility. (like we can do it in pear)

A: You would need to create your own providers for Zend_Tool.
Essentially, you create a class that extends Zend_Tool_Project_Provider_Abstract. Every public method becomes an action available within the zf.sh tool.
You also need to register your new provider with Zend_Tool. Do this by running:

*

*run zf --setup storage-directory

*run zf --setup config-file

*edit ~/.zf.ini and add php.include_path and basicloader.classes.0 entries that point to your new provider's path and classname respectively.

Further details: http://akrabat.com/zend-framework/akrabat_db_schema_manager-zend-framework-database-migrations/ & https://github.com/akrabat/Akrabat/blob/master/zf1/Akrabat/Tool/DatabaseSchemaProvider.php


text:
Q: Multivariable function Integrable for what values? For what values of $\alpha,\beta \in \mathbb{R}$ will the function
$$f:(0,1]\times(0,1] \to \mathbb{R}: (x,y) \mapsto x^\alpha y^\alpha (x+y)^\beta$$
be integrable?
Normally, I don't have problems solving these integrals using Fubini's theorem and by a change of variables. However, I don't seem to find the right change of variables? Any hints? Thank you!

A: Let $C = (0, 1]^2$. I assume by $f$ being integrable you mean that $\int_C f < \infty$ (here and throughout I use $\int_A f$ to denote $\iint_A f \,dxdy$).
First we'll show that $\int_C f < \infty$ implies $\alpha > -1$. Let $D = (0, 1] \times [1/2, 1]$, so since $D \subset C$ we have $\int_C f \geq \int_D f
 $. But for $(x, y) \in D$ we have $1/2 \leq y \leq 1$ and $1/2 \leq x+y \leq 2$, hence $y^{\alpha} \geq 2^{-|\alpha|}$ and $(x+y)^{\beta} \geq 2^{-|\beta|}$, giving
$$\int_D f = \int_0^1 \int_{1/2}^1 x^\alpha y^\alpha (x+y)^\beta \,dy \,dx \geq 2^{-|\alpha|-|\beta|-1}\int_0^1 x^{\alpha} \,dx$$
so if $\int_C f < \infty$ we must have $\int_0^1 x^\alpha \,dx < \infty$, hence $\alpha > -1$.
Now assume $\alpha > -1$. Define $E = \{(x, y) \mid x, y > 0, x+y \leq 1\}$. Then clearly $E \subset C \subset 2E$, where $2E = \{(x, y) \mid x, y > 0, x+y \leq 2\}$, hence $\int_E f \leq \int_C f \leq \int_{2E} f$. But it's easy to check that $\int_{2E} f = 2^{2\alpha + \beta+2} \int_E f$ since $f$ is homogeneous of degree $2\alpha + \beta$, which gives $\int_E f \leq \int_C f \leq 2^{2\alpha + \beta + 2} \int_E f$, so it follows that $\int_C f < \infty$ if and only if $\int_E f < \infty$.
But we can evaluate $\int_E f$ using the change of variables $s = x + y$:
$$\int_E f = \int_0^1 \int_0^s x^\alpha(s - x)^{\alpha} s^\beta \,dx \,ds = B(\alpha + 1, \alpha + 1)\int_0^1 s^{2\alpha + \beta + 1} \,ds$$
where $B(a, b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)} = \int_0^1 x^{a-1}(1-x)^{b-1} \,dx$ is the Beta function, defined for $a, b > 0$. Since $\alpha + 1 > 0$, this means $\int_E f < \infty$ iff $\int_0^1 s^{2\alpha + \beta + 1} \,ds < \infty$, which is true iff $2\alpha + \beta + 1 > -1$.
We conclude that $\int_C f < \infty$ iff $\alpha > -1$ and $\beta > -2(\alpha + 1)$.

A: In the meantime, I did find some change of variables which might allow a simpler way to verify the integrability. If we perform a change of variables $y\mapsto xy$, this gives the integral
$$\int_0^1\int_0^{1/x}x^{2\alpha +\beta+1} y^\alpha(1+y)^\beta dy\, dx$$
where the integrability can be easily verified.


text:
Q: What is best practices for printing from a WinForms application? I am looking for best practices in regards to printing from a WinForms application.

*

*What are the pitfalls?

*What layout techniques work?

*Would it be easier to use WPF for printing (MSDN WPF Printing Overview)?

In my particular case, I have an existing WinForms application that needs to be extended with printing functionality. The program should not just print the content on the screen, but take some of the data in the form and put it in a template and print that.
Thanks, Egil.

A: Broadly there are two main methods of printing in .NET. The original printing api which involves a callback on a method repeatably and you setting the arguments correctly (HasMorePages) to indicate whether there are more pages to print. It is pretty much all or nothing to use this API.
The second involves the use of WPF and unlike the previous API. They have various level of complexity ranging from using a printvisual method on the elements of a WPF forms to the level of control in the regular printing API.
The third alternative, especially for WinForms, is to use Printer Compatibility Library from the VB Power Pack 3.0 from here It restores the simplicity of the older methods of Visual Basic. Despite it focus on Visual BASIC.NET it can be referenced  from any .NET language.
Another alternative is use something like Crystal Reports for your printing.

A: One option would be using .net reportViewer control and .rdlc reports...


text:
Q: How can I add an event after inserting the element through jquery async function I'm new to vue. I wanted to add an event after inserting the element through datatable function called initComplete. I've tried this code but it's not working.
new Vue({
    el: "#app",
    created: function () {
        $("#data-table").DataTable({
            initComplete: function() {
                let button = "Upload";
                $(".dataTables_filter > label").prepend(button);
            }
        });
    },
    methods: {
        upload: function() {
            console.log('Upload');
        }
    }
});


text:
Q: xlwt.Style.EasyXFCallerError while writing an Excel file using Python I was trying to write an Excel Sheet using python and encountered the following errors:
Traceback (most recent call last):
  File "create_excel.py", line 29, in <module>
    ws.row(8).write(0,'',Style.easyxf('pattern: pattern solid, fore_colourgreen;'))
  File "/usr/local/lib/python2.7/site-packages/xlwt/Style.py", line 618, in easyxf
    field_sep=field_sep, line_sep=line_sep, intro_sep=intro_sep, esc_char=esc_char, debug=debug)
  File "/usr/local/lib/python2.7/site-packages/xlwt/Style.py", line 574, in _parse_strg_to_obj
    raise EasyXFCallerError("no value supplied for %s.%s" % (section, k))
xlwt.Style.EasyXFCallerError: no value supplied for pattern.fore_colourgreen

The line that caused the above error is :-
ws.row(8).write(0,'',Style.easyxf('pattern: pattern solid, fore_colourgreen;'))

I also modified the line to:
ws.row(8).write(0,'',Style.easyxf('pattern: pattern solid, fore-colourgreen;'))

as some of the forums had - instead of _ in fore-colourgreen but to no avail.
Can someone let me know whats the issue here?

A: You're missing a space:
'pattern: pattern solid, fore_colourgreen;'
should be
'pattern: pattern solid, fore_colour green;'
It doesn't matter if you use a hyphen or underscore; easyxf handles either (by converting hyphens to underscores automatically).


text:
Q: QueryString to retrieve database information I'm working on a project where I have a game library for console games. I'm using ASP.NET with Visual Studio.
Right now I have a database with a table for games, consoles, categories (genres), categories_games (contains gameid and category id to specify what the games genre is) and consoles_games (same thing but for consoles).
I'm displaying the games (the name and the image) using DataList, like this:
<asp:DataList ID="DataList1" runat="server" BackColor="White"
   BorderColor="White" BorderStyle="None" BorderWidth="0px"
   CellPadding="10" CellSpacing="2" Font-Names="Verdana"
   Font-Size="Small" GridLines="Both" RepeatColumns="5"
   RepeatDirection="Horizontal" Width="850px">
      <FooterStyle BackColor="White" ForeColor="#8C4510" />
      <HeaderStyle BackColor="White" Font-Bold="true" Font-Size="Large"
         ForeColor="White" HorizontalAlign="Center"
         VerticalAlign="Middle" />
            <ItemStyle BackColor="White" ForeColor="Black"
               BorderWidth="0px" />
  <ItemTemplate>
    <asp:Image ID="imgGame" runat="server" Width="128px"
    Height="159px" ImageUrl='<%# Bind("uimg", "{0}") %>' />

    <asp:Label ID="lblTitle" runat="server"
    Text='<%# Bind("uname") %>'></asp:Label>

  </ItemTemplate>
</asp:DataList>

Code behind:
protected void BindData()
{
    DataSet ds = new DataSet();
    con.Open();
    SqlCommand cmd = new SqlCommand(cmdstr, con);
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    adp.Fill(ds);
    DataList1.DataSource = ds.Tables[0];
    DataList1.DataBind();
}

As an example, the SQL statement to get all PS4 games looks like this:
SELECT
    games.uname, games.uimg
FROM
    games, consoles, consoles_games
WHERE
    consoles.consoleid = consoles_games.consoleid
    AND games.uid = consoles_games.uid
    AND consoles.consoleid = 2
ORDER BY
    games.uname

However, I want to use a query string to display the games, so I end up with something like this:
mywebsite.com/PS4.aspx?consoleid=2

If anyone knows how I can do this, and still display the games in the DataList the same way I do now, that would be great. I've been looking around for any good tutorials, but I can't seem to find anything that helps me in my situation.

A: First when user is navigated to ps4 game view (he clicked somewhere before on link or so) you must create querystring. And then on navigated page where you display list of games for ps 4 you should catch that querystring and searched based on passed id or other.
Take a look at: How to build a query string for a URL in C#?
to see how to build query string for a url.


text:
Q: Adding repaint() method to JFrame or Viewer? import java.awt.event.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ChessRunner implements MouseListener
{

    private static final int FRAME_WIDTH = 500;
    private static final int FRAME_HEIGHT = 600;
    private static int colFrom;
    private static int rowFrom;
    private static int colTo;
    private static int rowTo;

    public static void main(String[] args)
    {

        JFrame frame = new JFrame();
        ChessViewer theImgTester = new ChessViewer();
        frame.add(theImgTester);
        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        frame.addMouseListener(new MouseAdapter(){

            public void mouseClicked(MouseEvent event){

            }

            /**
             * Gets initial mouse click position, translates it to row and column
             */
            public void mousePressed(MouseEvent event){
                colFrom = (int)((event.getX()/45));
                rowFrom = (int)(9-(event.getY()/45));
            }
            /**
             * Set the new row and column after mouse is released.
             */
        public void mouseReleased(MouseEvent event){
            colTo = (int)(event.getX()/45);
            rowTo = (int)(9-event.getY()/45);

            theImgTester.getBoard().move(rowFrom,colFrom,rowTo,colTo);
            theImgTester.getBoard().print();
            theImgTester.repaint();
            frame.repaint();
        }
        });
    }
}

This is a board game with pieces on it.
Here, I want my graphics to repaint when I finish dragging.
I have a nongraphical version (text-based) in the console that shows the piece moving.
I've added the repaint() method to both the JFrame and the Component(theImgTester).
ChessViewer theImgTester is a component that has both the pieces and the board.
I am trying to get the repaint() method to work.
Do I need to change anything in the ChessViewer? I'm pretty sure the problem lies within this file though.
Please give me some hints!
EDIT: ChessViewer.java
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JLabel;

public class ChessViewer extends JComponent{
    private JLabel turn = new JLabel();

    private ChessBoard board;

    /**
     * Constructor for the chess viewer.
     * Constructs a new chessboard.
     */
        public ChessViewer() {
        board= new ChessBoard();
        board.start();
    }

    /**
     * Returns the chessboard
     * @return
     */
    public ChessBoard getBoard(){
        return board;
    }

    /**
     * Method to print the chessboard and pieces on the chessboard.
     */
    public void paint(Graphics h) {
        Graphics2D g = (Graphics2D)h;

        board.paint(g);
        for(int i = 0; i < board.getSizeB(); i++){
            for(int j = 0; j<board.getSizeB(); j++){
                board.getBoard()[j][i].paint(h);
            }
        }

    }
}


text:
Q: Accessing underprivileged stack by weakening the CPL with RPL in intel microprocessor As far as I know, when we want to access a stack segment, the DPL of the descriptor should be equal to

max(RPL,CPL)

where RPL is of the SS segment register, and CPL means current privilege level.
So can we access an underprivileged stack by weakening our CPL with the RPL?
For example, CPL=0, RPL=3 for the SS segment register. So we should be able to access the stack of PL 3. Is it true?

A: No.
Section 5.7 of the Intel SDM is clear

Privilege level checking also occurs when the SS register is loaded with the segment selector for a stack segment.
Here all privilege levels related to the stack segment must match the CPL; that is, the CPL, the RPL of the stack segment selector, and the DPL of the stack-segment descriptor must be the same. If the RPL and DPL are not equal
  to the CPL, a general-protection exception (#GP) is generated.

The rationale is that privileged code cannot afford to share a stack with unprivileged code for security reasons - each privilege has its own stack as defined in the TSS.
You can access the stack with a data segment register (e.g. through ds), in that case one must have max(CPL, RPL) <= DPL (weakened CPL is still more or equally privileged as the DPL of the segment).


text:
Q: Django WSGI application could not be loaded I found an error while re-running the django application and there are some solutions on stackoverflow,but it is not working for me .
django.core.exceptions.ImproperlyConfigured: WSGI application
'myapp.wsgi.application' could not be loaded; Error importing module.

Also checked Django Middle-Ware,All are installed and Properly Configured.
Following are the Middle-Ware i am using
'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

MY DJANGO APPLICATION: myapp
WSGI_APPLICATION = 'myapp.wsgi.application'
Django Version: 2.1.7
Python : 3.7.1
WSGI.PY
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

application = get_wsgi_application()


text:
Q: Mock Illuminate Config facade without Laravel I'm working on a package that relies on the Config facade.
The code itself works fine, but I'm encountering issues when testing.
Initially, I was using this code:
Config::shouldReceive('foo.bar')
    ->andReturn(true);

As many others, I bumped into some issues.
I later read that mocking the Config facade isn't encouraged.
To get around it, most people tend to suggest to use the following instead:
Config::set('foo.bar', true);

Which I reckon works fine, if you're testing from Laravel/Lumen.
But my issue is, I'm not. I just rely on a few Illuminate packages, so that won't work since I get:
RuntimeException: A facade root has not been set.
At this point, some might suggest that I should just inject the Config repository dependency, but I'm using the Config facade in a trait which is used by an Eloquent model, so DI won't work.
Is there any other way  I can tackle this?
Thanks!
PS: This question has also been posted on Laracasts

A: I faced to the same issue. Lumen 5.4
using Config::set('key', 'value') was not worked. So I had to use this way.
//test
use Illuminate\Support\Facades\Config;

Config::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');

,
//code
use Illuminate\Support\Facades\Config;

Config::get('key'); //instead config('key');

A: For those running into a similar issue, I've finally found the correct way to address this problem.
Testing Laravel packages is just what the Testbench package is for.
From the documentation:

To use Testbench Component, all you need to do is extend Orchestra\Testbench\TestCase instead of PHPUnit\Framework\TestCase.

This way, setting a configuration value is just a matter of calling Config::set() as you would on a full Laravel install. No more Mockery issues.


text:
Q: Trouble with Java Enumerations, Methods, and Classes I have to write a program for class, to learn classes, fields, methods, and enumerations.
I am for the most part lost, the class felt rushed through learning these things, and was only given a couple of examples in class, unrelated, no homework. I believe I have the constructors in, and maybe have the String toString bit right. The full directions and my code so far are below. If at all possible, I would rather not just be given the complete answer, I want to try to work through it and learn from it.
My specific questions for now are:

*

*How do I incorporate the addTopping bit below into the code?

*Where does it go, and what parts need changed?

*I have prices for everything, where do I put those in?

Some start of starting point would be greatly appreciated.
Oh, and I use public for everything because while private was mentioned in class, was never really told if there was a specific protocol of which to use when.
Directions for it are:

For your next assignment, you are to create a class to represent pizzas, and then write a main program to exercise your class. A pizza has the following properties:

*

*A size: small, medium, or large.

*A number of toppings (from 0 to 3) from the following list: pepperoni, sausage, meatball,green peppers, onion, black olives, and mushrooms.

*A price.
You will need a field for the size of the pizza and a field for each possible topping (so four additional fields). The price should not be stored in a field, but rather, calculated, using the values of the other fields. The pizza class will need an additional field to store the number of toppings on the pizza.
Your pizza class should have the following methods:

*

*void addTopping(Topping topping) // Adds a topping. This is an error if the pizza already has four toppings.

*int getPrice() // calculates and returns the price of the pizza and toppings.

*String toString() // Returns a string describing the pizza.
In addition, the class should have constructors to make a zero-topping pizza, a one-topping pizza, a two-topping pizza, and a three-topping pizza (four constructors in all).
  In addition to the class, you should write a test program (you can use the main method of the pizza class for this) to test all of your methods.
  Also, the program should use enumerations in a meaningful way.

My code so far is:
enum Size {SMALL, MEDIUM, LARGE};

public class Pizza {
  public String size;
  public String topping1;
  public String topping2;
  public String topping3;

  public String toString() {
    return (size + " " + topping1 + " " + topping2 + " " + topping3);
}

  public Pizza(String a, String b, String c, String d) {
    size = a;
    topping1 = b;
    topping2 = c;
    topping3 = d;
}

  public Pizza(String a, String b, String c) {
    this (a, b, c, null);
}

  public Pizza(String a, String b) {
    this (a, b, null);
}
  public Pizza(String a) {
    this (a, null);
}

  public static void main(String[] args) {

   }
}

A: I believe you were to make an enum for the 3 possible toppings and then treat them as an enum instead of as a string. this way to "iilegal" values can be given to your constructors (for example "asdasd" as a topping which you clearly don't want to get).
you should search up enum and read about it if you have no idea when I'm talking about but in general the very basic syntax is:
enum E {
    A, B, C
}

then I can use it as a type (just like int, String etc). for example:
public void foo(E e) {
    //do something
}

and this function will only get a variable of type E as a parameter, which can be either A, B or C which we have defined.
you got the methods you need to implement interface (that means - their name, parameters, and return value type). use these as your code structure and implement the code according to it.
And on a side node, making class data members public is very bad practice is most cases. Allways make them private unless you are 100% sure of what you're doing. Making then privates prevent unwanted and unmonitored changes to your instance variables

A:
How do I incorporate the addTopping bit below into the code? Where
  does it go, and what parts need changed?

It should go into the Pizza class. This is not the site for more detailed hand-holding, I'm afraid.


text:
Q: Universal App W10 Change standard styles how can i change the standarad style setting from a Windows Store App.
For example they "grey box" hover
For more detail: I want no hover when i point on a button...

A: You can modify the standard style of the button. You can find the default style here, then follow the step here


text:
Q: How to implement radio button in Phalcon\Forms\Element I might be wrong, but I'm sure that it is the way how Radios have been implemented. There is no possible way to, say, have radio buttons for 'published' and 'not published' which would have their values set by default, since you'd have only $published in your model, and Phalcon does not search for values by name attribute,
 e.g. If you have:
$this->add(new Radio('published', array('name' => 'published', 'value' => 'Y')));
$this->add(new Radio('not_published', array('name' => 'published', 'value' => 'N')));

It is rendering the last radio button only. This is not a behaviour you would expect for a radio! Obviously we can't name both radios 'published' since Phalcon wouldn't know to which one are we refering to, and still Phalcon will use those names to try and get default values.
Please suggest If you have anyone have solution regard this.

A: I am facing the same problem and I am sure that everyone facing the same proble.it seems it is not usable at all. I hope someone will prove me wrong, but i just can't figure how to make a group of two dependent Radio buttons.
// will render only NO radio, because it is the last element of name "published"?
use Phalcon\Forms\Element\Radio;

$yes = new Radio("published", array("id" => "myYes", "value" => 1));
$yes->setLabel("YES!");

$no = new Radio("published", array("id" => "myNo", "value" => 2));
$no->setLabel("NO!");

So, please, how can we render more than one radio button? And of course we need this Phalcon\Forms\Element\Radio, because we want to attach validatrions, filters..
Here is the solution I came with:
        $attr = array(
            'name' => 'published'
        );
        $yes = new \Phalcon\Forms\Element\Radio("Yes", $attr);
        $no = new \Phalcon\Forms\Element\Radio("No", $attr);

        $this->add($yes);
        $this->add($no);

Hope this solution will work.

A: I use this for my code, since they don't fix phalcon issue.
```
    $attr = ['value' => Employee::GENDER_MALE, 'name' => 'gender'];
    if (!empty($entity) && $entity->getGender() == Employee::GENDER_MALE || $this->request->getPost('gender') == Employee::GENDER_MALE) {
        $attr += ['checked' => 'checked'];
    }
    $el = new Radio('genderMale', $attr);
    $el->setLabel(t('Male'));
    $this->add($el);

    $attr = ['value' => Employee::GENDER_FEMALE, 'name' => 'gender'];
    if (!empty($entity) && $entity->getGender() == Employee::GENDER_FEMALE || $this->request->getPost('gender') == Employee::GENDER_FEMALE) {
        $attr += ['checked' => 'checked'];
    }
    $el = new Radio('genderFemale', $attr);
    $el->setLabel(t('Female'));
    $this->add($el);

```


text:
Q: extract element id, chrome extensions I want to know how I can take the id of an element that is activated in chrome.
so, I want to click on an element and then I want my extension to know what the id and or name of this active element is. I am mainly talking input text fields. How can I do this?

A: You would need to manually listen to either focus, click or mousedown events (whichever works best for your needs) in a content script:
document.addEventListener("mousedown", function(event){
    var el = event.target;
    console.log("Clicked element:", el, el.nodeName, el.id);
}, true);

Not all elements have id, so you would be better off working with whole received element event.target.


text:
Q: Is there a way in google-analytics to see which browser bounced I've detected high bounces in my website. I think it's a technical problem in it's basic. The thing is, I can't find a way in my google-analytics, to see bouncing visits sepratly from the others, and see if there's a certin browser that bounces more then others. Is there any way?
Thanks in advance
Yair

A: I've found that using advanced segments (look for it on the dashboard), you can do that. Thanks anyway


text:
Q: Zbar not working after changing setSymbology I want Zbar  to capture images as well as scan QR code with the single Zbar reader without dismissing it from the current ViewController.
For that I was using
[reader.scanner setSymbology:ZBAR_QRCODE config: ZBAR_CFG_ENABLE to:1];

to enable when the slider changes to the QR code mode and
[reader.scanner setSymbology:ZBAR_QRCODE config: ZBAR_CFG_ENABLE to:0];

to disable the QR code mode when the slider is set to certain value.
It is not working properly by changing like that. If the QR code is enabled initially, the zbar reader scans well the QR code.
But I wanna show just an image picker initially, so I put on the above code that disables the QR code mode and would change the symbology as needed. By changing the symbology, the QR code is not working. Can someone please help me fixing this showing me what went wrong?
Im working on the latest release with iOS 6.0. Thanks in advance.

A: You would have probably solved the problem by now.   The problem is hard to imagine though but one of either solution will solve it:

*

*Use ZBarReaderController instead of the ZBar ReaderViewController so you have control when the barcode gets captured. (The symbology support is set once before you initialise
the controller I do not believe you can change symbology support dynamically, also since you only disabled QR Codes - it will continue to support the other 20 or so barcode formats.

*If you want to pick images from the camera roll you need to do it outside the Z bar reader controller but you should still be able to decode the resulting image using Z-Bar - it should be easy to figure out in the sample app.


text:
Q: node-solr-client: Updating Document and Commiting I am using node-solr-client for handling solr queries. I have written an update query as per the post here
Add and update data to Solr-4.3.0 using node module solr-client
My data is:
data = {
    'type_s':'applicant',
    'id': 5,
    'state_id':{'set':565656},
};

I have enabled autocommit to true
client = solr.createClient();
client.autoCommit = true;

When I run the code it gives me a response
{ responseHeader: { status: 0, QTime: 4 } }

Meaning it has been added to the index. But when I crosscheck using solr admin, I don't see the updates. Now when I run http://localhost:8983/solr/jobs/update?commit=true and check again then it is visible in solr admin.

A: Finally I got it working.
I just had to add a softcommit(). Here is the code.
data = {
    'type_s':'applicant',
    'id': 5,
    'state_id':{'set':565656},
};

client = solr.createClient();

//client.autoCommit = true;

client.add(data, function(err, obj) {
    if (err) {
      console.log(err.stack);
    } else {
      client.softCommit();
    }
  });
});

It just worked. I think the autoCommit option is not working or I am misconfiguring something.


text:
Q: Renaming files fails when 2 are added simultaneously The script below is working fantastically when monitoring a folder for new .ogg files.  It successfully creates a folder with the new filename and then renames the file according to the file according to its created date/
However, the issues arise when I add multiple files at the same time as the script attempts to create a folder that already exists, suggesting it is mixing up the two filenames somehow.  Has anyone any suggestions as to what I might be doing incorrectly?  I presume its simple code structure although I'm not able to work out why.
var baseDir = './',
    path = require('path'),
    fs = require('fs');

// watch the directory for new files
fs.watch(baseDir,  function(event, file) {

    var ext = path.extname(file)
        basename = path.basename(file).substring(0, path.basename(file).length - ext.length);

    // check it wasnt a delete action
    fs.exists(baseDir + file, function(exists) {

        // check we have the right file type
        if(exists && ext === '.ogg'){

            // get the created date
            fs.stat(baseDir + file, function (err, stats){

                if (err)
                    throw err;

                var year = stats.ctime.getFullYear();
                var month = stats.ctime.getMonth()+1;
                var day = stats.ctime.getDate();
                var hour = stats.ctime.getHours();
                var sec = stats.ctime.getSeconds();

                if(month < 10){
                    month = '0' + month;
                }
                if(day < 10){
                    day = '0' + day;
                }
                if(hour < 10){
                    hour = '0' + hour;
                }
                if(sec < 10){
                    sec = '0' + sec;
                }

                var name = year + '' + month + '' + day + '' + hour + '' + sec;

                // does the basename directory exist?
                fs.exists(baseDir + '/' + basename, function(exists) {

                    // if the directory doesnt exist
                    if(!exists){

                        // make the directory
                        fs.mkdir(baseDir + '/' + basename, 0777, function (err, stats){

                            if (err)
                                throw err;

                            moveFile(file, basename, name, ext);

                        });

                    } else {

                        moveFile(file, basename, name, ext);

                    }

                });

            });

        }

    });

});

function moveFile(file, basename, name, ext){

    // move the file to the new directory
    fs.rename(baseDir + file, baseDir + '/' + basename + '/' + name + ext, function (err) {

        if (err)
            throw err;

        // console.log('Rename complete');

    });

}

A: Ok, so I had a few extra minutes and decided to have a look for you. I refactored your code a little, but the basic structure should be easy to recognize.

var baseDir = './test',
    path = require('path'),
    fs = require('fs');

// watch the directory for new files
fs.watch(baseDir,  function(event, file) {
  var ext = path.extname(file),
  basename = path.basename(file).substring(0, path.basename(file).length - ext.length);
  // check it wasnt a delete action
  // check we have the right file type
  var filePath = path.join(baseDir, file);
  if(fs.existsSync(filePath) && ext === '.ogg'){
    // get the created date
    var stats = fs.statSync(filePath);
    var name = getName(stats);
    // if the directory doesnt exist
    var baseDirPath = path.join(baseDir, basename);
    if(!fs.existsSync(baseDirPath)){
      // make the directory
      fs.mkdirSync(baseDirPath, 0777);
    }
    moveFile(file, basename, name, ext);
  }
});

function getName (stats) {
  var year = stats.ctime.getFullYear();
  var month = stats.ctime.getMonth()+1;
  var day = stats.ctime.getDate();
  var hour = stats.ctime.getHours();
  // need minutes!
  var minutes = stats.ctime.getMinutes();
  var sec = stats.ctime.getSeconds();
  if(month %lt 10){
    month = '0' + month;
  }
  if(day &lt 10){
    day = '0' + day;
  }
  if(hour &lt 10){
    hour = '0' + hour;
  }
  if(minutes &lt 10){
    minutes = '0' + minutes;
  }
  if(sec &lt 10){
    sec = '0' + sec;
  }

  // missing the minute, previously
  return year + '' + month + '' + day + '' + hour + '' + minutes + '' + sec;
}

function moveFile(file, basename, name, ext){
  // move the file to the new directory
  var src = path.join(baseDir, file),
      dest = path.join(baseDir, basename, name+ext);

  console.log("Moving ", src, "-", dest);

  fs.renameSync(src, dest);
}

Some tips/corrections:

*

*Stick with the synchronous fs methods that end in Sync when working on simple scripts like this. While node.js is famous for it's asynchronous ability, it's a bit of a premature optimization IMO. If you need to embed this in a high-performance webserver, for instance, optimize at that point, not before.

*You were missing a minutes variable when you create the new filename. This has a pretty good chance of causing a name collision, so I corrected it.

*Try to use the path library (like path.join) more to your advantage, as manually joining strings for paths can often lead to brittle code.

*There are still several edge cases where this can crash. Creating a file without an extension that will have the same name as a directory you will create based on another file. (Files can't become directories, and you can't move a file inside another file.). If you plan to go into a production environment, you will want to harden the code with at least a few unit tests.
Cheers,
Dan


text:
Q: CodeIgniter 3 on remote server issues I am trying to setup a production server with a codeIgniter project.
All my http request redirects to homepage that login page.
I have followed a few instructions from StackOverflow but in vain
Following is my config.php settings
$config['base_url'] = 'http://XXXXX.local/';
$config['index_page'] = '';
$config['uri_protocol'] = 'QUERY_STRING';

The .htaccess settings
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

And my sites-enabled config in apache2 sites-enabled settings
<VirtualHost *:80>
    ServerName    XXXXX.local
    DocumentRoot "/var/www/html/xxx/index.php"
    <directory "/var/www/html/xxx/index.php">
        DirectoryIndex index.php
        AllowOverride all
        Order Allow,Deny
        Allow from all
    </directory>
</VirtualHost>

For e.g. if I open on browser http://XXXXX.local/assets/js/jquery.validate.min.js, it opens  homepage
Also my session does not work, it prints empty..I'm setting like
$this->session->set_userdata('test','hellow world');
 Here's my configuration
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_cookie_name'] = '';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

Please help!

A: The document root in your Apache config needs to be a folder, not a file.
Change
DocumentRoot "/var/www/html/xxx/index.php"
<directory "/var/www/html/xxx/index.php">

to
DocumentRoot "/var/www/html/xxx"
<directory "/var/www/html/xxx">

Don't forget to restart Apache after you've updated the config.


text:
Q: Auto-size thumbnails in a both left/right justified frame/window I am doing on a webpage for display a large amount of pictures/thumbnails. What I am looking for is to auto-resize the pictures, make each line has fixed height, and the right margin of each line is also equal. Even the images are reformatted when I change the size of window, the above mentioned style is kept.
That is quite similar with what google did when displaying their images search results:
Google image example  (resize your browser window and you may find what I'm trying to say :-) )
Anyone has idea on this would be much appreciated! Thanks

A: According to me there 2-ways, 1)by css 2)by js
1)CSS: you can add this in your css, this will resize your thumbnail accordingly.
img{max-width:100%;}

2)JS: Using js you can resize the thumbnails based on the available space and also decide on how many images do you want to show in one row.


text:
Q: OpenCL на С++ или на Java На C++ или на java выгоднее/дешевле/быстрее реализовать программу для работы с большими объемами данных? Уточню что архитектура программы предполагает большое количество параллельных асинхронных потоков. OpenCL при этом используется для математических расчетов двойной точности.
Погуглив нашел лишь похожие темы 5-ти летней давности.

A: Если нужна максимальная производительность - однозначно C++. Программируя на Java мы получаем преимущественно в скорости написания кода и его переносимости. Многие базовые задачи решает виртуальная машина Java, что в свою очередь требует затрат ресурсов на интерпретацию/JIT-компиляцию байт-кода, управления памятью... В C++ же "платишь" ровно за то, чем пользуешься. Для реализации многопоточности и асинхронности подойдет библиотека Boost.Asio. Если проект достаточно сложный чтобы писать логику в асинхронном стиле, можно использовать сопрограммы. Сам пишу с Folly/Fibers.
Но тут нужно понимать что если вся логика приложения сводиться к использованию OpenCl, то особого преимущества C++ перед Java нет. Вызовы методов библиотеки OpenCl для обоих языков будут требовать почти одинаковых затрат, тут как раз таки важен остальной функционал приложения.


text:
Q: Volume of the intersection of two cylinders $x^2+y^2=1$ and $y^2+z^2=1$. Consider two intersecting cylinders. I know the regular way to do this is:
$$ \int_{-1}^{1} \left(2\sqrt{1-2x^2}\right)^2\,dx = \frac{16}{3} $$
This methods integrates the square sides of the solid that you get

However, is it just as viable to flip the picture 90° (have the yellow tube going up) and trying to integrate then? You will get discs where the front and back are circular but the interior is square (integrate along the yellow face on the right side image) e.g.
$$ \int_{-1}^{1} \int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}} 2\sqrt{1-y^2}\,dy\,dx $$
Should these two integrals be equal or am I doing something wrong?

A: Yes absolutely, these integrals should be equal.
However, the way you wrote it, the computation is not straightforward. Instead, note that by switching the order of the variables in the integral, it also equals
$$
\int_{-1}^{1} \int_{-\sqrt{1-y^2}}^{\sqrt{1-y^2}} 2 \sqrt{1-y^2}\; dx dy =
\int_{-1}^{1}4 (1-y^2)\; dy = \frac{16}{3}
$$