Q: JTree wont update I am trying to add a node to my JTree. I do that like so:
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
    root.add(newNode);
    ((DefaultTreeModel) tree.getModel()).reload();

However, the tree itself doesnt update. Ive read posts that reload() is what you are supposed to call, but to no effect. Also please note this is being called on the EDT. Any ideas?
EDIT:
I have tried this approach:
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
    ((DefaultTreeModel) tree.getModel()).
            insertNodeInto(newNode, root, root.getChildCount() - 1);

Still no go. However, when I shut the program down and reopen it, the new node is there. (I persist my data).

A: Add nodes to a JTree using the DefaultTreeModel's insertNodeInto method. To quote the API

This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.

For example:
((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, 0);//inserts at beginning
//((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, root.getChildCount() - 1);//inserts at end


Q: pandas.DataFrame.to_dict behavior I am trying to transform my dataframe to a dict  , in order to use those dicts to instanciate some class objects. Following documentation, http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html, the rule I need in my case is orient='records'.
However, I noticed that it does not behave as I expected when column names are integers,or strings containing only integer:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 15:[4,5,6], '302':[5,6,7]})
mydict = df.to_dict(orient='records')
print(mydict)

returns
[{'_2':4, 'a':1, '_0':5},{'_2':5, 'a':2, '_0':6}, {'_2':6, 'a':3, '_0':7}]

I found a way to work around the problem, doing:
mydict = list(df.to_dict(orient='index').values())

but I am at loss as to why this is happening. I am on python 3.5 and on pandas 0.24.
Any ideas?

A: This is a bug that was introduced in pandas 0.24.0, and fixed in 0.24.1. See https://github.com/pandas-dev/pandas/issues/24940


Q: Problems about find conditions in recursive = 2 this is my debug $this->Subjob->find('all')
(int) 0 => array(
    'Subjob' => array(
        'id' => '1',
        'job_id' => '2',
        'subjob_title' => 'mastersubsjob',
    ),
    'Job' => array(
        'id' => '2',
        'content_id' => '2',
        'Content' => array(
            'id' => '2',
            'content_type_id' => '2',
            'content_title' => 'masterdata' //

I set recursive = 2 and I want to search Subjob by content_title ,
this is my controller
 $conditions[] = array('Content.content_title LIKE'=>'%'.$this->data['Subjob']['content_title'].'%');

$this->set('subjobs', $this->paginate($conditions));
but I get "Database Error Unknown column 'Content.content_title' in 'where clause'".
Sorry for my bad English.


Q: flask error with SQLAlchemy / ORM -- not seeing db tables In development (so sqlite3) I'm getting this error on any database access:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ujs ...

I got here by saying
export FLASK_ENV=development
export FLASK_APP=my_app.py
flask db init
flask db migrate
flask db upgrade
flask run

and then doing an HTTP GET against that dev server.
I believe the migration workflow succeeded, because when I use the sqlite3 commandline client, I can see the (empty) table with a believably correct schema.
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $ sqlite3 dev.db
SQLite version 3.27.2 2019-02-25 16:06:06
Enter ".help" for usage hints.
sqlite> .table
alembic_version    ujs
sqlite> .quit
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $

I therefore believe I've made a coding error.  But I'm not seeing it.
I have this code (pared down to what I believe is the essential bits):
my_app.py:
from app import create_app, db, cli
from app.models import UJS

app = create_app()
cli.register(app)

@app.shell_context_processor
def make_shell_context():
    return {'db': db,
            'UJS': UJS}

app/models.py:
from app import db
import time

def now_in_microseconds():
    """Return the current time in microseconds since the epoch.
    """
    return time.time() * 1000 * 1000

class UJS(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp_microseconds = db.Column(db.BigInteger, default=now_in_microseconds)
    ip_hash = db.column(db.String(40))

    # And then some more columns, all quite boring.

    def __repr__(self):
        return '<[{tag}]/[{ip}] {microsec}/{city}>'.format(
            tag=self.tag, ip=self.ip_hash,
            microsec=self.timestamp_microseconds, city=self.city)

app/__init__.py:
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    try:
        app.config.from_pyfile("../config_local.py")
    except FileNotFoundError:
        print('No local config found.')
    except:
        print('Unexpected error on app.config.from_pyfile()')

    db.init_app(app)
    migrate.init_app(app, db)
    ...
    return app

from app import models

and app/main/routes.py:
from flask import request, g, current_app, session
from app import db
from app.main import bp
from app.models import UJS

@bp.before_app_request
def before_request():
    if 'static' == request.endpoint:
        # This should only happen in dev.  Otherwise, nginx handles static routes directly.
        return
    # I expect this to return an empty list, but it throws a 500.
    print(UJS.query.all())

Any suggestions what I'm missing?

A: For anyone who might find this question later on: the problem was about having the right absolute path to your DB in your SQLALCHEMY_DATABASE_URI config value.
Also (this wasnt the case here, but it might possibly gotcha with the same symptoms) - if you omit __tablename__ on Model declaration, SQLAlchemy might autogenerate something you wont expect. Just a thing to keep in mind, if you're working with an existing DB with some schema already in place.


Q: condition for ng-model Help me please with ng-model. I have an input field where when selecting substituted values from an array 'posters'. Yhe value selected by the filter appear in the list. The list is displayed by default 'The grund tour'. When I enter in the form of a value that is not in the array - in the list displays an empty field, but I need to be displayed or the value of the array or the default value (if the form is entered the value is not of the array). I have no idea how to do it.
I think it may be possible to apply for a condition for the ng-model to make it work only for the values of an array
My code html:

        <form action="" class="form">
            <input type="text" class="form__input" placeholder="Search..." autocomplete="on" list="posters" ng-model="posterTitle"  >
            <datalist id="posters" >
                <option ng-repeat="poster in posters" >{{poster.title}}
                </option>
            </datalist>
        </form>

{{poster.title}}

{{poster.title}}

Controller:
'use strict';
  angular.module('oldmenTest')
   .controller('FormController', ['$scope', 'postersName', function($scope, postersName) {
    $scope.posters= postersName.getPosters();

    $scope.posterTitle = '';
 }]);

Var:
'use strict';

angular.module('oldmenTest')
 .service('postersName', function() {

var posters = [{
    title: 'var1',
    description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    image: 'resources/images/mars.jpg'
}, {
    title: 'var2',
    description: 'TLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    image: 'resources/images/earth.jpg'
}, {
    title: 'var3',
    description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    image: 'resources/images/venus.jpg'
}
];

this.getPosters = function(){
    return posters;
};

});

Thanks for hepl!

A: As I understand you have to apply filter conditionally on specific property or all properties based on title.
You could do something like below.

      .
      {{poster.title}}


Q: Spring Beans Created Multiple Times I am just new to Spring and facing a design problem. The problem is i have a maven multiple module projects. Project Structures goes as follows.
module-backoffice  - Packaging(war)
module-ws        -   Packaging(war)
module-dao      - Packaging(jar)
module-shared     -  Packaging(jar)
In "module shared "all my service class and in "module-dao" all dao related codes exists.
module-shared and module-dao is in the build path of module-backoffice and module-ws.
Now Problem is when i run module-backoffice war and module-ws war Spring creates two instance of Service class beans and dao class beans.
What should i do so that one instance of service class and dao class will be created and shared among multiple war ? Please help. Thanks you.
Code in Module-Shared: Below  is Service factory class
@org.springframework.stereotype.Service
public class Services {

@Autowired
private List<Service> services;

private static final Map<Class<?>, Service> serviceCache = new ConcurrentHashMap<Class<?>, Service>();

@PostConstruct
public void initServiceCache() {
    services.forEach(service -> serviceCache.put(service.getClass(), service));
    services = null;
}

public static Bootstrap bootstrap() {
    return (Bootstrap) serviceCache.get(Bootstrap.class);
}

And the service class is :
@Component
public class Bootstrap implements Service {

public Bootstrap() {
    System.out.println("Bootstrap");
  }
}

When i run tomcat deploying two wars then in console two times "Bootstrap" printed. How do i restrict that.?

A: The purpose of web container like tomcat is to able to run applications independently so they can be started and stopped without affecting each other. In case you think there can be multiple future applications will also require the same service, you can make a separate application and expose an API for the operations.


Q: PHP: deleting old images from array and displaying default image I have a site that is used to display the last 7 days webcam images from a defined folder.
We have a code written for it that looks for the specific file types, deletes any that are over a defined age, and then puts them into an array along with their creation date. This array that is used to display the images in date order.
I want to amend the code so that if 7 days goes by without new images being uoloaded, a default "camera Offline" image is shown instead.
I have tried using array_push at the end to add my default image, but I cant get it to work. any suggestions?

// Array holding filename and creation date
$files = array();
// Delete all webcam files older than a week
function getFileList()
{

global $files;

    $captchaFolder  = './';         // Define the folder to clean
    $fileTypes      = 'EZ*.jpg';    // Filetypes to check
    $expire_time    = 10080;        // Define after how many minutes the files should get deleted

    // Find all files of the given file type
    foreach (glob($captchaFolder . $fileTypes) as $Filename)
    {
        $FileCreationTime = filectime($Filename);   // Read file creation time
        $FileAge = time() - $FileCreationTime;      // Calculate file age in seconds
        if ($FileAge > ($expire_time * 60))         // Is the file older than the given time span?
        {
            unlink($Filename);
        }
        else
        {
            array_push($files, array($Filename, $FileCreationTime));
        }
    }
    // Sort the array by $FileCreationTime
    $times = array();
    foreach($files as $file)
    {
        $times[] = $file[1];
    }
    array_multisort($times, SORT_ASC, SORT_NUMERIC, $files);
}

getFileList();
$numPics = count($files);

// Insert the options in the select element
function buildOptions()
{
    global $files;
    $count = 1;
    foreach ($files as $file)
    {
        $dt =  date ("D d/m/y H:i", $file[1]);
        echo "\t\t<option value=\"$file[0]\">$dt (UTC)</option>\n";
        $count++;
    }
}

A: // check if the array is empty
if(empty($files)){

    // add a default image to the empty array (the timestamp doesn't matter because it will not be used)
    $files[] = array('default_image.png');

    // because it's empty you could also use:
    $files = array(array('default_image.png'));

}


Q: Deltacloud / Ruby LoadError I've just put a new RVM build with Ruby 1.9.2 on OS 10.6 and I'm trying to get Deltacloud up and running. Seem to have some problem with Gems, but I'm not sure what I'm dealing with.
craigb@macbook:>rvm list

rvm rubies

   ree-1.8.7-2011.03 [ i686 ]
=> ruby-1.9.2-p290 [ i386 ]
   ruby-1.9.3-p0 [ x86_64 ]

craigb@macbook:>rvm gemset list

gemsets for ruby-1.9.2-p290 (found in /Users/craigb/.rvm/gems/ruby-1.9.2-p290)
   global

craigb@macbook:>deltacloudd -l
/Users/craigb/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require': no such file to load -- server.rb (LoadError)
    from /Users/craigb/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/gems/deltacloud-core-0.4.1/bin/deltacloudd:115:in `<top (required)>'
    from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/bin/deltacloudd:21:in `load'
    from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/bin/deltacloudd:21:in `<main>'
craigb@macbook:>

Can someone point me in the right direction?

A: This pull request includes a patch for the problem; the code is updated in git but is apparently not up to date even in the latest available gem.  It's a one-line edit to bin/deltacloudd
https://github.com/apache/deltacloud/pull/3


Q: Connecting to a C++ websocketpp server within Docker I am trying to establish a websocket connection with a server written in C++ with websocketpp. I can successfully establish a connection with my server when it is running on my computer, but I am unable to connect with the same server when it is running in a Docker container on my local machine.
I spent a while looking up this issue online, and it seemed that the main pain points were to listen  to 0.0.0.0 instead of 127.0.0.1, and to use the -p config instead of EXPOSE in the Dockerfile. I  think what I have now follows those two pieces of advice, but I am still unable to connect to the endpoint. I was pretty lost, so I figured I would ask here to see if anyone else ran into a similar issue.
My client looks like this (just from within the browser):
let ws = new WebSocket('ws://localhost:3001');

My server looks like this:
websocketpp::server<websocketpp::config::asio> server_;

server_.clear_access_channels(
   websocketpp::log::alevel::frame_header | websocketpp::log::alevel::frame_payload
);
server_.set_reuse_addr(true);
server_.init_asio();

server_.listen(port_); // port_ is set to 3001

server_.start_accept();
server_.run();

and my Dockerfile looks like the following:
FROM gcc:latest

RUN set -ex; \
    apt-get -y update; \
    apt-get -y upgrade; \
    apt-get install -y cmake build-essential libboost-dev \
        libboost-system-dev libboost-thread-dev librange-v3-dev \
        libfmt-dev libprotobuf-dev protobuf-compiler \
        libwebsocketpp-dev libgtest-dev google-mock

# libgtest-dev only installs source files which need to be compiled -- actually compile them here
RUN cd /usr/src/googletest; \
    cmake .; \
    cmake --build . --target install

COPY . /usr/src/mazer
WORKDIR /usr/src/mazer

RUN cd /usr/src/mazer;  \
    mkdir build;  \
    cd build; \
    cmake ..; \
    make

CMD exec "./build/mazer-server/mazer-server"

I am starting the container with the following command:
docker run --rm -p 3001:3001 mazer-server


Q: Displaying four li's per ul's not returning result as required I want to display
 and
 dynamically like

ie, each
 with 4
s.
I want to display these dynamically. I tried with the following code:
$i=0;
foreach($query->result() as $inboxresult)
{
        if($inboxquery->num_rows()>0)
        {
            if($i%4==0)
            {
                echo '
';
            }
            $parentid=$inboxresult->id;
            echo '

                   <input type="hidden" id="status'.$inboxresult->id.'">
                   ';
                    echo '';
                    echo '

';
             if($i%4==0 && $i!=0)
             {
                echo '
';
             }
        }
        $i++;
}

This is returning result as shown below:

            <input type="hidden" id="status10">

             <input type="hidden" id="status7">

            <input type="hidden" id="status1">

Can anybody help me to solve this? Thanks in advance.

A: You're incrementing $i when you shouldn't... When you don't print li elements, you should not increment $i:
$i = 0;
foreach ($query->result() as $inboxresult)
{
        if ($inboxquery->num_rows()>0)
        {
            if ($i % 4 == 0)
            {
                echo '
';
            }
            $parentid = $inboxresult->id;
            echo '

                   <input type="hidden" id="status'.$inboxresult->id.'">
                   ';
                    echo '';
                    echo '

';
             // if you increment $i here, you don't need to worry if $i = 0 to close the ul
             $i++;
             if ($i % 4 == 0)
             {
                echo '
';
             }
        }
}

Oh, and mixing logic with HTML output, very bad idea ;-)


Q: Can I write a file in a public folder from my iOS application? I want to know whether I can write a music file in a public folder from my iOS application? I want my file to be accessed out of my app.

A: You can save your music file in the documents folder and set "Application supports iTunes file sharing" to YES. Then you can reach the file from outside the app.
Hope this helps


Q: How to use condition in sort function? I attempted to use condition to sort array by different fields:
 return source.sort((a, b) => {
      if (a.orderBy && b.orderBy) {
        return sortOrder === 'asc'
          ? a.orderBy - b.orderBy
          : b.orderBy - a.orderBy;
      }

      return sortOrder === 'asc' ? a.name - b.name : b.name - a.name;

    });

I have got the error:
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

What is problem?
It works for me, but probably it could be better:
  return source.sort((a, b) => {
      if (a.orderBy && b.orderBy) {
        return sortOrder === 'asc'
          ? a.orderBy - b.orderBy
          : b.orderBy - a.orderBy;
      }

      if (sortOrder === 'asc') {
        if (a.name < b.name) {
          return -1;
        }
        if (a.name > b.name) {
          return 1;
        }
        return 0;
      } else {
        if (a.name > b.name) {
          return -1;
        }
        if (a.name < b.name) {
          return 1;
        }
        return 0;
      }
    });

A: You cannot substract strings.
You should use a.prototype.localeCompare(b)
It will return 1 if a > b; -1 if b > a; and otherwise 0
In your example you should do following:
return source.sort((a, b) => {
  if (a.orderBy && b.orderBy) {
    return sortOrder === "asc" ? a.orderBy - b.orderBy : b.orderBy - a.orderBy;
  }

  return sortOrder === "asc" ? a.localeCompare(b) : b.localeCompare(a);
});


Q: Let svg paths "intersect" sorry, but i don't know how to formulate this question ;)
I have a svg animation of an atom. (Not from me, just as an example)
http://codepen.io/davidsneighbour/pen/raPBRO
The three ellipsae (?) defined by path.class='atom-1' to 'atom-3' are at the moment on top of each other.
<path class="atom-1" fill="none" stroke="#555" stroke-width="8" stroke-miterlimit="10" d="M231.7,200c0,17.4-1.7,88-31.7,88s-31.7-70.6-31.7-88s1.7-88,31.7-88S231.7,182.6,231.7,200z"/>

I would like to create an effect of 3-d-intersection so that each ellipsis is going at least once behind one of the other ellipsae, well, as if they are intertwined in 3d.
is this possible? how do I define some kind of z-index for parts of svg paths?


Q: Javascript - formation button- method post I am not expert of javascript.
I'm working on a project for implementing a javascript web interface like in the first picture.first picture
This is a form. When I select an option in the first and a second select I get the second line displayed in the second picture.second picture
On the second line you can see that I implemented an other button, which execute a php script. I would like that, when I execute it with the method post, the result would appear on the side frame (where is written TEST). So, this means that I have a form action associated to the button on the first line and another button on the second line. I would like that, when I click on the first button (on first line) a php script with method post would open in a new window. On the other hand, if I click the button on the second line, I would like to execute another php script with the method post and that its results appears on the side frame.
To implement this I used a formaction for the second button. However I cannot pass the variables coming from the selects.
Could anyone give me some ints to fix this issue?
I write here the code I used.
I didn't post the two scripts php as they are really trivial.

<html>
<head>
<meta charset="UTF-8" />

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="../calendar/mootools-yui-compressed.js"></script>
    <script type="text/javascript" src="../calendar/datepicker.js"></script>
    <link type="text/css" rel="stylesheet" href="../calendar/datepicker.css">
</head>
<body>

<script>
 var arrayA = ["Chap1"];

 var arrayB = ["Chap1"];

 var myForm = document.createElement("FORM");
 myForm.setAttribute("method","post");
 myForm.setAttribute("id","myForm");
 myForm.target ="";
 document.body.appendChild(myForm);

 var button = document.createElement("INPUT");
 button.setAttribute("type", "submit");
 button.setAttribute("formaction","test.php.php");
 button.setAttribute("formtarget","_blank");
 //----------- Select a matter-------------------------------------
 var arrayMatter = ["Choose a matter","Choice A","Choice B"];
 mySelect("matterSelect", arrayMatter, myForm);

 //------------ Select an operation---------------------------------
 var arrayOperations = ["Choose an operation",
                        "Execute it"];

 mySelect("operationSelect", arrayOperations, myForm);

 myForm.appendChild(button);

 document.getElementById("matterSelect").addEventListener("click", function(){dropDownReset()});

 document.getElementById("operationSelect").addEventListener("click", function(){dropDownOperations()});

 //_________________________________________________________________________________________________________
 //----------------- FUNCTIONS------------------------------------------------------------------------------
 //_________________________________________________________________________________________________________

 //------------ Function to create a Select ------------------------------
 function mySelect(id, options, parent){
  var myselect = document.createElement("SELECT");
     myselect.setAttribute("id", id);
     parent.appendChild(myselect);

  for(i = 0; i < options.length; i++){

      var matterOption = document.createElement("option");
      matterOption.setAttribute("value", options[i]);
      var matterNode = document.createTextNode(options[i]);
      matterOption.appendChild(matterNode);
      myselect.appendChild(matterOption);
  }
 }

 //------------ Function to create a checkbox with text ------------------------------
    function myCheckBox(id, text){

  var cell1 = document.createElement("TD");

     var mycheckbox = document.createElement("INPUT");
     mycheckbox.setAttribute("type", "checkbox");
     mycheckbox.setAttribute("id", id);
     mycheckbox.setAttribute("name", id);

  cell1.appendChild(mycheckbox);
  document.getElementById("chapterTable").appendChild(cell1);

     var cell2 = document.createElement("TD");
     var checkboxNode = document.createTextNode(text);
     cell2.appendChild(checkboxNode);
  document.getElementById("chapterTable").appendChild(cell2);

  var arrayMinDfLevel = ["Choose min difficulty level","1","2","3","4","5"];
  var arrayMaxDfLevel = ["Choose max difficulty level","1","2","3","4","5"];

  var cell3 = document.createElement("TD");
  mySelect("selectMinDfLevel"+id,arrayMinDfLevel,cell3);
  document.getElementById("chapterTable").appendChild(cell3);
  document.getElementById("selectMinDfLevel"+id).disabled = true;

  var cell4 = document.createElement("TD");
  mySelect("selectMaxDfLevel"+id,arrayMaxDfLevel,cell4);
  document.getElementById("chapterTable").appendChild(cell4);
  document.getElementById("selectMaxDfLevel"+id).disabled = true;

  var butt = document.createElement("Input");
  butt.setAttribute("id","butt"+id);
  butt.setAttribute("type","submit");
  butt.setAttribute("formtarget","SideFrame");

  butt.setAttribute("method","post");

  butt.setAttribute("formaction","SideFrame.php");

  var textButt = document.createTextNode("Get Exercises list");
  butt.appendChild(textButt);
  document.getElementById("chapterTable").appendChild(butt);
  document.getElementById("butt"+id).disabled = true;

  mycheckbox.addEventListener( 'change', function() {
      if(this.checked) {
       document.getElementById("selectMinDfLevel"+id).disabled = false;
       document.getElementById("selectMaxDfLevel"+id).disabled = false;
       document.getElementById("butt"+id).disabled = false;
      } else {
       document.getElementById("selectMinDfLevel"+id).disabled = true;
       document.getElementById("selectMaxDfLevel"+id).disabled = true;
       document.getElementById("butt"+id).disabled = true;
      }
  });
 }

 //------------ Function to create a submit ------------------------------
    function myFunction() {
      document.getElementById("myForm").submit();
     }

 //------------ Function to reset chapters ------------------------------
     function dropDownReset() {
      document.getElementById("myForm").removeChild(document.getElementById("divTest"));
     }

     function displayListOptions(matter, subject, diff_level_min, diff_level_max){
         var urlget = "var1='"+var1+"'&diff_level_min="+diff_level_min+"&diff_level_max="+diff_level_max;
         windows.location.href =  "./SideFrame.php?"+urlget;
     }

     function dropDownOperations(){
        var arrayS = [];
        if(document.getElementById("matterSelect").options[document.getElementById("matterSelect").selectedIndex].value == "Choice A"){
    arrayS = arrayA;
        }
        else if(document.getElementById("matterSelect").options[document.getElementById("matterSelect").selectedIndex].value == "Choice B"){
          arrayS = arrayB;
        }

     var opSelect = document.getElementById("operationSelect");

     if(opSelect.options[opSelect.selectedIndex].value == "Créer une séquence d'entrainement random"){

     }
     else if(opSelect.options[opSelect.selectedIndex].value == "Execute it"){

       var divTest = document.createElement("div");
      divTest.setAttribute("id","divTest");
      document.getElementById("myForm").appendChild(divTest);

       var chapterTable1 = document.createElement("TABLE");
      chapterTable1.setAttribute("id", "myTable");
      divTest.appendChild(chapterTable1);

      var row1 = document.createElement("TR");
      row1.setAttribute("id", "myRow");
      chapterTable1.appendChild(row1);

      var chapterTable = document.createElement("TABLE");
      chapterTable.setAttribute("id", "chapterTable");
      divTest.appendChild(chapterTable);

      for(k = 0; k < 1; k++){
          var row = document.createElement("TR");
          row.setAttribute("id", "myRow"+k);
          chapterTable.appendChild(row);
       myCheckBox("chapter"+k,arrayS[k]);
      }
     }
     }

</script>

</body>
</html>
<html>
<head>
</head>
<frameset cols="70%,30%">
 <frame id ="GeneralPanel" name="GeneralPanel" heigth = 1000 width = 700 src="GeneralPanel_v002.php">
 <frame id = "SideFrame" name="SideFrame" src="SideFrame.php">
</frameset>
</html>


Q: SQL conditions with mutually exclusive performance I just replaced an SQL statement that looked like this:
SELECT UserID, sUserName, sFirstName + ' ' + sLastName as [Name], iSiteNumber
FROM DecimalUsers left join dbo.CustomerSitePermissions on  UserID = iUserID
WHERE
    (cast(iSiteNumber as nvarchar(50)) like '%' + @query + '%' and (iPermissionIndex = 2 or iPermissionIndex = 0) and (bPrimarySite = 'true' or UserID in
        (SELECT top 1 iUserID FROM CustomerSitePermissions where iUserID not in
        (SELECT iUserID FROM CustomerSitePermissions WHERE bPrimarySite = 'true'))))
    OR CAST(sUserName as NVARCHAR(50)) LIKE @query + '%'
    OR CAST(sFirstName as NVARCHAR(50)) LIKE @query + '%'
    OR CAST(sLastName as NVARCHAR(50)) LIKE @query + '%';

It ran very slowly (around 15 seconds per query). Maybe it's that first part of the WHERE statement with the ugly nested queries. Sure enough, removing it knocks the time down to under a second. Case closed!
OR IS IT?
Not only did the query speed up when you removed the first where condition, but also if you removed all the other ones. Checking sUserName, sFirstName, and sLastName, but not iSiteNumber ran in under one second. Likewise, checking iSiteNumber, but not sUserName, sFirstName, or sLastName also ran in under a second. The query was only slow if the iSiteNumber check and any other check (didn't matter which one or how many) was left in.
Something about this query is slower than the sum of its parts. Why?

A: Firt, however, be sure you have proper index  then
In your iSiteNumber
You are using multiple subselect for in clause,   this force the db engine for repeated  access  to data  ..
for the others part  each OR clause mean a repeated  access to date
could be that  you can rewrite you query avoiding these tecnique
eg instead of  the not in  for where bPrimarySite = 'true'
  ( SELECT top 1 iUserID
        FROM CustomerSitePermissions where iUserID not in
        (SELECT iUserID
          FROM CustomerSitePermissions WHERE bPrimarySite = 'true'
    )
  )

you could use a inner join  for the inverted  logical query  or a simplified  query eg:
  ( SELECT top 1 iUserID
    FROM CustomerSitePermissions where
    bPrimarySite = 'false'
  )

and you could try to rewrite you query for avoid the upper subselect for an IN clause and use a inner join  .. if is possible.
These suggestion can be useful or not depending by the real  logic and result you really need


Q: Not all rows are rendered in ng-grid in my project I'm fetching data from the server, and receive 20 data-items. However, only 6 rows are rendered, and inside ng-repeat there are 6 of them. However the height of the canvas is calculated correctly All other items appears after resize of the window.
This issue is similar to: https://github.com/angular-ui/ng-grid/issues/860
but using virtualizationThreshold doesn't work for me and there is no other way around
Here is part of controllers code:
app.controller('NagruzkaController', ['$scope', 'NagruzkaService', 'Cacher', 'RawInfoRetriever', '$timeout',
function ($scope, NagruzkaService, Cacher, RawInfoRetriever, $timeout) {
    $scope.configRequest = {};

    $scope.showLoader = false;
    $scope.showTable = false;

    $scope.fetch = function () {
        $scope.showLoader = true;

            NagruzkaService.getAll().then(function (data) {
                var tmp = RawInfoRetriever(data);
                $scope.nagruzkaData = tmp;
                Cacher.nagruzka = $scope.nagruzkaData;

                $scope.showLoader = false;
                $scope.showTable = true;
            });
        }
    };

    $scope.gridOptions = {
        data: 'nagruzkaData',
        enableColumnResize: true,
        showGroupPanel: true
    };

In my html template I use ng-grid in this way:

I got ng-grid via npm and my current version is 2.0.1
I've tried to get later version and tried to use 2.0.14, however with this version rows are not shown at all, untill window resizing.
Can anyone help me with this?

A: You will have to use a ng-grid plugin Flexible Height Plugin. Add this plugin to plugins property of the grid options.
$scope.gridOptions = {
    data: 'nagruzkaData',
    enableColumnResize: true,
    showGroupPanel: true,
    plugins: [new ngGridFlexibleHeightPlugin()]
};

A: Eventually, as I need to solve that problem as quick as I could, I ended up just triggering empty 'resize' event via jQuery, which made ng-grid rebuild and show all data received from the server.

A: please use this for not Not all rows are rendered in ng-grid
 it will work 100%
 $scope.gridOptions.excessRows = 100;


Q: Dribble is producing empty output files I need to create an output file for a program in lisp, but I cannot get dribble to properly record my output. I'm using lispbox and my buffer looks like this when I try to use dribble:
(dribble "output.txt")
"output.txt"
... Calls to functions I defined
... I've tried entering expressions, values, strings
(dribble)
NIL

But when I go to output.txt I have an empty file that is 0 bytes. I'm pulling my hair out because I'm having trouble finding the answer and it seems like my computer is the problem. Any thoughts on where to start troubleshooting this (or solutions) would be greatly appreciated.

A: I'd bet dribble is rebinding some streams that are different from the ones being used by SLIME to get output to and from the REPL.  (Issue DRIBBLE-TECHNIQUE might be worth reading.)
Your solution depends on what your are doing.  If you just want a record of your interactions with Lisp, remember that emacs is a text editor and you can save the contents of the REPL buffer to a file or copy an excerpt.
If you want to write a program that saves output to a file, dribble is not a good mechanism for this.  Have a look at
open,
close,
print,
format,
and
with-open-file.


Q: react-typeahead - invariant violation: addComponentAsRefTo(...) issue Node v0.12.2
React v0.13.2
Npm v2.7.4
Using the standard typeahead input causes the following error:
Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.
This is how I am implementing the typeahead...
Index.jsx has:
'use strict'
var React = require('react');
var ReactTypeahead = require('react-typeahead').Typeahead
var QuickSearch = React.createClass({
 render: function () {
  return(
   <ReactTypeahead options={["spam", "foodbar"]}/>
  );
 }
});

var Topbar = React.createClass({
 render: function() {
  return (
   <QuickSearch />
  );
 }
});

module.exports = Topbar;

And then in my App.jsx I have:
'use strict';
var React = require('react');
var Topbar = require('./topbar');
var App = React.createClass({
render: function () {
  return (
   <div>
    <Topbar />
   </div>
  );
 }
});

module.exports = App;

A: Seems to me you are missing a semicolon after requiring the typeahead.


Q: How to use data returned from subprocess.call without returning the entire output? def is_akamaized(url):
    stripped_http_url = url[8:]
    clean_host = stripped_http_url.rsplit('/')[0]
    nslookup_data = subprocess.call(["nslookup", clean_host], stdout=subprocess.PIPE)
    if nslookup_data.find('akamaiedge'):
        return "\033[1;31mEnvironment is Acamaized {0}  -  {1}\033[1;m"

This function just takes a url and runs nslookup on it.  What I WANT to happen is I want to take the output of nslookup and parse through it for certain keywords.  The problem is, with the current code if I pass in a url that should work (contain the word acamai in the nslookup)
print is_acamaized(url)

it returns 0
Note, I added the stdout=subprocess.PIPE so that the entire output of nslookup is not returned to the terminal.
Any suggestions on how to assign the output of nslookup to a variable so I can access it?

A: subprocess.call() returns the exit code, not the stdout.  You can use the Popen class directly:
nslookup_data = subprocess.Popen(["nslookup", clean_host], stdout=subprocess.PIPE).communicate()[0]

The .communicate()[0] at the end is important.  That tells Popen that we are done, and it returns a tuple: (stdout, stderr).  The first item in the tuple [0] is the stdout.
You could also use subprocess.check_output():
nslookup_data = subprocess.check_output(["nslookup", clean_host])


Q: How to add data with image in response I want to send userid with image in response. I am using httpServletResponse class for that.
This is my code.
I am adding data in header and image in regular body..But I want data with image in body.I dont want to add in header. Is this possible?
bytes = objUserMaster.getProfilePicture();
 responseImage = ImageIO.read(new ByteArrayInputStream(bytes));
 out = response.getOutputStream();
 response.addHeader("Hiiiiiii", "message");


Q: Is it possible to save PDF file directly into the file without using UIActivityViewController or UIDocumentInteractionController iOS? I need to save a PDF document from URL into the device. Is it possible to save the PDF and access it from device file manager without using UIActivityViewController or UIDocumentInteractionController.

A: Add these 2 keys in your Info.plist: LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled. And set YES as the value for both.
Now you will be able use the Files app to see any file saved by your app in Documents Directory.

A:
Swift 5.0 and iOS13

let documentController = UIDocumentPickerViewController(url: exportToURL, in: .exportToService)
self.present(documentController, animated: true, completion: nil)

exportToURL represent application local URL whichever file want to save into iPhone Files app.


Q: InvalidPipelineOperator MongoError: Unrecognized expression '$replaceAll' I am running following code in MongoDB:
db.response_graphs.aggregate(
    [
        {
            $match : {
                "Response_measure" : "MasksMandatory"
            }
        },
        {
            $project : {
                date_end: { $replaceAll: { input: "$date_end", find: "NA", replacement: "2020-08-01" }}
            }
        }
        ]
    )

I am getting following error:
{
"message" : "Unrecognized expression '$replaceAll'",
"ok" : 0,
"code" : 168,
"codeName" : "InvalidPipelineOperator",
"name" : "MongoError"
}
I am following the syntax from the following link still getting the above error:
https://docs.mongodb.com/manual/reference/operator/aggregation/replaceAll/
Please help me resolve it. Thanks in advance.


Q: How to differentiate usage and inheritance in a layered architecture? I'm trying to validate the following dependencies:

Source
In this picture, red relationships are forbidden, green relationships are allowed:

*

*no class in the adapter package can inherit from a class in the port package;

*any class in the adapter package can use (e.g. have a field) a class in the port package;

*no class in the service package can use (e.g. have a field) from a class in the port package;

*any class in the service package can inherit a class in the port package;

If possible I'd like to add these validations to Layered Architecture.
Thank you.

A: LayeredArchitecture considers all dependencies between layers. You cannot forbid inheritance, but allow access – nor vice versa. I recommend to define individual specific rules instead:
@ArchTest
ArchRule adapter_should_not_inherit_from_port = noClasses()
    .that().resideInAPackage("….adapter")
    .should().beAssignableTo(JavaClass.Predicates.resideInAPackage("….port"));

@ArchTest
ArchRule service_should_not_access_port = noClasses()
    .that().resideInAPackage("….service")
    .should().accessClassesThat().resideInAPackage("….port");


Q: Blueprism get all files contained in a root folder I have a root folder with multiple sub folders and those sub folders could have more sub folders and so on and so forth. I want to run an action and pass it the base folder and get all files that are contained in there (Even in sub folders). The Get files action only gets the files at the first level and to use get folders you'd need to create a huge process which checks every level to see if there are more sub folders and you could potentially miss some files.

A: run the command through command prompt maybe and then pipe your results out to read them? something like
dir /s /b /o:gn

Gives you all sub files etc in a root directory you can use that to pipe your answer into something readable or stdout it direct into a variable in your code if you can.

A: Zip Parent folder by using 7z commands or simply by Blueprism Zip Folder action and Use 7z Commands to extract recursive and relocate to single outputpath folder.
7zip tool is free of cost and usually every other organisation has these Tools.
Use recursive commands (X) of extraction and set the output path to a single location.
7z will do all the recursive fetching.
https://7ziphelp.com/7zip-command-line


Q: What is the Path for Call_History.db in iOS 6. Is it same as that of iOS5? I am new at iPhone development. I want to access iOS6 call_history. My code work for iOS5 but not work for iOS6. please help me to solve this problem. Many Thanks.

A: You cannot access the call log using the SDK and approved APIs. There are some workarounds, as you probably already know. The only option I know about is accessing call_history.db.
Take a look at this tutorial. Unfortunately for you, security has been made more severe, and you only can access that file in iOS < 5.0 (and probably all jailbreacked versions).


Q: Python: Loop not giving desired result So I'm trying to write a code that simulates a predator and prey situation where it starts off with a low population of predators and high population of prey. Over time the predator population grows while the prey population shrinks until the prey population is too little to sustain the predator population. The predator population dies off and then the prey population is able to repopulate. The simulation is supposed to stop whenever one of the two populations reach 0, in this case the predator population will and plot two populations over time of the simulation until it stopped. This is my code so far:
import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = []
    predatorCounts = []
    predatorI = initialPred
    preyI = initialPrey
    predator = predatorI
    prey = preyI

    while predator > 0 and prey > 0:

            predator = predatorI * (1 - predShrink + predFedBirthRate * preyI)
            prey = preyI * (1 + preyGrowth - predationRate * predatorI)
            predatorCounts.append(predator)
            preyCounts.append(prey)
            predatorI = predator
            preyI = prey

    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()

    return preyCounts, predatorCounts

simulate(50,1000,0.25,0.01,0.05,0.00002)

Its output is this
:
But it's supposed to come out like this:

Can someone help me please?
*Also aside from this whenever I put my plotting code outside of the function after the function line with values inside like this:
simulate(50,1000,0.25,0.01,0.05,0.00002)
plt.plot(predatorCounts, 'r', preyCounts, 'b')
plt.show()

It doesn't plot the values from the function and says predatorCounts and preyCounts are undefined.

A: So you looked at your process/calcs and it seems correct but you look at your result and it's funny.  One thing you notice when you print the counts...
print predatorI, preyI

is that there are fractions of predators and prey which, in the real world, doesn't make sense.  You are trying to simulate the real world. All your rate parameters are probably based on whole things, not fractional things.  So you decide that there can't be any fractional beings in your simulation and you only deal with whole beings (ints) after the population growth calculations ...

Your function returns the count vectors.  If you want to move the plotting statements outside of the function you need to assign the function's return value(s) to a name and then use them for plotting.
prey, predator, = simulate(50,1000,0.25,0.01,0.05,0.00002)
plt.plot(predator, 'r', prey, 'b')
plt.show()

Here are some things to read from the docs concerning names, scope, namespaces
https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects
https://docs.python.org/3/reference/executionmodel.html#naming-and-binding
You might need to read them periodically as you use the language more.

A: If I initialize your plot data with the starting populations and use int() truncation for the populations, I get the plot you say you're supposed to see:
import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = [initialPrey]
    predatorCounts = [initialPred]
    predator = initialPred
    prey = initialPrey

    while predator > 0 and prey > 0:
        predatorScaleFactor = 1.0 - predShrink + predFedBirthRate * prey
        preyScaleFactor = 1.0 + preyGrowth - predationRate * predator
        predator = int(predator * predatorScaleFactor)
        prey = int(prey * preyScaleFactor)
        predatorCounts.append(predator)
        preyCounts.append(prey)

    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()

    return preyCounts, predatorCounts

simulate(50, 1000, 0.25, 0.01, 0.05, 0.00002)


Q: Writing unit tests with QTestLib this is my first step into the world on unit-testing so please be patient. I'm writing a Qt 4.8.1 C++ program and as test framework I'm using the integrated QTestLib. I should test a class that inhrerits from a base one and that loads a certain XML file to read and parse it later with a function that will return a C++ class object with the xml values that I can retrieve and set via set/get functions. The class in the constructor instantiate a QFile object and in the readXml function I use it to parse with the QXmlStreamReader the file. What's the best way to test all this class with unit-tests? I don't see how I could bypass the file-read operation to inject a own string representing the file content. Or should I use as test content a different ad-hoc XML file?

A: Injecting a string to represent the file contents seems like it would be the most straightforward way of testing a class such as this.  However, directly instantiating a QFile instance in your class constructor makes this impossible (in other words, it's impossible to inject your dependency).  Moreover, it's quite a bit of work to create a "Fake" or "Mock" version of a QFile (a.k.a. a Test Double of a QFile).
The easiest way to resolve this is to pass a QIODevice into your class constructor (QFile inherits from QIODevice).  In your unit test, you can fake the contents of the file by passing in a QIODevice with the contents you wish to test.  In this case, you can accomplish this with a QBuffer, which allows you to arbitrarily set its contents.  As such, your class would like something like the following:
class MyXmlParser
{
   MyXmlParser(QIODevice* device);

   ...
};

Your unit test constructs the class with a QBuffer; your production code constructs it with a QFile.
Should I use a real XML file in my test?
Generally speaking, the more external dependencies your unit test has, the more costly it is to ensure that it doesn't break in the future (it potentially makes your unit test sensitive to its context).  As such, it is advisable to avoid using a real XML file in order to ensure that your test is self-contained.  Moreover, passing in a real XML means that you are now implicitly testing QFile as well as your XML parser (in other words, it's not longer a unit test, it's an integration test).  You can generally assume that the IO device that you pass into your parser works; you only need to verify that your parser uses the IO device correctly and that it can parse the XML properly.
Consider reading through the material at xunitpatterns.com, particularly the section on Test Smells.


Q: Property list in a Model property couldn't be mapped while trying to migrate I'm setting up a migration in an MVC5 that has a Model that's called "Order" with 3 properties, one of them is a class of PizzaModel. PizzaModel has the code below, what I'm trying to do is to enable multiple instances of pizzas in a single Order, so one Order can have many pizzas.
public class PizzaModel
{
    [Key]
    public int Id { get; set; }
    public List<PizzaSet> Pizzas { get; set; }
    public int Cost { get; set; }

}
public class PizzaSet
{
    public enum Toppings { GreenOlives, BulgarianCheese, Onions, Mushrooms, Peppers, Basil, Sausage, Pepperoni, Ham, Beef }
    public enum Sauces { BBQ, Islands }
    public enum Size { Personal, Medium, Family }

    public Size PizzaSize { get; set; }
    public List<Sauces> PizzaSauces { get; set; }
    public List<Toppings> PizzaToppings { get; set; }
}

Is this a wrong approach for a migration?

A: Your PizzaSet class is using a List of Enums, which will not map to a database schema in EF.
If you want to use an enum for Sauces and Toppings and want to allow multiple selections, you need to use the [Flags] property for the enum, to treat it as a bit field.
public class PizzaSet
{
    [Flags]
    public enum Toppings { GreenOlives = 1, BulgarianCheese = 2, Onions = 4, Mushrooms = 8, Peppers = 16, Basil = 32, Sausage = 64, Pepperoni = 128, Ham = 256, Beef = 512 }

    [Flags]
    public enum Sauces { BBQ = 1, Islands = 2 }

    public enum Size { Personal, Medium, Family }

    public Size PizzaSize { get; set; }
    public Sauces PizzaSauces { get; set; }
    public Toppings PizzaToppings { get; set; }
}

Then Toppings and Sauces become a bit field of possible values (notice the values will need to represent unique bits)
To select multiple toppings:-
PizzaSet ps = new PizzaSet();

ps.Toppings = Toppings.GreenOlives | Toppings.Peppers;

However, given your list of toppings and sauces may change over time, it's probably better to have a separate table that lists toppings, and use a join table (since it's EF Core)

A: You have enums as your list type.
If youre storing this data in a database. The database needs a placeholder to store the enum values.
In general this is done by a table.
So, if you make classes of your enums, these will be translated to tables and the mapping will work.
public class Topping
{
     public string Name {get;set;}
}

Use this class as your list type.
Do note that you need to fill the topping, sauces and etc. tables. The good news is: you can extend them without changing the code :-)

Alternatively,  you can put the
[NotMapped]

attribute on your property.  Do note that this won't help you in your specific case because it would not store the toppings in the database then.


Q: Flutter : stack & Ink overlay I am using a Stack to recreate this effect :

But for some reason, using the Ink widget to be able to get the gradient effect, this is what I have :

This is my code :
Stack(
                        children: [
                          SizedBox(
                            height: 100.0,
                            width: 100.0,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(20.0),
                              child: CachedNetworkImage(
                                imageUrl:
                                    'https://images.unsplash.com/photo-1570296767266-60ccc88974a5',
                                fit: BoxFit.cover,
                                placeholder: (context, url) => MC_Shimmer(),
                              ),
                            ),
                          ),
                          Positioned(
                            right: -5.0,
                            bottom: -5.0,
                            child: SizedBox(
                              height: 30.0,
                              width: 30.0,
                              child: Ink(
                                decoration: BoxDecoration(
                                  gradient: gradient,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(5.0)),
                                ),
                                child: Icon(
                                  OMIcons.cameraAlt,
                                  color: Colors.white,
                                  size: 15.0,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),

A: you can use Container instead of Ink and able to use gradient effect.
Positioned(
      right: -5.0,
      bottom: -5.0,
      child: SizedBox(
        height: 30.0,
        width: 30.0,
        child: Container(
          decoration: BoxDecoration(
            gradient: gradient,
            borderRadius:
            BorderRadius.all(Radius.circular(5.0)),
          ),
          child: Icon(
            OMIcons.cameraAlt,
            color: Colors.white,
            size: 15.0,
          ),
        ),
      ),
    )

A: I tried this in dart pad it worked alright.
Positioned(
                    right: -5.0,
                    bottom: -5.0,
                    child: SizedBox(
                      height: 30.0,
                      width: 30.0,
                      child: Material(
                        child: Ink(
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                                colors: [Colors.pink, Colors.yellow]),
                            borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          ),
                          child: Icon(
                            Icons.camera,
                            color: Colors.white,
                            size: 15.0,
                          ),
                        ),
                      ),
                    ),
                  )


Q: There is a way to use not operator in regex when ^ inside bracket is not an option? I went through dozen of already answered Q without finding one that can help me.
I have a string like this:
aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{

and I want to obtain a string like this:
aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa

Essentially I want to keep:

*

*valid word chars and hyphens wrapped in an open and a closed curly bracket, something that will match the regex \{[\w\-]+\}

*all the valid word chars and hyphens outside curly brackets

Using this:
$result = preg_replace( array( "#\{[\w\-]+\}#", '#[\w\-]#' ), "", $string );

I obtain the exact contrary of what I want: I remove the part that I want to keep.
Sure I can use ^ inside the square brackets in the second pattern, but it will not work for the first.
I.e. this will not work (the second pattern in the array is valid, the first not):
$result = preg_replace( array( "#[^\{[\w\-]+\}]#", '#[^\w\-]#' ), "", $string );

So, whis the regex that allow me to obtain the wanted result?

A: You may consider matching what you want instead of replacing the characters you do not want. The following will match word characters and hyphen both inside and outside of curly braces.
$str = 'aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{';
preg_match_all('/{[\w-]+}|[\w-]+/', $str, $matches);
echo implode('', $matches[0]);

Output as expected:
aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa

A: Also an option to (*SKIP)(*F) the good stuff and do a preg_replace() with the remaining:
$str = preg_replace('~(?:{[-\w]+}|[-\w]+)(*SKIP)(*F)|.~' , "", $str);

test at regex101; eval.in


Q: My table won't show the border i defined in css I'm trying to edit the borders of my table in css but the border's won't show.
Here's the code :

.midden {
  text-align: center;
}
.lijstje {
  list-style: inside;
  text-align: left;
  padding-left: 40%;
}
.naamkolom {
  background-color: lightgreen;
  font-weight: bold;
  border-radius: 25px;
  border-top: 2px chartreuse;
}
table {
  border: 25px green;
}
body {
  background-color: antiquewhite;
}
p {
  font-size: 25px;
  font-family: Georgia;
}

Italiaanse Recepten

    Recepten
    Ingrediënten
    Bereiding

    Spaghetti carbonara met andijvie

300 g spaghetti

250 g champignons

100 g Parmezaanse kaas

300 g gerookte spekreepjes

400 g gesneden andijvie

3 eieren

Kook de spaghetti volgens de aanwijzingen op de verpakking.

Snijd ondertussen de champignons in plakjes. Rasp de Parmezaanse kaas.

Verwarm een ruime hapjespan zonder olie of boter en bak de spekjes 3 min. op middelhoog vuur. Voeg de champignons en de andijvie in delen toe en bak nog 5 min. Schep regelmatig om. Breng op smaak met peper en eventueel zout.

Doe ondertussen de eieren in een kom en klop met 2/3 van de kaas los tot saus.

Giet de spaghetti af en doe terug in de pan. Voeg al roerend de saus toe. Blijf roeren tot de saus iets is ingedikt. Schep het andijviemengsel erdoor. Verdeel over de 4 borden en bestrooi met de rest van de kaas.

    Pangrattato

ciabatta

75 ml olijfolie

2 tl chilivlokken (molentje)

2 tenen knoflook

Maal de ciabatta in de keukenmachine tot broodkruim

Verhit de olijfolie in een grote koekenpan.

Voeg het broodkruim en de chilivlokken, peper en eventueel zout toe en bak in 5 min. op middelhoog vuur krokant.

Schep regelmatig om. Snijd ondertussen de knoflook fijn. Voeg de knoflook aan de pan toe en bak 2 min. mee op laag vuur.

Neem de pan van het vuur en laat de pangrattato afkoelen.

Terug naar startpagina

I really don't understand why the border isn't showing, since i can get the top columns to change color and the title to center, so the css file is working.
I've also tried creating a selective class for the table and assigning that in the html file but that didn't work either.

A: table {
    border: 25px solid green;
}

instead of
table {
    border: 25px green;
}

A: You have to define the type of border, so in your case I guess you want a solid border.
Here you have all css types of borders


Q: PIG Group by avoid Bag This is a basic PIG question.
I have my data something like this
10  | Dog
15 | Cow
20 | Dog
15 | Elephant
15 | Dog
25 | Elephant

I want to find the average weight of each animal and have the output as this :
Dog | 12.5
Elephant | 20
Cow | 15

I am able to use GROUP by and get the result, but the result is a bag, something like this :
 {(Dog), (Dog) } | 12.5
 {(Elephant), (Elephant)} | 20
 {(Cow)} | 15

How can I extract just the individual animal ?
I am using GROUP by like this.
--animal_weight is derived through other means
animal_by = GROUP animal_weight by (animal);
results = FOREACH animal_by GENERATE animal_weight.animal as animal_name, AVG(animal_weight.weight) as kg;
STORE results INTO '$output_4' USING PigStorage('|');

A: Use group instead of animal_weight.animal.Note that from your sample data,Dog should have an average of weight (10+20+15)/3 = 15 kg
results = FOREACH animal_by GENERATE group as animal_name, AVG(animal_weight.weight) as kg;

Output


Q: Unable to get data from child form into selected Parent DataGridView Cell I have been stumped on a programming issue. When I right click on a cell of a DataGridView object, a context menu will show. From that context menu, a user can click an option. That option will show a form. When the user is finished, the resultant of that form will be populated in the selected cell.
Problem: How do I get the result from the child form into the selected cell? There are multiple DataGridView objects on the parent form that use the same functionality.
Code:
    private void commandOperation(Object sender, EventArgs e)
    {
        if (sender == dec2HexToolStripMenuItem)
        {
            frmNumFormatConv form = new frmNumFormatConv();
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // Get data from the form into the selected cell!!!
            }
        }
        else
        {
            throw new Exception("Operational object unknown");
        }
    }

    private void cellMouseDown(Object sender, DataGridViewCellMouseEventArgs e)
    {
        if (sender == dgvCircuit1TestSetup || sender == dgvCircuit2TestSetup)
        {
            if (e.Button == MouseButtons.Right)
            {
                ((DataGridView)sender).CurrentCell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex];
                itsGridContextMenu.Show((DataGridView)sender, new Point(e.X, e.Y));
            }
        }
    }

A: A very easy way is to put a public property in the popup form that will return the values you want (Say RtnValue).  Then
This is an example for popup form:
    public string RtnValue
    {
        set { textBox1.Text = value; }
    }

This is your current code:
frmNumFormatConv form = new frmNumFormatConv();
        if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            dgvalue = form.RtnValue;
            // Get data from the form into the selected cell!!!
        }


Q: Why when I merge 2 pdf files with `gs` (ghostscript) the identify command cannot get the page count? This my gs command than merges 2 one-page pdf file:
gs -dNOPAUSE -dSAFER -sDEVICE=pdfwrite -sOUTPUTFILE=/tmp/blahblahblah.pdf -dBATCH page1.pdf page2.pdf

And this is the output:
GPL Ghostscript 8.70 (2009-07-31)
Copyright (C) 2009 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
Processing pages 1 through 1.
Page 1
Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Querying operating system for font files...
Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Didn't find this font on the system!
Substituting font Helvetica for ArialMT.
Loading NimbusSanL-Regu font from /usr/share/fonts/default/Type1/n019003l.pfb... 3397696 1943901 17192756 15861178 3 done.

The font ArialMT is not found and Helvetica is substituted with it. I got the merged file from server by scp and opened it in my local system. The file is properly merged including 2 pages. So file has no problem. Now I use the below command in order to get the PDF page count:
identify -format %n '/tmp/blahblahblah.pdf'

This command cannot get the page count and gives the below error:
identify: Postscript delegate failed `/tmp/blahblahblah.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/664.

NB: I should note that file exist in /tmp/blahblahblah.pdf path!
Why I cannot get page count via identify?
Sample files are attached in link below:
2 PDF sample file


Q: How to block ip Ranges using http modules? How to block Ip ranges using http modules with c# . I have a simple solution but its for single Ip and How can I read IPs from  xml file in http modules so that if an IP is there in that file it will be blocked  .Here is my code
public class MyHandler :IHttpModule
{
 public MyHandler(){}

    public bool IsReusable
    {
        get { return false; }
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }
    private void Application_BeginRequest(object source, EventArgs e)
    {
        HttpContext context = (source as HttpApplication).Context;
        List<string> BlackListIp = new List<string>();
        BlackListIp.Add("127.0.0.1");

        if (BlackListIp.Contains(context.Request.UserHostAddress))
        {
            context.Response.Write("
Your IP is Blocked
");
        }
    }

    public void Dispose()
    {
    }
}

A: Just add the xml file inside app_data folder and read it using XDocument.
You can event use Cache with FileDependency to improve performance.


Q: Disable other checkboxes in a GroupBox when two are checked  Private Sub AllBoxes_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged

    Dim qty As Int16 = 0
    Dim cb As CheckBox

    For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
        If cb.Checked Then
            qty += 1
        End If
    Next

    If qty = 2 Then

        For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
            If Not cb.Checked Then
                cb.Enabled = False
            End If
        Next
    Else

        For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
            cb.Enabled = True
        Next
    End If
End Sub

it just doesn't work. The groupbox's name is groupbox8 and it has 6 checkboxes on it. I need to select two checkboxes.

A: You can simplify a lot your CheckedChanged event handler using a bit of Linq
Private Sub AllBoxes_CheckedChanged(sender As Object, e As EventArgs)

    ' Get all checkboxes in the groupBox8
    Dim checks = groupBox8.Controls.OfType(Of CheckBox)()
    ' Count how many are checked
    Dim cnt = checks.Where(Function(x) x.Checked).Count()

    If cnt < 2 Then
        ' Enable all, avoid an if and don't care if already enabled
        For Each c In checks
            c.Enabled = True
        Next
    Else
        ' Disable all except the two checked...
        For Each k In checks.Where(Function(x)  Not x.Checked)
            k.Enabled = False
        Next
    End If
End Sub


Q: Cannot access XML Document using simplexml_load_file() I NEED HELP! I'm trying to generate XML document from my website database in hosting provider and accessing it from my home PC, right now I'm doing it in localhost environment. I use these codes and I got error message in browser. Please take a look at  my codes...
data.php for generating XML document
<?php
include ("koneksi-database.php");

header('Content-Type: text/xml');
echo "<?xml version='1.0'?>";
echo "<outbox>";

$query = "SELECT * FROM `tbstatus` WHERE `status` = '$status' ORDER BY `ID`";
$result = mysql_query($query);

while ($data = mysql_fetch_array($result))
{
echo "<data>";

    echo "<trx>".$data['trx']."</trx>";
    echo "<status>".$data['status']."</status>";
    echo "<signature>".$data['signature']."</signature>";
    echo "<time>".$data['time']."</time>";

echo "</data>";
}

echo "</outbox>";
?>

read.php for reading the XML document in localhost
print_r($dataxml = simplexml_load_file('data.php'));

I also create index.php for running the script every 5 seconds.

Server is Running...

finally this the error messages that i get from browser when I open read.php.
Warning: simplexml_load_file() [function.simplexml-load-file]: data.php:9: parser error : Start tag expected, '<' not found in C:\xampplite\htdocs\simpul\baca.php on line 9

Warning: simplexml_load_file() [function.simplexml-load-file]: echo "<?xml version='1.0'?>"; in C:\xampplite\htdocs\simpul\baca.php on line 9

Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in C:\xampplite\htdocs\simpul\baca.php on line 9

A: Your print_r($dataxml = simplexml_load_file('data.php')); is reading you raw PHP file, not the script execution result!
data.php file have a PHP code that outputs a XML file, not a really XML file.
You should use print_r($dataxml = simplexml_load_file('http://localhost/data.php')); for example. (Assuming that http://localhost/data.php is the url to access your file.)
using only 'data.php' as parameter will get the raw file from server, not processed by PHP.


Q: Referencing the current jQuery object in a chain? At DevDays in SF last year (before jQuery 1.4 was released), I thought they mentioned an upcoming feature in 1.4 that would allow you to reference the current jQuery object while in a chain. I've read through all of the 1.4 improvements and wasn't able to find it. Does anyone know how this can be done?
Example
Being able to access the current jQuery object would be helpful when working with methods that are in relation to the current object like .next():
// Current way
var items = $(this).closest('tr');
items = items.add(items.next(':not([id])'));

// Magical 1.4 way? Is there a "chain"-like object?
var items = $(this).closest('tr')
    .add(chain.next(':not([id])'));

A: I think this is the closest available, using .andSelf():
var items = $(this).closest('tr').next(':not([id])').andSelf();

This goes to the .next() call, but then adds the tr back to it.  Everything is in the context of where the chain occurs, so either jumping around to add elements, or storing the original reference as you have it is as close as is currently available.  These are the helpful functions for jumping around: http://api.jquery.com/category/traversing/miscellaneous-traversal/
John Resig posted this concept a while back, but to my knowledge, nothing closer to that has made it into jQuery core.  You can however use the code posted on the blog there if you want.

A: Possibly andSelf() http://api.jquery.com/andSelf/
This returns the previous selection, but you would then have to use :not([id]) on everything..


Q: Android Image Upload Fails I'm trying to upload an image from my phone to a server. So I get the image uri and create a NameValuePair with it. I then use the following Android code to get a connection and upload the pic. This was taken from previous stackoverflow question(I would link but can't find it even with Google...)
public void post(String url, List<NameValuePair> nameValuePairs) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
           MultipartEntity entity = new
                       MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

             entity.addPart(nameValuePairs.get(0).getName(), new FileBody(new File(nameValuePairs.get(0).getValue())));
        Log.v("Uploading file",nameValuePairs.get(0).getValue());
        httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
           Log.v("Response", response.toString());
        } catch (IOException e) {
          e.printStackTrace();
        }
   }

On the server side I have the following code. This is PHP, which I am a complete novice at. I know there is no validation in the code, but I want to get the upload working before I start worrying about everything else.
      <?php

     if($_FILES){
           $name = $_FILES['image']['name'];
           move_uploaded_file($_FILES['image']['temp'],$name);

           echo "success!";
     }
    else {

  echo "Nothing uploaded";
   }
 ?>

Here the name of the NameValuePair is 'image', which is used as the file name.
Nothing gets uploaded, but a connection is made. Please help.
Following the request I put print_r($Files) in the code. The respons from the server was:
09-05 23:23:35.745: VERBOSE/Response(13849): Array

09-05 23:23:35.745: VERBOSE/Response(13849): (

09-05 23:23:35.745: VERBOSE/Response(13849):     [image] => Array

09-05 23:23:35.745: VERBOSE/Response(13849):         (

09-05 23:23:35.745: VERBOSE/Response(13849):             [name] => DSC_0100.jpg

09-05 23:23:35.745: VERBOSE/Response(13849):             [type] =>

09-05 23:23:35.745: VERBOSE/Response(13849):             [tmp_name] => /tmp/phpXcY8L1

09-05 23:23:35.745: VERBOSE/Response(13849):             [error] => 0

09-05 23:23:35.745: VERBOSE/Response(13849):             [size] => 806873

09-05 23:23:35.745: VERBOSE/Response(13849):         ) 09-05 23:23:35.745: VERBOSE/Response(13849): )

09-05 23:23:35.745: VERBOSE/Response(13849):**

A: On server side please add this code ,
print_r($_FILES);

then check for array parameter 'error' then check error code from here
  http://php.net/manual/en/features.file-upload.errors.php
if you want the file upload code for android then please tell me i can post here
i hope this will help you.
Thank you.

A: move_uploaded_file($_FILES['image']['temp'],$name); replace this line with
move_uploaded_file($_FILES['image']['tmp_name'],$name);
The file's temporary file name is in "tmp_name", as i can see from your log output.


Q: RPN stacking method not working with converted string arrays I'm trying to make a program that processes a line of rpn expression through a stack method. The input is a string array that is converted from a string input.
String[] collect = "8 6 + 2 /"; //the
String line; //the inputed line
collect = line.split(" "); //the conversion
System.out.println(stackem(collect)); // calling the stack method for an output method

The problem is that the output is always the operator ate the end of the line, so when I put in the code that checks for malformed expressions it always turns into the error. Basically my input would be like this:
input: 8 6 + 2 /
output: Error: "Expression is malformed"
output (without the error code): /
output (what's supposed to be the output): 7
This is the code for the stack method:
public String stackem(String[] input)
{
Stack<String> stack = new Stack<String>();
int x, y;
String result = "";
int get = 0;
String choice;
int value = 0;
String p = "";
int output;

try
{
for (int i = 0; i < input.length; i++)
{
if (input[i] == "+" || input[i] == "-" || input[i] == "*" || input[i] == "/" || input[i] == "^")
{
choice = input[i];
}
else
{
stack.push(input[i]);
continue;
}

switch (choice)
{
case "+":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x + y;
result = p + value;
stack.push(result);
break;

case "-":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y - x;
result = p + value;
stack.push(result);
break;

case "*":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x * y;
result = p + value;
stack.push(result);
break;

case "/":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y / x;
result = p + value;
stack.push(result);
break;

case "^":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = (int)Math.pow(y,x);
result = p + value;
stack.push(result);
break;

default:
continue;
}
}

output = Integer.parseInt(stack.pop());
}
catch (Exception ex)
{
return "Error: Expression is malformed";
}
return "Result: " + output;
}

Is there any way to fix this issue?


Q: Paypal recurring payment IPN usage I successfully create a listener and it is working well if I am using the IPN simulator. However, when I am doing the payment request in the process of payment, I set the same listener url for the notify_url, nothing happens even the process working properly. How can I know if someone cancel his recurring payment directly from the Paypal or how do I setup up the listener whenever a recurring payment is made? Is it something wrong with my notify_url? This is what my notify_url look like:

http://example.com/paypal_notification/ipn_callback

No extra parameters. Is it correct? Thank you in advance.

A: You should be getting an IPN when the profile is created, each time the recurring profile bills, and when the profile is cancelled.  Check your IPN history in your account to make sure the IPN's are being sent out, and check to see if there is any type of error being returned to PayPal.  Check your server access logs to see PayPal is calling your script and check your error logs to see if anything is being triggered.  Try adding www. to your URL, and the ext to the end of your URL for the type of file it is.  Also, there are some IPN troubleshooting tips I posted for IPN on this forum POST.

A: The IPN will only be sent to the account on which the profile was created.
Here's how I would do it.

*

*Store the Paypal ProfileID and e-mail address in a database.

*Receive all of the IPN notifications yourself, and in the case of a failure, send an e-mail to the specific user based on their ProfileID, or perform other actions.


Q: Python: How can I find the heading of the road using Google Maps API? I wrote a program in python that takes in a starting point and end point and then uses google maps API to create a gif of the route using google street view. Everything works perfectly I just can't find a way to get the bearing/heading of the car. The resulting gifs is the correct path but the camera doesn't point at the road.
https://www.dropbox.com/s/b17el2lmiyna7m6/finalproduct8fps.gif?dl=0
here is sample to show you what I mean, the camera isn't pointing at the road at all times, how can I get the heading of the vehicle?


Q: Android lint custom check UCallExpression type of method receiver I'm writing custom lint check to ban some methods. So if someone calls banned method foo on instance of class A, lint should report error.
I achieved this for static methods like this (inside visitCallExpression(UCallExpression):
node.receiver as UReferenceExpression).getQualifiedName()

From qualified name I can get the Class object and run my check but I can't get the qualified name for methods called on instantiated object. I can get the name of the class to which the objects belongs but not the qualified name.
How do I get qualified name of class of method that is called on instance of that class? If I'm being unclear, here is an example.
import android.view.Button;

class ButtonSetTextIntClass {
       private Button button;

       public void bannedSetText (){
            button.setText(123);
       }
}

And I need in visitCallExpression (UCallExpression) get qualified name/class of button.

A: UCallExpression.receiverType does what you want:
public class CustomDetector extends Detector implements SourceCodeScanner {

    @Nullable
    @Override
    public List<Class<? extends UElement>> getApplicableUastTypes() {
        return Collections.singletonList(UCallExpression.class);
    }

    @Nullable
    @Override
    public UElementHandler createUastHandler(@NotNull JavaContext context) {
        return new UElementHandler() {

            @Override
            public void visitCallExpression(@NotNull UCallExpression node) {
                node.getReceiverType(); // PsiType:Button
            }
        };
    }
}

To extract qualified name you can use the following method:
((PsiClassType) node.getReceiverType()).resolve().getQualifiedName() // android.widget.Button

A: I found a solution which works for both static and non-static methods and for Kotlin top level functions. Not sure if it is the best way to do it but at least it works.
override fun visitCallExpression(node: UCallExpression) {
     (node.resolve()?.parent as? ClsClassImpl)?.stub?.qualifiedName
}

A:     /**
     * eg: android.util.Log
     * ps. imports was initialized in visitImportStatement
     */
    private fun getClassNameWithPackage(node: UCallExpression): String {
        var className = node.resolve()?.containingClass?.qualifiedName
        if (className != null) {
            return className
        }

        className = getClassName(node) ?: return ""
        for (import in imports) {
            if (import.contains(className)) {
                return import
            }
        }
        return "$packageName.$className"
    }

    /**
     * eg: Log
     */
    private fun getClassName(node: UCallExpression): String? {
        return node.receiver?.javaPsi?.text ?: when (val uExpression = (node.methodIdentifier?.uastParent as UCallExpression?)?.receiver) {
            is JavaUSimpleNameReferenceExpression -> {
                uExpression.identifier
            }
            is KotlinUSimpleReferenceExpression -> {
                uExpression.identifier
            }
            is UReferenceExpression -> {
                uExpression.getQualifiedName()
            }
            else -> null
        }
    }


Q: sphinxsearch-0.9 in mediawiki-1.32.0 error 2019/01/14 12:04:51 [error] 21549#21549: *3558 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class SphinxMWSearch contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SearchDatabase::doSearchTextInDB, SearchDatabase::doSearchTitleInDB) in /var/opt/www/extensions/SphinxSearch/SphinxMWSearch.php on line 15" while reading response header from upstream, client: 192.168.122.1, server: wiki.yuyizhi.org, request: "GET /index.php?title=Special:%E6%90%9C%E7%B4%A2&search=sphinx HTTP/1.0", upstream: "fastcgi://unix:/var/run/php-fpm/php5-fpm.sock:", host: "wiki.yuyizhi.org"

FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class SphinxMWSearch contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SearchDatabase::doSearchTextInDB, SearchDatabase::doSearchTitleInDB) in /var/opt/www/extensions/SphinxSearch/SphinxMWSearch.php on line 15", client: 192.168.122.1, server: wiki.abc.com, request: "GET /api.php?action=opensearch&search=bai&namespace=0 HTTP/1.0", host: "wiki.abc.com"

A: The SearchDatabase class that SphinxSearch extends was changed from REL1_31 to REL1_32. It now requires you to define doSearchTextInDB and doSearchTitleInDB methods.
See REL1_31 https://doc.wikimedia.org/mediawiki-core/REL1_31/php/classSearchDatabase.html
vs REL1_32 https://doc.wikimedia.org/mediawiki-core/REL1_32/php/classSearchDatabase.html
This is sortof mentioned in the patch notes if you search for Search under deprecation (note this is a Backwards compatibility break instead) https://www.mediawiki.org/wiki/Release_notes/1.32#Compatibility:

Overriding SearchEngine::{searchText,searchTitle,searchArchiveTitle} in extending classes is deprecated. Extend related doSearch* methods instead.

If you are like me and not comfortable fixing the extension yourself, you will have to wait for one of the extension contributors to update the extension to work with REL1_32. Until then you will have to stay on REL1_31 if you wish to use the extension.

A: Just adding these two empty functions to SphinxMWSearch.php under the definition of SphinxMWSearch class seems to do the trick. It makes it stop complaining and - as far as I can tell - search function is working fine.
function doSearchTextInDB($term) {
}
function doSearchTitleInDB($term) {
}

Hopefully developers of this extension will come up with a proper fix soon.


Q: Android App actions issues when English Articles are used as a part of speech We have implemented android shortcuts. Testing of App actions on physical devices was fine, except for an issue with English Articles.
When English Articles appear as a part of a statement, the statement is not recognized as an action, and Assistant does not redirected to the app. For example, 'add note to Express Scheduler' is recognized, while 'add a note to Express Scheduler' is not.
My question is whether anybody have experienced similar issues?
Please, see capabilities segment extracted from shortcuts.xml. I am  using actions.intent.CREATE_THING and actions.intent.GET_THING BIIs. I've listed one example above: 'add note to Express Scheduler' is recognized, while 'add a note to Express Scheduler' is not.
<capability android:name="actions.intent.CREATE_THING">
    <intent>
        <url-template android:value="https://vijac.ca/schedule{?name,description}" />
        <parameter
            android:name="thing.name"
            android:key="name"
            android:required="false" />
        <parameter
            android:name="thing.description"
            android:key="description"
            android:required="false" />
    </intent>
</capability>

<capability android:name="actions.intent.GET_THING">
    <intent>
        <url-template android:value="https://vijac.ca/search{?name}" />
        <parameter
            android:name="thing.name"
            android:key="name" />
    </intent>
</capability>enter code here

Thank you!

A: I think what may be happening is that you have a very generic name of the thing ("a note"), when it is expecting to handle specific names which normally don't need an article ("Pixel 4", "Stairway to Heaven").
You may want to try one of these to address the problem:

*

*The thing.name parameter for that BII allows for an inline inventory which is a way of setting allowable values and alises for those values. You can create an inventory item for note that has aliases such as "a note" and "note".

*Consider using the actions.intent.CREATE_DIGITAL_DOCUMENT BII which indicates that it supports phrases such as "Create a note".


Q: htaccess redirect .PDF for Prevent Direct Access but visible in internal viewer I'm developing with a small web-based project with WordPress which contains a lot of PDF files. What I'm looking for is to close the direct access to PDF files, like in https://sciami.com/scm-content/uploads/2018/06/myfile.pdf and redirect the request to the attachment page in https://sciami.com/myfile.
To do this, I wrote a code in .htaccess as below:
RewriteCond %{REQUEST_URI} \.pdf$ [NC]
RewriteRule ^scm-content/uploads/([0-9]+)/([0-9]+)/(.+)\.pdf$ /$3 [R=301,L]

In this way all PDFs are redirected to related attachment page (and it works!). Inside the attachment page, there is a PDF viewer that shows related PDF file. But because of the rule written in the .htaccess, the PDF viewer doesn't show anything because the https://sciami.com/scm-content/uploads/2018/06/myfile.pdf URL necessary for show PDF is rewritten.
My question is how to close the direct access to PDFs, while allowing them to be loaded within the viewer?
The condition
RewriteCond %{HTTP_REFERER} !^https://(www.)?sciami.com/ [NC]

allows operation within the site, but prevents redirect from within the site.
Every help is welcome.


Q: Filter custom post types by Post Object Custom Field I have post types named "tour" and "country".
"tour" post type has some custom fields and type of one of them is Post Object and filtered by Post Type "country".
Now I want to show tours filtered by a specific country, for example:
$located_tours = get_posts(array(
    'numberposts'   => 3,
    'post_type'     => 'tour',
    'meta_key'      => 'country',
    'meta_value'    => 'turkey'
));

But the result for this query shows nothing.
I know "country" I have used as meta_key is an object, but how can I use it correctly in my query?
Anyone has any idea?
Thanks


Q: Laravel Controller beforeFilter not working as expected My controllers constructor looks like
function __construct(MessageRepository $message)
{
    $this->beforeFilter('canViewThisMessage', array('only', 'show'));
    $this->message = $message;
    $this->pagesize = 8;
    $this->pageTitle = 'messages';
}

and I expect the filter to be applied on show action. Which looks like
public function show($id)
{
    $message = Message::findOrFail($id);

    return View::make('messages.show', compact('message'));
}

But the filter is applied on all actions, not just on show method! Why is this happening?

A: I think instead of:
$this->beforeFilter('canViewThisMessage', array('only', 'show'));

you should use:
$this->beforeFilter('canViewThisMessage', array('only' =>  ['show']));

or
$this->beforeFilter('canViewThisMessage', array('only' =>  'show'));

looking at documentation


Q: html5shiv.js and respond.js without Bootstrap 3

 <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

Whenever I search for these scripts on the internet they are always connected with Bootstrap 3. Should I use them in any responsive website using HTML5?


Q: setColorFilter not working with resource color If I use setColorFilter like this, it works and paint my image with the chosen color:
int color = Color.parseColor("#FF0000");
viewHolder.Icon.setColorFilter(color);

But if I try to use a resource color, it does nothing:
viewHolder.Icon.setColorFilter(R.color.colorPrimary);

where the resource is defined like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#FF5722</color>
</resources>

A: try this
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);

and you set actionBarBackground in the method setColorFilter thats all

A: Answer marked as "right" use getColor() method which is deprecated.
That's why here is up-to-date answer:
int color = ResourcesCompat.getColor(getResources(), R.color.my_color, null);

A: please add   PorterDuff.Mode.MULTIPLY  See below example
viewHolder.Icon.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );