text:
Q: Yii2 Optional textbox with Checkbox from database I am using following code to generate checkboxes from database. I need to add optional textbox for some options. Can anybody give me clue to add it ?
$form->field($model_detail, 'DOCUMENT_TYPE_ID')
       ->checkboxList(
        $listData,array('separator'=>'
')
       )->label('Select Document(s)');

A: You should extends ActiveField and write your custom checkboxList method. It may looks like this:
class ProjectActiveField extends ActiveField
{
    /**
     * @inheritdoc
     */
    public function checkboxList($items, $options = [])
    {
        $inputs = '';
        foreach ($items as $id => $value) {
            $input = Html::activeCheckbox($this->model, $this->$id, $options);
            $description = $options['itemDescriptions'][$id];
            if ($description) {
                $input = '
' . $description . $input . '
';
            }

            $inputs .= $input;
        }

        $this->adjustLabelFor($options);
        $this->parts['{input}'] = $inputs;

        return $this;
    }
}


text:
Q: Change php to new facebook SDK I cant figure out how to change this simple code to work with the newest facebook SDK...
It seems like they have changed some of the variables, and the way you retrieve information. I have not worked with facebook SDK before and is not that good in programmering. After ready the documentation and trying a few things I still fail. So I hope some of you guys can help me here...
require("src/facebook.php");

// construct the object with your facebook app data
$facebook = new Facebook(array(
'appId'  => '[YOUR APP ID]',
'secret' => '[YOUR APP SECRET ID]',
'cookie' => true
));

try {
    // to get the id of the currently logged in user
    // if, you want you can manually set a user id here like this:
    //$uid = '[FB USER ID]';
    $uid = $facebook->getUser();

    // if you know know the access token before hand then you can set it here
    // or you can leave this line commented
    //$facebook->setAccessToken([ACCESS TOKEN FOR THIS USER - APP]);

    $api_call = array(
        'method' => 'users.hasAppPermission',
        'uid' => $uid,
        'ext_perm' => 'publish_checkins'
    );
    $can_post = $facebook->api($api_call);
    if ($can_post) {
        $facebook->api('/'.$uid.'/checkins', 'POST', array(
        'access_token' => $facebook->getAccessToken(),
        'place' => '[LOCATION ID]',
        'message' => 'I am place to check in',
        'picture' => 'http://test.com/someplace.png',
        'coordinates' => json_encode(array(
           'latitude'  => '[LATITUDE]',
           'longitude' => '[LONGITUDE]',
           'tags' => '[A LIST OF TAGS TO USE FOR THIS CHECKIN]'))
        ));
        echo 'You are checked in';
    } else {
        die('Permissions required!');
    }
} catch (Exception $e){
    // No user found - ask the person to login
    $login_url = $facebook->getLoginUrl();
    header("Location: ".$login_url);
}

A: What that code is trying to achieve is not possible anymore: https://developers.facebook.com/docs/graph-api/reference/v2.5/user/checkins

This endpoint is removed as of Graph API version 2.0

You can only get the user checkins by using the /me/feed enpoint, since checkins are now just status posts with a place.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I implement park/unpark methods in pure Java? I know LockSupport is part of the JDK, but I am wondering if the implementation below is semantically correct. Observe that Object.wait can deal with the problem of thread's interrupt. My question is not regarding performance; however, I will appreciate any suggestion to improve my solution as long as your solution only uses basic construction like wait, notify and synchronized.
Thanks a lot.
final class LockSupport {
    static void park(long time) {
        Thread th = Thread.currentThread();
        if (th instanceof MyThread) {
            MyThread h = (MyThread)th;
            synchronized (h.obj) {
                if (h.permit) {
                    h.permit = false;
                    return;
                }
                try {
                    h.obj.wait(time);
                } catch (InterruptedException e) { }
            }
        }
    }

    static void unpark(MyThread h) {
        synchronized (h.obj) {
            h.permit = true;
            h.obj.notify();
        }
    }
}

abstract class MyThread extends Thread {
    public Object obj = new Object();
    public boolean permit = true;
}

A: Initial permit should be false.
When an interrupt is caught, you need to re-interrupt the current thread
 catch (InterruptedException e) { th.interrupt(); }

because if park() returns due to interrupt, the interrupt status should be set (see javadoc example)
After wait() completes, normally or abruptly due to interrupt, consume the permit.
In unpark(), if permit is already true, there's no need to notify.


text:
Q: CKEditor 3.0 Height Is there a way to set the height of CKEditor 3.0 to a percentage, such as 100%, such that it takes up the whole window?
I am currently using absolute values, but they do not blend well with my UI :(
CKEDITOR.replace('editor1',{
    height: '600px'
});

A: After a lot of fiddling with this resizing stuff on ckeditor 4 I made up this which works perfectly perfectly for me:
in config.js:
// prevent flashing of resizing by setting the content panel to zero height before it is resized
config.height = '0px';
config.width = '100%';

jQuery:
$(document).ready(function(){

    // resize the editor(s) while the instance is ready
    CKEDITOR.on('instanceReady', function() {
        var textEditHeight      = $(".textPanel").height();
        var ckTopHeight         = $("#cke_1_top").height();
        var ckContentsHeight    = $("#cke_1_contents").height();

        for (var i = 1; i < 10; i++) {
            $("#cke_"+i+"_contents").height( (textEditHeight - ckTopHeight - 10) + "px");

        }
    });

    // resize the editor(s) while resizing the browser
    $(window).resize(function(){
        var textEditHeight      = $(".textPanel").height();
        var ckTopHeight         = $("#cke_1_top").height();
        var ckContentsHeight    = $("#cke_1_contents").height();

        for (var i = 1; i < 10; i++) {
            $("#cke_"+i+"_contents").height( (textEditHeight - ckTopHeight - 10) + "px");
        }
    });

});

I have multiple instances of the editor of the exact same size in tabs, for every language one, hence the for loop. If you have one editor you can leave that line away and use the standard id cke_1_contents.
In this example the heights are taken from the first editors toolbar (cke_1_top) and contentpanel (cke_1_contents). The .textPanel height is the surrounding div were the editor should fit in. I added 10px because I needed that for my layout.
I think it can be a littlebit more efficiënt (it initiates the resizing as many times as there are editors) but for now it is finally working flawlessly in all my recent browsers (ff, ie, chrome and safari).

A: I managed to configure a 100% height via CSS:

*

*Configure the editor with config.height = '100%', even when the docs say this isn't supported.

*Put this in your CSS:

span.cke_wrapper cke_ltr,table.cke_editor, td.cke_contents, span.cke_skin_kama, span.cke_wrapper, span.cke_browser_webkit{
    height: 100%!important;
}

I tested this with Chrome, Firefox and Safari and it worked fine. Since this is pure CSS, the height will get adjusted automatically when the window or the corresponding container is resized.

A: The documentation on ckeditor for CKEDITOR.config.height say that they do not support percentage units e.g.: 30%;
however, there is a td with a class of cke_contents. if you set the height on that (with an absolute value it will work).
It seems that ckeditor does not have a good solution for this problem.
The only other way I can think of is to use javascript to change the style on the above td.

A: None of the above solutions worked fine for me in order to set the height either with percentage or without it. Percentages are still not supported at all unless you hack it with one of the above solutions.
As stated in the documentation, you may set the height and css style with:

http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.height

A: Put this property in your css config file:
.cke_reset{
    min-height: 200px;
}

A: First add a function for resizing your edtior:
function resizeEditor() {

  var defaultHeight = 300;
  var newHeight = window.innerHeight-150;
  var height = defaultHeight > newHeight ? defaultHeight: newHeight;

  CKEDITOR.instances.editor1.resize('100%',height);
}

Note: 150  works for me, maybe change the value from 150 to more or less.
Call this from the window onresize Event:
window.onresize = function() {
  resizeEditor();
}

and add the first call to the constructor of your editor:
CKEDITOR.replace('editor1',
  {
    on:
    {
      instanceReady: function(ev)
      {
        setTimeout(resizeEditor, 500);
      }
    }
  });

A: I have been looking for a clean way to get the CKEditor window to be the same height as the textarea it is replacing. I'm using Drupal, and this is how I did it ...
In my theme I load up a javascript file, (using "scripts[] = default.js" in my .info file).
In this file I have:
$(document).ready(function(){

    // Set CKEditor height
    if (typeof CKEDITOR!='undefined') {
        CKEDITOR.on( 'instanceReady', function( e ) {
            e.editor.element.show();
            var elHeight = $(e.editor.element.$).height();
            e.editor.element.hide();
            e.editor.resize('100%', elHeight, true);
        });
    }
}

The beauty of this is you can then change the height using css.
I had been changing the settings.height via the wysiwyg module in wysiwyg/editors/js/ckeditor-3.0.js
Drupal.wysiwyg.editor.attach.ckeditor = function(context, params, settings) {
    // Apply editor instance settings.
    CKEDITOR.config.customConfig = '';

    // Match the height of the replaced field
    settings.height = $('#' + params.field).height();
}

but this would get overwritten during updates, so went with the top solution.

A: here is the dojo version of the code above... in case anyone is interested...
var adjustEditor = function() {
  var editorNode = dom.byId('cke_messageEditor');
  console.log("editor node %s ", editorNode);
  var editorStyle = domStyle.getComputedStyle(editorNode);
  console.log("editor node %s and style %s", editorNode, editorStyle);
  var textEditHeight      = domGeom.getMarginBox(editorNode, editorStyle).h;

  var toolbarNode = dom.byId('cke_1_top');
  var toolbarStyle = domStyle.getComputedStyle(toolbarNode)
  var ckTopHeight = domGeom.getMarginBox(toolbarNode, toolbarStyle).h;

  var contentNode = dom.byId('cke_1_contents');
  var contentStyle = domStyle.getComputedStyle(contentNode)
  var ckContentsBox    = domGeom.getMarginBox(contentNode, contentStyle);
  console.log("text editor: %s, button bar: %s", textEditHeight, ckTopHeight);

  console.log("setting margin box to: %s ", JSON.stringify(ckContentsBox));
  ckContentsBox.h = textEditHeight - ckTopHeight;
  console.log("setting margin box to: %s ", JSON.stringify(ckContentsBox));

  domGeom.setMarginBox(contentNode, ckContentsBox, contentStyle);
}

// adjust editor immediately
CKEDITOR.on('instanceReady', adjustEditor);
// and again everytime the window is resized
on(window, "resize", adjustEditor);

A: I just got around doing this in CKEditor4, not sure if it is any use to you

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

   <textarea name="editor1" id="editor1" class="cktextarea"></textarea>

If you are not using the maximize plugin a lot of the javascript is unnecessary, I replaced the functionality of this plugin because it was breaking the new CSS (and breaking by itself after I set all the CSS !important).

A: This is solution for me, without jQuery, working in C# WebBrowser control, also no vertical scroll when horizontal shown.

<!DOCTYPE html>

 <meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=edge">
 <title>CKEditor Sample</title>

 <link rel="stylesheet" href="css/samples.css">
 <link rel="stylesheet" href="toolbarconfigurator/lib/codemirror/neo.css">


text:
Q: PushSharp OnNotificationSent event not trigger when push notification sent to Android but its trigger when sent to iphone I am using PushSharp library to send PushNotification From .net to android and iphone
my android and iphone recieving push notification sent from .net but in
.net OnNotificationSent event trigger only for ios and not for android
    **My PushSharp registration code**

  push = new PushBroker();
    push.OnNotificationSent += NotificationSent;
    push.OnChannelException += ChannelException;
    push.OnServiceException += ServiceException;
    push.OnNotificationFailed += NotificationFailed;
    push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
    push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
    push.OnChannelCreated += ChannelCreated;
    push.OnChannelDestroyed += ChannelDestroyed;

    push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationSettings.AppSettings["PushNotificationApiKey"]));

    string basePath = AppDomain.CurrentDomain.BaseDirectory;
    string fullPath = Path.Combine(basePath, "Certificates/Certificate.p12");

    byte[] appleCert = File.ReadAllBytes(fullPath);
    push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, ""));


text:
Q: Visual studio 2019 or GIT is ignoring newly added files in the solution even the file extension is not mention in .gitignore
If you see the image two .cs files are locked and i just added Test.cs file in project and it is started showing as ignored file.
Is there any way to make all newly added files automatically added to source control?.

A: Right click on the file in question > Under the Exclude From Project, select the option "Add ignored file to Source Control"

A: The "red minus overlay icon in Visual studio's Solution Explorer?" should means "excluded from build", not "ignored by Git".
Double-check in command-line with:
cd /path/to/project
git check-ignore -v -- Test.cs

If it is also ignored, that check-ignore command will give you the exact .gitignore and rule.

A: Right-click on the file  Select Git => Add Ignored file to source control


text:
Q: How to set input element value to some string which has double quotes? In the following code I am not able to set a value which has double quotes.
<html>
<head>
</head>
<body>
<div id="d"/>
<button id="button">Click Me</button>
</body>
<script>
    var button = document.getElementById("button");
    button.onclick = function() {
        var d = document.getElementById("d");
        var value = 'some"val\'ue';
        var h = "<input type=\"text\" id=\"someid\" value=\"" + value + "\">"
        d.innerHTML = h;
    }
</script>
</html>

Is there any way to do it?
Note: Due to some reasons I cant render the input element first and later set the value using .value. I have to do it using innerHTML.

A: " is html way of saying ".


text:
Q: Display custom user profile fields in wordpress I am new to wordpress development. I was trying to solve the problem of adding extra fields to my wordpress user profile area. I achieved this with a plugin. How do I call the value of these fields on my custom dashboard page template for logged in users, like so: <?php echo $profile_field_name ?>.

A: You can use get_user_meta Function. for exp in your case :
$profile_field_name = '';
if (get_user_meta( $user_id, 'profile_field_name', true )){
     $profile_field_name = get_user_meta( $user_id, 'profile_field_name', true );
    };

then you can echo like your example :
<?php echo $profile_field_name ?>


text:
Q: "Continued on next page" automatically inserted in footnote Re: bigfoot (three different sets of footnotes used) and footmisc.
I am looking for a way to have a symbol (~☞) or text (Cont'd.) inserted automatically at the end of each footnote that continues onto the next page, similar to what is possible for tables or described here
(Adding a MWE seems rather pointless.)
PS: As this is NOT a coding problem I'll provide an explanatory screenshot.


text:
Q: ModuleNotFoundError: No module named 'gensim' My goal is to import gensim in Python 3 on Windows.
I am using Python 3.7.2 (checked by running python -V in Windows command prompt). I installed gensim by running pip install gensim. I checked the installation by running pip freeze, and saw the line gensim==3.7.3.
Then, I ran the command py to enter the interactive python mode (still in Windows command prompt). I ran the line import gensim and got the following output:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'gensim'

I also tried from gensim import test and got the following output:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'gensim'

Any suggestions? How do I install gensim on Windows with Python 3? How do I test gensim?

A: In Mac, open anaconda navigator, Click on 'Open Terminal option'. If you are using Windows, Run anaconda prompt as administrator and run the following command:

conda install -c conda-forge gensim

A: I think you have installed it using normal cmd, so it may have installed it on python2.x. Install it with anaconda prompt.
Let me know if it worked for you.

A: I got the same error after installing gensim in Anaconda. It worked only after I re-started the Anaconda: by exiting it, and re-opening it via the command prompt. I wanted to share this experience since someone else may meet the same issue.

A: To understand why this happens, you must know how Windows finds executables to run, and how the Python software is installed.

*

*When running a command, Windows searches for an executable in the environment variable PATH. It executes the first one found.

*python.exe is installed in <PYTHON_INSTALL_DIR> (e.g. C:\Python\3.7).

*pip.exe and other Python tools (e.g. pylint, virtualenv, pycrust, etc.) are installed in <PYTHON_INSTALL_DIR>\Scripts.

*py.exe is installed in your Windows system directory (e.g. C:\Windows).

*python and pip commands use the modules found in the directory their installed in, they do not look at PATH.

So, let's say you have the following Python versions:
C:\Python\2.7
C:\Python\3.6
C:\Python\3.7

and your PATH environment contains the following directories:
C:\Python\2.7
C:\Python\3.6\Scripts

then, see the following output:
C:\>python -V
Python 2.7.16

C:\>pip -V
pip 19.1.1 from c:\python\3.6\lib\site-packages\pip (python 3.6)

C:\>py -V
Python 3.7.3

So, when running pip, it is possible that the packages are installed in another Python version then the version you'll get when running python.
To see which versions are (correctly) installed on your system, run py -0p. Example output:
C:\>py -0p
Installed Pythons found by py Launcher for Windows
 -3.7-64        C:\Python\3.7-64\python.exe *
 -3.7-32        C:\Python\3.7-32\python.exe
 -3.6-64        C:\Python\3.6-64\python.exe
 -2.7-64        C:\Python\2.7-64\python.exe
 -2.7-32        C:\Python\2.7-32\python.exe

General solution (for Windows)
The best thing is not to rely on your system PATH. Use the py launcher to select the version you want. To run the pip module corresponding to the Python version you want to use, start pip as a module instead of executable.
So instead of:
pip install <package>

run:
py -3.6 -m pip install <package>

A: Here's My hypothesis towards your situation, since your OS is able to recognize both python and py commands in commandline, this may mean that you have two separate versions of python installed.
Since, as you mentioned that python -V shows gensim as an installed module. Try opening python interactive interpreter via command python instead of py, and import gensim module in it.
C:\Users> Python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import gensim

see if that works.
P.S.
I would not recommend having two different compiler versions on a single OS as it creates a lot of commotion, and create incompatibility issues with program's made on one compiler with the other. And makes problems (like you mentioned) a lot more prevalent.

A: Most probably you have > 1 python installed in your machine. To install gensim (or any package) inside python command line, you can run below:

*

*type "python" then enter

*type "import subprocess" then enter

*type
"subprocess.check_call(["python", '-m', 'pip', 'install', 'gensim'])"
then enter

Sample below:
>>> import subprocess
>>> subprocess.check_call(["python", '-m', 'pip', 'install', 'gensim'])
Collecting gensim
..
...
Installing collected packages: smart-open, gensim
Successfully installed gensim-3.7.3 smart-open-1.8.3
0


text:
Q: Is it possible to call a method to send messages while a WebsocketApp is running from the same class? I am working on a websocket application that utilizes WebSocketApp from websocket-client. As my websocket is running, and listening for messages I would like to be able to call a method to send a message to the server as needed.
WebSocket
import websocket

class WebSocketTest():

    wsapp = None
    print("starting websocket app")
    ws_is_open = False

    def on_message(self, wsapp, message):
        print("ON_MESSAGE")
        print(message)

    def on_open(self, wsapp):
        print("SOCKET OPENING")
        self.ws_is_open = True

    def on_close(self):
        print("SOCKET CLOSING")

    async def start(self):
        self.wsapp = websocket.WebSocketApp("ws://localhost:5001",
            on_message=self.on_message,
            on_close=self.on_close,
            on_open=self.on_open)
        self.wsapp.run_forever()

    def send(self, msg):
        if self.ws_is_open:
            print(f"SENDING: {msg}")
            self.wsapp.send(msg)

Test Setup File
from websocketapp import WebSocketTest
import asyncio

ws = WebSocketTest()
asyncio.run(ws.start())
ws.send("Hello!")

Output
some_user python % python test.py
starting websocket app
SOCKET OPENING

I have created a setup file that initializes the class, starts the server and then attempts to send a message using the send method. It looks like it never gets to the line that calls send. The connection to the server works, and if I broadcast a message from my websocket server to the client on_message is triggered and I see the message printed out.


text:
Q: Rake task to change all occurances of a method in a project I am trying to write a rake task to rename all occurrences of a method in a ruby project. I have achieved this using the following command from the command line.
Basically
retention.group_by('bla').count

needs to be changed to
retention.group_by('bla').size

I managed to achieve this uisng the following from the command line
find . -name \*.rb -exec ruby -i -p -e "gsub(/(group_by(\(([^\)]+)\))).count/, '\1.size')" \;

I am now trying to do this from a rake task to make it straight forward to change in all our projects. Which is the easiest / most elegant way to do this ? Think I am close, its just selecting all files in a project directory I am stuck on.

A: This did the trick
 namespace :rename do

  task :gb_count_rename do
    Dir.glob("**/*.rb").each do |file_name|
      text = File.read(file_name)
      content = text.gsub(/(group_by(\(([^\)]+)\))).count/, '\1.size')
      File.open(file_name, "w") { |file| file << content }
    end
  end

end


text:
Q: Laravel 5.4 cannot view image in public storage in blade I am having trouble getting Laravel to display an image that is in public storage.
Each user has their own folder and I want to display their profile image.
I've searched everywhere for an answer and I'm doing everything suggested and it still won't show the image.

*

*I've run php artisan storage:link

*I've made sure that Options FollowSymLinks is set in Apache

*The image exists in the public storage folder

*I've set permissions of the user folder and image to 777

I have tried the following and the image is not shown
<img src="{{ asset('storage/' . $userfolder. '/profile_image.png') }}">

If I go to the URL for the image in the browser, I get a 403 error message.
I don't know if I'm missing anything from here
'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],
...

A: Just make sure:
$userfolder = $filename . '_' . time() . '.' .$extension;
NOT:
$userfolder = $request->file('imagePath')->storeAs('public', $fileNameToStore);
The 1st code will store file as filename.ext , 2nd code will store file as public/filename.ext
using src="{{ asset('storage/'..... will give you a path with public/ folder already so using src="{{ asset('storage/'.' $userfolder' with the first code in your controller will show image


text:
Q: Need help with complex SQL query for moving nested set items I have a database of rows that are organized via Nested sets. This is from a site that was suppose to be a multi-tier affiliate site, but the prior programmer made the decision to use nested sets instead of a simple tier system, so virtually every row affects every other row in terms of positioning, and this is a big pain when trying to move a tiered member to a different tier. The code below is supposed to move a nested set from one to another, but the problem is after I have ran the code the left and right values are not what they are supposed to be, they are thousands of numbers off. Another difficulty is each row is related to another row in the same table. Below is the SQL code that I hacked together from another post on here, so all help would be appreciated.
Thanks for the consideration.
# step 0: Initialize parameters.
SELECT
    @member_id := e1.memberid,
    @member_lft := e1.lft,
    @member_rgt := e1.rgt,
    @parent_id := e2.memberid,
    @parent_rgt := e2.rgt,
    @member_size := @member_rgt - @member_lft + 1
FROM ept_viewer e1
LEFT JOIN ept_viewer e2
#put the new parent id
ON e2.memberid = $
#put the child id
WHERE e1.memberid = $;

# step 1: temporary "remove" moving node
UPDATE `ept_viewer`
SET `lft` = 0-(`lft`), `rgt` = 0-(`rgt`)
WHERE `lft` >= @member_lft AND `rgt` <= @member_rgt;

# step 2: decrease left and/or right position values of currently 'lower' items (and parents)
UPDATE `ept_viewer`
SET `lft` = `lft` - @member_lft
WHERE `lft` > @member_rgt;
UPDATE `ept_viewer`
SET `rgt` = `rgt` - @member_size
WHERE `rgt` > @member_rgt;

# step 3: increase left and/or right position values of future 'lower' items (and parents)
UPDATE `ept_viewer`
SET `lft` = `lft` + @member_size
WHERE `lft` >= IF(@parent_rgt > @member_rgt, @parent_rgt - @member_size, @parent_rgt);
UPDATE `ept_viewer`
SET `rgt` = `rgt` + @member_size
WHERE `rgt` >= IF(@parent_rgt > @member_rgt, @parent_rgt - @member_size, @parent_rgt);

# step 4: move node (ant it's subnodes) and update it's parent item id
UPDATE `ept_viewer`
SET
    `lft` = 0-(`lft`)+IF(@parent_rgt > @member_rgt, @parent_rgt - @member_rgt - 1, @parent_rgt - @member_rgt - 1 + @member_size),
    `rgt` = 0-(`rgt`)+IF(@parent_rgt > @member_rgt, @parent_rgt - @member_rgt - 1, @parent_rgt - @member_rgt - 1 + @member_size)
WHERE `lft` <= 0-@member_lft AND `rgt` >= 0-@member_rgt;

A: I've never used Nested Set in SQL either but I've read about them and their are some advantages that may be applicable.
Joe Celko has written extensively on the topic so google "Joe Celko nested Sets" for more info
Here's a link to his book on Google Books that might be a good place to start too Celko's Trees and Hierarchies


text:
Q: How to create a self-signed certificate using PRINTABLE_STRING, IA5STRING or BMPSTRING as certificate fields? I need to know how I can make sure certificate fields of my self-signed certificate, like subject common name and issuer common name, is encoded as PRINTABLE_STRING, IA5STRING or BMPSTRING, but not UTF-8 encoding.
I'm trying to create it using PowerShell cmdlet.
I'm trying to create a self-signed certificate that conforms to these rules.
These are the parameters I found that I think comply with those rules.
New-SelfSignedCertificate -DnsName 'wdac' -CertStoreLocation Cert:\CurrentUser\My\ -Type Codesigning -HashAlgorithm "SHA512" -KeyLength 4096 -KeyAlgorithm RSA


text:
Q: Compute the factorial of n using range with two parameters I am trying to compute the factorial of n using for loop and an accumulator. I am having trouble with the range command and its two parameters - start and end. I am getting invalid syntax error. Here's the code:
# factorial.py
#   Program to compute the factorial of a number
#   Illustrates for loop with an accumulator

def main():

    n = int(input("Please enter a whole number: "))

    fact = 1

    for factor in range(1, (n + 1))
        fact = fact * factor

    print("The factorial of", n, "is", fact)

main()

Where's the problem?
I am using Python 3.6.

A: You simply forgot a : after your range function since it is a for loop ^.^


text:
Q: extract columns containing a specific string in the header I have a tab delimited file, where I want to scan the header (first line) for columns that contain a key word. Then, I want to print only those columns from the rest of the file.
From this example file:
sample  AAA BBB sample_CCC  DDD EEE sample_FFF
000 aaa bbb ccc ddd eee fff

I am looking to get something like this:
sample  sample_CCC  sample_FFF
000 ccc fff

I have tried:
awk -F"\t" '{for(i=1;i<=NF;i++){if ($i ~ /sample/){print $i}}}' filename > outputfile

however, this only pulls out columns with that exact string (sample), not columns that contain it (sample_CCC, sample_FFF).
Is there a way to alter this code so that it will pull columns that do not match the string exactly, but contain the string?

A: perl allows a nice concise solution:
perl -ale '
    @cols = grep {$F[$_] =~ /sample/} 0..$#F if $. == 1;
    print "@F[@cols]";
' file

A: What about something like this?
NR==1   {
        for (i=1; i<=NF; i++) {
                if ($i ~ /sample/) {
                        head[i]= $i
                        printf "%s\t", $i
                }
        }
        printf "\n"
}

NR>1    {
        for (i=1; i<=NF; i++) {
                if (head[i]) {
                        printf "%s\t", $i
                }
        }
        printf "\n"
}

A somewhat naïve approach, but it does the job for small files.

A: $ awk '
    BEGIN { FS=OFS="\t" }
    NR==1 {
        for (inFldNr=1; inFldNr<=NF; inFldNr++) {
            if ($inFldNr ~ /sample/) {
                out2inFldNr[++numOutFlds] = inFldNr
            }
        }
    }
    {
        for (outFldNr=1; outFldNr<=numOutFlds; outFldNr++) {
            inFldNr = out2inFldNr[outFldNr]
            printf "%s%s", $inFldNr, (outFldNr<numOutFlds ? OFS : ORS)
        }
    }
' file
sample  sample_CCC      sample_FFF
000     ccc     fff


text:
Q: SQL Server drop query request It is possible to view and analyze queries in SQL Server before implement on database and log or drop it if necessary?
For example some application send an update query to SQL Server, can I first log it to a database, and then possibly reject it if the query is illegal based on my roles?

A: You can use SQL Profiler to monitor queries sent to server, but you can't do what you wnat to.
If you say it is illegal for smoe roles to execute some queries it should be specified in permissions - every role have assigned permissions.
One way to achieve what you want is to define user, which mentioned applciation would use (I would even create dedicated user). Then, if you want this user to execute SELECT, just execute such command
GRANT SELECT ON [table] TO [user]

Then the user won't be able to update table, just select rows from it.

A: I found solution to use SQL SERVER triggers so after insert or update I check my role so if there is any access problem I can rollback transaction and send error to user.


text:
Q: xcdatamodeld issue with adding new fields i have a a Cars.xcdatamodeld (used for a light migration) that has my main entity Cars2.xcdatamodel (it is the entity selected)
when i try to add a field to my Cars2, i am not permited to add a field that starts with a upper scale letter (although there are fields that are with an upper scale).
When i try:
Cars *CS = (NeonSigns *)[NSEntityDescription insertNewObjectForEntityForName:@"Cars" inManagedObjectContext:managedObjectContext];
CS.newImageUrl = @"www.xrt.ro/a.jpg"

where .newImageUrl is a field i just added, the compiler doesn't recognize newImageUrl (although it recognizes the other fields) . Why is this?

A: NextStep naming conventions dictate that class definitions begin with a capital letter and methods and properties begin with lower case letters. Core Data depends upon those conventions when translating between the different representations of information in the Core Data stack, model definitions, back end stores, and runtime objects. Core Data maps entities to Objective C classes and attributes to properties of those classes. You can confuse Core Data when you deviate from this naming convention.


text:
Q: Installing the ahkab packages of Python I've one problem, when I try to install the 'ahkab' packages on Linux, Ubuntu based, for Python with the command pip (pip install ahkab).
You can to see my problem on image below. I don't know what do I need to do to solve this case.

A: I think you may need to run with super user permission while installing.
Use sudo in-front of you command.


text:
Q: WPF - Slider with a range of number - draw bar I'm working on a WPF project with the MVVM pattern and i need to create a user control like the following image:
Which has a vertical slider, a range of numbers and a graph that represent the selected value over the total being able the user to increment and decrease the value with the slider.
The problem is that i don't know how to create such a slider and i am also having some problems to draw the colour bar filled.
Any help would be very appreciated. Thanks in advance.
This is what i have in xaml:
<UserControl x:Class="Tenaris.SM.View.CCMOperativeScreen.View.Controls.SetPointSteelLevel"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>

</UserControl.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="7*"/>
    </Grid.ColumnDefinitions>
    <Grid>
         <Slider Orientation="Vertical"></Slider>
    </Grid>
    <Grid Grid.Column="1" HorizontalAlignment="Left">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Style="{StaticResource GridValueCell}" Text="88" />
        <TextBlock Style="{StaticResource GridValueCell}" Text="87" Grid.Row="1"/>
        <TextBlock Style="{StaticResource GridValueCell}" Text="86" Grid.Row="2"/>
        <TextBlock Style="{StaticResource SetPointPresetNumber}" Text="85" Grid.Row="3"/>
        <TextBlock Style="{StaticResource SetPointPresetNumber}" Text="84" Grid.Row="4"/>
        <TextBlock Style="{StaticResource SetPointPresetNumber}" Text="83" Grid.Row="5"/>
        <TextBlock Style="{StaticResource SetPointPresetNumber}" Text="82" Grid.Row="6"/>
        <TextBlock Style="{StaticResource GridValueCell}" Text="81" Grid.Row="7"/>
        <TextBlock Style="{StaticResource GridValueCell}" Text="80" Grid.Row="8"/>
        <TextBlock Style="{StaticResource GridValueCell}" Text="79" Grid.Row="9"/>

    </Grid>
    <Grid Grid.Column="2">
        <Rectangle>
            <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                    <GradientStop Color="#303030" Offset="0" />
                    <GradientStop Color="LightGray" Offset=".5"/>
                    <GradientStop Color="#303030" Offset="1" />
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
</Grid>

A: Dude, you need to learn how to search for help. If you type Slider class into a search engine, the very first result will almost certainly be for the API page on MSDN: Slider Class. The vast majority of these API pages on MSDN have detailed descriptions and often code examples to help you... use them. If you had looked there, you'd have seen that you don't have to manually add the numbers to the side of the Slider... they will be added by the control if you set the right settings on the control.
Next: Rectangle Class. On this page, you'll find a Height property that Gets or sets the suggested height of the element. We can use that to change the Height of the rectangle/bar. You could do that in two ways... either by manually setting Rectangle.Height = newValue, or by using data Binding... again, MSDN to the rescue.
Finally to the Style... your bar looks like it has one grey Rectangle in the background that doesn't move and then one on top of it (with a small Margin set on it). You could put both of these into the same grid cell making sure to declare the back one first. I hope that helps.
Good luck with your interesting project.


text:
Q: Display Woocommerce Product Attribute Term Description on product page In WooCommerce under Products > Attributes > [Name of Attribute] > Add New [Attribute Variation] there is a section titled "Description" with the text "The description is not prominent by default; however, some themes may show it."
I would like to display this on the Product Page, underneath the attribute dropdown
This is how I want it to look:

And this is where the code should go I assume:
<?php foreach ( $attributes as $attribute_name => $options ) : ?>

                        <label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?>

                            <?php
                                $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) : $product->get_variation_default_attribute( $attribute_name );
                                wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                            ?>

                <?php endforeach;?>

Someone has asked something similar on here but I can't see how to amend it to display on the product page.
$values = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' =>  'all' ) );
if( $values ){
    echo '
';
        foreach ( $values as $term ){
            echo '<dh>' . $term->name.' </dh>';
            echo '
' . term_description( $term->term_id, $term->taxonomy ) . '
';
        }
    echo '
';
}

Thank you

A: try to get attribute value with single attribute name.
$values = wc_get_product_terms( $product->id, 'test_attributename', array( 'fields' =>  'all' ) );
if( $values ){
    echo '
';
        foreach ( $values as $term ){
            echo '<dh>' . $term->name.' </dh>';
            echo '
' . term_description( $term->term_id, $term->taxonomy ) . '
';
        }
    echo '
';
}

A: As specified here - term_description you can use term_description() to get the description of a term of choice.
The function accepts two parameters, one being the id of the tag and the other the slug of the term you want to get the description for. If no term ID is passed, the description of current queried term will be returned.
The function works inside the product-attributes.php file.


text:
Q: What vim plugins are available for Eclipse? I have found three and would like to know if there are others and what their advantages or disadvantages might be:

*

*Vimplugin

*Vrapper

*Eclim
I've included Eclim, but it differs from the other two options in that it makes Eclipse functionality available in vim and what I'm really after is vim functionality within the Eclipse environment.

A: Eclim
Eclim is not the correct approach in my opinion. You want to retain the flexibility and functionality of the IDE while gaining the editing power of Vim.
viPlugin
I used viPlugin when I was working with Eclipse. However it is not free (unlike the IntelliJ Idea Vim plugin). It also is not as thorough as the Visual Studio Vim plugin. You'll find that certain functionality is missing. Things like Ctrl+] to "go to definition" or Ctrl+o for "go back" don't work. Macros don't work either however it does have marks. It provides the core functionality of Vim text editing. If I recall correctly you can even have a simple vimrc configuration file. You can do a free trial to test it out.
Vrapper
Apparently Vrapper has macros and marks, as well as the following commands:
Motions
h j k l w W e E b B f F t T ; , ^ $ 0 % G H M L gg ge gE
Operators
y Y d D c C s S p P r J x X i I a A o O . < > gc gu gU
Search
/ ? n N * #
Text Objects (only in normal mode)
ib i( i) i[ i] iB i{ i} i i" i' i` iw iW ab a( a) a[ a] aB a{ a} a a" a' a` aw aW
Counts
You can use the number keys to specify counts in front of other commands.
Other Commands
v V u <C-R> <C-F> <C-B> ~ q @ zo zR zc zM zz gt gT
Plus it's free, so I'd go with that one.

A: Sadly, viplugin is the best one.

A: I have tried Viable and it's my top pick out of them all. It's got pretty much all the features of Vrapper, but some additional features that none of the others have like window splitting, command history, and external filters and commands.
It is pay, but it's free to try. It does lack some of the basics like Pierre mentioned, no support for Ctrl+] for example, however the development is active so chances are it will be implemented.

A: I used viplugin for quite a while, but now that I've built up a pretty customized vim environment I've switched to eclim.  Vim already gives you most of what you need - tags, file navigation, and project view.  Eclim gives you a way to plug into eclipse and gets you the completion and refactoring tools.  You use vim for what it's best at and eclipse for what it's best at.
Really, I think trying to reimplement vim within the eclipse environment is just a losing proposition.  If all you care about are the basic movement and navigation functions, one of the plugins will work just fine.  But if you've invested time in getting vim to work the way you want it to, eclim is a painless way to easily hook into eclipse.


text:
Q: CloudFormation building a cluster and need pass Master IP to other resources I have a CloudFormation template that I currently have hardcoded with IP addresses that I know I have in a subnet. Being part of a large corporation I need to make it dynamic as I create more clusters and have to reference IP addresses. In my current setup I have 1 master and a bunch of slaves that all need to know the master's IP. They do not need to know each other.
I have found the following:
"MasterNetInt" : {
  "Type" : "AWS::EC2::NetworkInterface",
  "Properties" : {
    "SubnetId": { "Ref" : "MySubnet" }
  }
}

My question is that I just need to put this one resource and than under each of the 10 slaves have something like this:
    "UserData": {
                        "Fn::Base64": {
                            "Fn::Join": [
                                "", [
        "sed -i -e 's/server_host=localhost/server_host=", { "Fn::GetAtt": [ "MasterNetInt", "PrimaryPrivateIpAddress" ] }, "/g' /etc/master/config.ini \n",
...

A: Assuming that the ref name is "MasterNetInt" this should work to give you the IP
 "Fn::GetAtt": [
                            "MasterNetInt",
                            "PrivateIp"
                        ]


text:
Q: Is the image in $\mathbb{Q}_{p}^{\times}$ of a Cauchy sequence in $\mathbb{Q}_{p}$ also Cauchy, or even fixed?
Is the image in $\mathbb{Q}_{p}^{\times}$ of a Cauchy sequence in $\mathbb{Q}_{p}$ in general, also Cauchy?  Must it be a fixed point?

I'm assuming that it's conventional to consider a sequence to be Cauchy in $\mathbb{Q}_p$ if it's Cauchy as measured by its p-adic metric.
By the image in $\mathbb{Q}_p^{\times}$ of a number $n$ in $\mathbb{Q}_p$ I mean $n\times\lvert n\rvert_p$ for example the image of $24$ in $\mathbb{Q}_2^{\times}$ is $3$.
If true, this fact would be helpful.  It looks like it should generally be true but if we consider the sequence:
$2^n\times n\times (2(n\mod 2)+1)$ for increasing integers $n$, i.e. the sequence:
$\{1,6,4,24,16,96,64,\ldots\}$
We can see from the sequence $\lvert n_i-n_{i-1}\rvert_2=\{1,\frac{1}{2},\frac{1}{4},\frac{1}{8},\frac{1}{16},\ldots\}$ that it is Cauchy in $\mathbb{Q}_2$ despite the fact that its image in $\mathbb{Q}_2^{\times}$ is $\{1,3,1,3,1,\ldots\}$ and it would appear on the face of it to have two distinct trajectories.
Now I'm led to believe that the 2-adics are something of a special case when it comes to convergence because uniquely their logarithm has a nontrivial kernel in the $\mathbb{Z}_2$-principal units (and let me be clear, I have next to no idea what that means).  The question is, is this independence of convergence in the two components of Cauchy Sequences unique to $\mathbb{Q}_2$ or can this happen for any $p$?

A: No, there's no such requirement in any base $p$. Convergence of a sequence in $\mathbb{Q}_p$ and convergence of its image in $\mathbb{Q}_p^{\times}$ can be independent, as demonstrated by:
The Cauchy sequence $(-p)^k$ whose image in $\mathbb{Q}_p^{\times}:\{-1,+1\}$ does not converge.
And the sequence:
$\{2,12,14,60,62\ldots\}$ which does not converge in $\mathbb{Q}_2$ while its image in $\mathbb{Q}_2^{\times}: \{1,3,7,15,31,\ldots\}$ is Cauchy.


text:
Q: How to insert a star into the Chile flag using Turtle graphics I'm using turtle graphics and I was able to create the most of the Chilean flag. Here is my code so far.
import turtle

def rectangle(wdth, ht, c):
  turtle.fillcolor(c)
  turtle.begin_fill()
  for i in range(2):
    turtle.forward(ht)
    turtle.left(90)
    turtle.forward(wdth)
    turtle.left(90)
   turtle.end_fill()

rectangle(50, 250, "red")

turtle.left(90)
turtle.forward(50)
turtle.right(90)

rectangle(50, 100, "blue")
turtle.right(360)
turtle.forward(50)

rectangle(50, 200, "white")

turtle.done()

I want a white star to be placed within the blue box and I can't seem to get it right.

A: My first suggestion is that you lookup the Flag of Chile in Wikipedia and correct your aspect ratio.
Drawing a star is trivial using turtle's .circle() function:
import turtle

STAR_SIZE = 27

turtle.begin_fill()
turtle.circle(-STAR_SIZE, 720, 5)  # twice around the circle in five steps
turtle.end_fill()

turtle.hideturtle()

turtle.done()

But there are complications if/when we want to make it a filled star.  On Windows implementations of tkinter, the filled star should look fine.  But on Unix-based implementations, you get this:

In order to get a proper star in both environments, we have to draw it a different way.  I suggest you search SO for tag [turtle-graphics] and term 'star' to see possible solutions.  Here's my personal approach which is to use stamping, instead of drawing, to make both the star and the flag itself:
from turtle import Turtle, Screen

WIDTH = 250
HEIGHT = WIDTH * 2 / 3
STAR = HEIGHT / 8
EXPAND = 1.2
TRANSLATION = STAR * EXPAND / 4
CURSOR_SIZE = 20

screen = Screen()

tortoise = Turtle('square', visible=False)
tortoise.penup()

tortoise.shapesize(HEIGHT / CURSOR_SIZE, WIDTH / CURSOR_SIZE)
tortoise.fillcolor('red')
tortoise.stamp()

tortoise.shapesize(HEIGHT / 2 / CURSOR_SIZE, WIDTH / CURSOR_SIZE)
tortoise.sety(tortoise.ycor() + HEIGHT / 4)
tortoise.fillcolor('white')
tortoise.stamp()

tortoise.shapesize(stretch_len=HEIGHT/ 2 / CURSOR_SIZE)
tortoise.backward(HEIGHT / 2)
tortoise.fillcolor('blue')
tortoise.stamp()

# Draw the white star in the blue field

tortoise.shape('triangle')
tortoise.shapesize(STAR * EXPAND / 2 / CURSOR_SIZE, STAR * EXPAND / CURSOR_SIZE)
tortoise.left(18)  # make sure star has an upward point
tortoise.color('white')

for _ in range(5):
    tortoise.right(72)
    tortoise.forward(TRANSLATION)
    tortoise.stamp()
    tortoise.backward(TRANSLATION)

screen.mainloop()

Of course, you can mix and match drawing with stamping.


text:
Q: Existence of Knight's Tours on an ordinary chessboard Is it possible,starting from any of the 64 squares of the chessboard, to move a knight such that it occupies every square exactly once and return to the initial position? If so, give one such tour.
I don't have any idea

A: HINT
Yes, it is possible. I would encourage you to draw a chess board and start. Here's a hint: the corner moves are all prescribed.


text:
Q: Popup/Alert between two ViewController Segue I have two ViewController and use a (tableview click) seque for opening the second ViewController.
My Problem is, the Second View Controller load much Data. So the time between switch is <> 10 Seconds. In this 10 Seconds the App freeze. Thats OK, but HOW can i insert a "Popup" or "Alert" Message like "Please Wait..." BEVOR . I have testing much tutorials for Popups and Alerts, but the Popup/Alter shows only, when the SecondView Controller is complete loaded. I will show the Message BEVOR the SecondViewController is compled loaded.
Example:
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

        // IF i set here the ALERT, the Alter was only show, when the Second View Controller is complete loaded!

        NSDictionary *rowVals = (NSDictionary *) [SearchNSMutableArray objectAtIndex:indexPath.row];

        [self performSegueWithIdentifier:@"Foo" sender:self];

    }

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {

        if ([[segue identifier] isEqualToString:@"Foo"]) {

            // Get indexpath from Tableview;
            NSIndexPath *indexPath = [self.SearchUITableView indexPathForSelectedRow];

            // Get Data from Array;
            NSDictionary *rowVals = (NSDictionary *) [self.SearchNSMutableArray objectAtIndex:indexPath.row];

            // Destination View;
            [MySecondViewController alloc];
            MySecondViewController *MyView = (MySecondViewController *)segue.destinationViewController;

        }
}

A: You are trying to fix the problem with the wrong solution. That solution is just as bad because the popup will also freeze for 10 seconds. What if you add more data and it takes 30 seconds or 10 minutes? Are you going to expect your users to see a dialog they can't dismiss for 10 minutes?
Are you fetching the data from the internet? If so you need to fetch your data asynchronously in the background.
If you're loading it from disk then there's too much being loaded that could possibly be displayed on one screen, you need to load only a small portion of it, and if that still takes a long time you need to load it asynchronously.

*

*UPDATED -

You should have a model class for your application that is responsible for fetching the data from the internet.
Google Model View Controller to get some background information on what a Model is.
As soon as the app launches the model can start to download the data which needs to be down in the background (that's too big a topic to answer how to do that here).
The View controller can launch while the data is being downloaded and it can display a spinning activity indicator wheel or progress bar or dialog etc. while waiting. The important thing is the GUI will not freeze.
When the model has downloaded the data it needs to tell the view controller the data is now available, which it can do using NSNotification center.
There's lots for you to investigate and learn, to do it without GUI freezing it needs to be done properly, there's no shortcut, you have a lot to study.

A: @Martin,
i found a solution:
// Send the Request;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

So the request are asynchrony. Thanks for your answer. Great +1


text:
Q: an input prompt that dynamically reflects the number of characters as you type How can I, in a bash script, have a variable that takes user input of no more than 300 characters, and displays the number of characters left as the user types?
In this case the characters will be numbers corresponding to a feed from get-iplayer, with a maximum of 4 characters in a block separated from the next by a space.
The relevant script follows -
{
    read -n1 -p "Do you want to download some tv programmes? [y/n/q] " ynq ;
    case "$ynq" in
        [Yy]) echo
      read -n300 -p "Please input the tv programme numbers to download [max 300 characters]  " 'tvbox'
              echo
              cd /media/$USER/back2/proggies/
              /usr/bin/get-iplayer --get $tvbox
              ;;
        [Nn]) echo;;     # moves on to next question in the script
        [Qq]) echo; exit;;            # quits
        * ) echo "Thank you ";;
     esac
};

A: If you have a string consisting of space-separated words, you can iterate over it like this:
str="hello world nice to meet you"
for word in $str; do
    echo "word=$word"
done

On the other hand, if get-iplayer --get required one argument that is a string consisting of space-separated words, you need to quote the variable:
/usr/bin/get-iplayer --get "$tvbox"

I assume from your comment that if you enter "123 456 789 234 567 890 345", you need to call the program like:
/usr/bin/get-iplayer --get "123 456 789 234"
/usr/bin/get-iplayer --get "567 890 345"

If that's true:
printf "%s\n" $tbbox | paste - - - - | while read four; do
    /usr/bin/get-iplayer --get "$four"
done

or
nums=( $tvbox )  # this is now an array
for ((i=0; i < ${#nums[@]}; i+=4)); do
    /usr/bin/get-iplayer --get "${nums[@]:$i:4}"
done

A: As I understand the question. It is about having an input prompt that will be dynamically updated as the digits are entered.
Here is a solution that is based on a small modification of an answer to another question posted on this site almost two years ago.
Take a script that reads each character in stty cbreak mode into a variable called $result and updates the prompt accordingly.
#!/bin/bash

# Input a line with a dynamically updated prompt
# and print it out

ask () {
    n=$1                    # the limit on the input length (<1000)
    if [ -z "$2" ] ; then   # the name of variable to hold the input
       echo "Usage $0: <number> <name>";
       return 2;
    fi
    result="" # temporary variable to hold the partial input
    while $(true); do
        printf '[%03d]> %s' "$n" "$result"
        stty cbreak
        REPLY=$(dd if=/dev/tty bs=1 count=1 2> /dev/null)
        stty -cbreak

        test "$REPLY" == "$(printf '\n')" && {
             printf "\n"
             eval "$2=$result"
             return 0
        }
        test "$REPLY" == "$(printf '\177')" && {
             # On my terminal 0x7F is the erase character
             result=${result:0:-1}
             (( n = $n + 1 ))
             printf "\r\033[K"
             continue
         }

        result="${result}$REPLY"
        (( n = $n - 1 ))
        if [ $n -eq 0 ] ; then
           printf "\n"
           eval "$2=$result"
           return 1
        fi
        printf "\r\033[K" # to clear the line
    done
}

echo "Please input the tv programme numbers to download [max 300 characters]"
ask 300 'tvbox'
echo "$tvbox"
# ... here goes the code to fetch the files ...

This script is half baked since it does not handle cursor movement escape characters correctly as read does. Yet it might put you on track.


text:
Q: Keeping UIButton relative when zooming I have a UIScrollview with a UIImageview inside it showing a floor plan. I also have a UIButton within the scrollview that acts as a marker/pin.
I have implemented zooming with pinching/double tapping on the image, but the UIButton element obviously doesn't move when the image scrolls and/or zooms.
I have tried the following code to try and resposition the button when a zoom is completed:
[myButton setFrame:CGRectMake(
                          (myButton.frame.origin.x - myButton.frame.size.width / 2) * _scrollView.zoomScale,
                          (myButton.frame.origin.y - myButton.frame.size.height / 2) * _scrollView.zoomScale,
                          myButton.frame.size.width, myButton.frame.size.height)];

This moves the button to the top left hand corner.
Has anyone got any idea of what I should be doing to keep the button relative to the image (the same way a marker does on a Google map).

A: I answered a question very similar to this recently. If you don't need realtime updating (only update when a zoom is completed), then you should be able to use the method outlined here.

A: Ok well this was solved by the following:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"Marker.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(640.0, 230.0, 30.0, 46.0);
[button addTarget:self action:@selector(aMethod:)forControlEvents:UIControlEventTouchUpInside];
[self.imageView addSubview: button];
self.imageView.userInteractionEnabled = YES;

Basically by adding the button to the imageView directly and then enabling userInteraction, I was able to get all the functionality needed.


text:
Q: How can I get root permissions with running "sudo su -" instead of "/tools/xgs/bin/sudo su -"? Currently I am running a server on vnc with RHEL 7 operating system.
Background:

*

*I login to the server say kpod@server1

*Now when I need to access root permissions. I use the path /tools/xgs/bin/sudo su -

*Instead of the full path, how can I get root access with only running command sudo?

Note:

*

*/etc/ contains - sudoers.rpmsave

*/etc/ doesn't contain sudoers.d
How can I become root with running only sudo?
Edit: /tools/xgs/bin/sudo is the path where the sudopackage is stored.

A: There are two solutions to this sort of thing:

*

*Add a simple alias to your ~/.bashrc file (or wherever you usually define aliases):
alias sudo=/tools/xgs/bin/sudo

Then log out and log in again (or at least open a new terminal).  The alias should then be active.

*Modify your PATH variable (possibly also in ~/.bashrc) by appending the path where the sudo command lives:
PATH=$PATH:/tools/xgs/bin

This would additionally give you access to all other executables at that path.  The same thing applies here, log out and in again, or at least open a new terminal.
For testing either of these variations before you add them to your shell's startup file, you could just give either of the above commands in an interactive shell.
Also note that sudo su is never really necessary. See e.g. "Is there ever a good reason to run sudo su?"


text:
Q: What is the architecture of a scikit-learn MLPRegressor? I am using a MLPRegressor, and want to make sure I understand the architecture being fit.
Here is the model:
x_train, x_test, y_train, y_test = train_test_split(x_scaled[1:6000], y[1:6000], train_size=0.5, test_size=0.25)

mlp = neural_network.MLPRegressor(hidden_layer_sizes=(100, 20), activation="relu",
                 solver='adam', alpha=0.0001,
                 batch_size='auto', learning_rate="constant",
                 learning_rate_init=0.001,
                 max_iter=1000,tol=1e-4)

mlp.fit(x_train, y_train)
r = mlp.score(x_train, y_train)
y_predict = mlp.predict(x_test)

I want to check my understanding of the architecture here. Are there:

*

*6 units in the input layer if I am using 6 inputs in x?

*2 hidden layers of 1000 and 20 units respectively?

*an output layer with 1 unit?

A: Almost (unless the 1000 units was a typo):

*

*6 inputs in the input layer if the shape of X is (_, 6)

*2 hidden layers with size 100 and 20, respectively

*1 unit in the output layer since this is a regression task

More generally: these are properties that can be inspected using attributes of the neural_network.MLPRegressor object. For example:
from sklearn.neural_network import MLPRegressor
from sklearn.datasets import make_regression

X, y = make_regression(n_samples=1000, n_features=6)

nn = MLPRegressor(hidden_layer_sizes=(100, 20), activation="relu",
                 solver='adam', alpha=0.0001,
                 batch_size='auto', learning_rate="constant",
                 learning_rate_init=0.001,
                 max_iter=1000,tol=1e-4)

nn.fit(X, y)

print(f"Number of inputs:  {nn.n_features_in_}")
print(f"Number of outputs: {nn.n_outputs_}")
print(f"Number of layers:  {nn.n_layers_}")
print(f"Layer sizes: {[l.shape for l in nn.coefs_]}")

Which shows us the number of inputs, outputs, layers, and sizes for coefficients in the hidden layers:
Number of inputs:  6
Number of outputs: 1
Number of layers:  4
Layer sizes: [(6, 100), (100, 20), (20, 1)]


text:
Q: Change the way users are ordered in the users tab https://meta.stackoverflow.com/users
They are ordered by rep, but the way it's done feels very unnatural and it took me a while to understand how it worked. Basically you have to read column by column instead of line by line.
Jon Skeet, at 2x1, is second.. Kyle at 1x2 is 8th.
I think it would be much better if they were ordered so that the first line has the top 5 users, and so on.

aaettkioa
fld eesrt
tlow  ,te
e nrlt ul
rw'iihfny

A: Reading down the list of users is quieter than wading through the mucky mess of rows.
There is a wider, gentler, sense of calming whitespace between the columns than there is between the rows.
The ample sum of relaxation as you scan down affords a breathing channel as you slide down the board of Snakes and Ladders.

A: I don't think so. We are all used to the existing order now.


text:
Q: C# Generics : CS0311 when implementing generic class that meets a generic interface contract I have searched around and found one somewhat relevant answer but, for the life of me, I still cannot figure out where I'm going wrong! I am trying to implement some generically typed tree data structures, using code similar to that below, but I get compiler error CS0311.

error CS0311: The type 'Test.TestType' cannot be used as type parameter 'K' in the generic type or method 'Test.TreeIndex<K>'. There is no implicit reference conversion from 'Test.TestType' to 'Test.IIndexable<Test.TestType>'.

I just can't figure out why the compiler doesn't know how to deal with this so any clues would be much appreciated.
public interface IIndexable<K> where K : IComparable
{
    byte[] ToBytes();
    K FromBytes(byte[] bytes);
}

public class TestType : IIndexable<byte>, IComparable
{
    public int CompareTo(object b)
    {
        return 1;
    }

    public byte[] ToBytes()
    {
        return new byte[1];
    }

    public byte FromBytes(byte[] bytes)
    {
        return 0;
    }
}

public class TreeIndex<K> where K : IComparable, IIndexable<K>
{
    public int SomeMethod(K a, K b)
    {
        return a.CompareTo(b);
    }
}

class Program
{
    static void Main()
    {
        TreeIndex<TestType> treeIndex = new TreeIndex<TestType>(); // CS0311 generated twice here
    }
}

A: Your TreeIndex<K> class requires K implement IIndexable<K>, so TestType should implement IIndexable<TestType> instead of IIndexable<byte>
public class TestType : IIndexable<TestType>, IComparable
{
    public int CompareTo(object b)
    {
        return 1;
    }

    public byte[] ToBytes()
    {
        return new byte[1];
    }

    public TestType FromBytes(byte[] bytes)
    {
        //...
    }
}

You might also want to consider using the generic IComparable<T> constraint on your IIndexable<K> interface i.e.
public interface IIndexable<K> where K : IComparable<K>
{
    byte[] ToBytes();
    K FromBytes(byte[] bytes);
}

A: Since you have the following generic constraint
public class TreeIndex<K> where K : IComparable, IIndexable<K>
And you´re declaring
TreeIndex<TestType>
You're saying that TestType implements IIndexable<TestType>, which cannot be true.

A: You are telling the compiler to make a new TreeIndex<TestType>()
The definition for TreeIndex is TreeIndex<K> where K : IComparable, IIndexable<K> which means that the type you pass for the generic must be of IIndexable<K>.
So when you say: TreeIndex<TestType> then the compiler expects TestType to be of type IIndexable<K>, where K is TestType, so it expects TestType to implement IIndexable<TestType>, which it does not. It implements IIndexable<byte> instead.

It is hard to tell what the best solution would be for your case, but one way to solve it is to specify 2 generics:
// change the TreeIndex definition to take 2 generic types
public class TreeIndex<K, Y>
    where K : IComparable, IIndexable<Y>
    where Y : IComparable

...

// specify both generic types
TreeIndex<TestType, byte> treeIndex = new TreeIndex<TestType, byte>();

A: From Compiler Error CS0311

When a constraint is applied to a generic type parameter, an implicit
  identity or reference conversion must exist from the concrete argument
  to the type of the constraint. To correct this error
Change the argument you are using to create the class.

*

*Change the argument you are using to create the class.

*If you own the class, you can remove the constraint or else do something to enable an implicit reference or identity conversion. For
  example, you can make the second type inherit from the first

Based on that, TreeIndex<K> class have to implement IIndexable<TestType> not IIndexable<byte>.
When you write TreeIndex<TestType> compiler asks for IIndexable<K> which means IIndexable<TestType> on your case.
But your TestType class doesn't implement IIndexable<TestType>. It implements IIndexable<byte>.


text:
Q: how to retrieve selected array object in mongodb I am having mongodb data like this
{
    "_id" : ObjectId("58eb32fb58bbf720a80daf6f"),
    "RoleName" : "Admin",
    "UIList" : [
        {
            "UiName" : "ManageRole",
            "View" : true,
            "Edit" : false,
            "_id" : ObjectId("58eb32fb58bbf720a80daf79")
        },
        {
            "UiName" : "ManageBuildings",
            "View" : false,
            "Edit" : false,
            "_id" : ObjectId("58eb32fb58bbf720a80daf78")
        },
        {
            "UiName" : "ManageFacility",
            "View" : true,
            "Edit" : false,
            "_id" : ObjectId("58eb32fb58bbf720a80daf77")
        }
    ],
    "__v" : 0,
    "Description" : "Full Control",
    "IsActive" : true
}

I want to retrieve only View:true in UIList under UiName:"ManageFacility" 's  how to retrieve that.
I tried to get the data following this query but it retrieve all UIList Under Uiname:,View,Edit  value.
db.getCollection("manage_roles_news").find(
    { _id:ObjectId("58eb32fb58bbf720a80daf6f")},
    {UIList: {$elemMatch: {UiName: "ManageFacility"}}});

How to retrieve that only view in UIlist under Uiname:"ManageFacility"
can anyone tell me

A: I don't think there is way to project individual fields from positional/elemMatch projection. It always resolves to array element.
You can try below aggregation to project field. The below query uses $filter operator to find the matching array values which is piped to $arrayAtElem to return the first element (0) and pass the matching document to $let operator and followed by picking the View property.
db.getCollection("manage_roles_news").aggregate(
  { $match: { _id: ObjectId("58eb32fb58bbf720a80daf6f") } },
  { $project: {
      _id:0,
      View:
      { $let: {
            vars: {
              mElement: {
                $arrayElemAt: [{
                            $filter: {
                                input: "$UIList",
                                as: "fElement",
                                cond: {
                                    $eq: ["$$fElement.UiName", "ManageFacility"]
                                }
                            }
                        }, 0]
                    }
                },
            in: {$cond:["$$mElement.View", 1, 0]}
            }
        }
    }
})


text:
Q: PostgreSQL using pg_trgm slower then full scan I playing with pg_trgm extension and I am confused a bit. Here is the session:
postgres=# create table t(i int, x text);
CREATE TABLE
postgres=# insert into t select i, random()::text from generate_series(1,50000000) as i;
INSERT 0 50000000
postgres=# explain analyze select * from t where x ilike '%666666%';
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..531870.29 rows=12954 width=36) (actual time=131.436..11408.176 rows=432 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   ->  Parallel Seq Scan on t  (cost=0.00..529574.89 rows=5398 width=36) (actual time=108.771..11304.946 rows=144 loops=3)
         Filter: (x ~~* '%666666%'::text)
         Rows Removed by Filter: 16666523
 Planning Time: 0.121 ms
 Execution Time: 11408.279 ms
(8 rows)

postgres=# explain analyze select * from t where x ilike '%666666%';
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..580654.94 rows=5000 width=21) (actual time=124.986..11070.983 rows=432 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   ->  Parallel Seq Scan on t  (cost=0.00..579154.94 rows=2083 width=21) (actual time=72.207..11010.876 rows=144 loops=3)
         Filter: (x ~~* '%666666%'::text)
         Rows Removed by Filter: 16666523
 Planning Time: 0.283 ms
 Execution Time: 11071.065 ms
(8 rows)

postgres=# create index i on t using gin (x gin_trgm_ops);
CREATE INDEX
postgres=# analyze t;
ANALYZE
postgres=# explain analyze select * from t where x ilike '%666666%';
                                                     QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on t  (cost=54.75..18107.93 rows=5000 width=21) (actual time=116.114..26995.773 rows=432 loops=1)
   Recheck Cond: (x ~~* '%666666%'::text)
   Rows Removed by Index Recheck: 36257910
   Heap Blocks: exact=39064 lossy=230594
   ->  Bitmap Index Scan on i  (cost=0.00..53.50 rows=5000 width=0) (actual time=75.363..75.363 rows=592216 loops=1)
         Index Cond: (x ~~* '%666666%'::text)
 Planning Time: 0.389 ms
 Execution Time: 26996.429 ms
(8 rows)

postgres=# explain analyze select * from t where x ilike '%666666%';
                                                     QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on t  (cost=54.75..18107.93 rows=5000 width=21) (actual time=128.859..29231.765 rows=432 loops=1)
   Recheck Cond: (x ~~* '%666666%'::text)
   Rows Removed by Index Recheck: 36257910
   Heap Blocks: exact=39064 lossy=230594
   ->  Bitmap Index Scan on i  (cost=0.00..53.50 rows=5000 width=0) (actual time=79.147..79.147 rows=592216 loops=1)
         Index Cond: (x ~~* '%666666%'::text)
 Planning Time: 0.252 ms
 Execution Time: 29231.945 ms
(8 rows)

As you can see that without index the query is more then two times faster then with index. Just for now there are default PostgreSQL settings (shared buffers, work memory etc)
What I missed?
PS: PostgreSQL 11.5 (Ubuntu 11.5-1.pgdg18.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0, 64-bit
PPS: Using gist index it is even slower.

A: tldr: trigrams may not good at searching for patterns consisting of a single character repeated N times (such as 666666) because there exists only 1 non-terminal trigram and that could have a high occurrence in the search space.
When the gin-index is used, the bitmap of rows is too large to fit in memory, so instead it stores reference to pages, and the database has to perform a further recheck scan over these pages. If the number of rechecked pages is small, the index-use is still beneficial, however with high number of recheck pages the index performs poorly. This is highlighted by the following lines in your explain output
   Recheck Cond: (x ~~* '%666666%'::text)
   Rows Removed by Index Recheck: 36257910
   Heap Blocks: exact=39064 lossy=230594

The issue is particular to your search string, i.e. 666666, with respect to the test data.
if you run select pg_trgm('666666'), you will find:
        show_trgm
-------------------------
 {"  6"," 66","66 ",666}
(1 row)

The first 3 trigrams will not even be generated in an ilike context (correction suggested by user jjanes). Searching on the index yields all pages containing 666. You can validate this by running the explain analyze query with ... ilike '%666%', and obtaining the same Heap Blocks output as above.
if you search with the pattern 123456, you will see it performs much better, because it generates a larger set of trigrams to search against:
              show_trgm
-------------------------------------
 {"  1"," 12",123,234,345,456,"56 "}
(1 row)

On my machine, I get the following:
|------------------------------------|
| pattern | pages rechecked          |
|         | exact | lossy  | total   |
|------------------------------------|
| 123456  |   600 |        |    600  |
| 666666  | 39454 | 230592 | 270046* |
|    666  | 39454 | 230592 | 270046* |
|------------------------------------|
*this is rougly 85% of the total # of pages used for the table 't'

Here's the explain output:
postgres=> explain analyze select * from t where x ~ '123456';
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on t  (cost=90.75..18143.92 rows=5000 width=22) (actual time=110.962..113.509 rows=518 loops=1)
   Recheck Cond: (x ~ '123456'::text)
   Rows Removed by Index Recheck: 83
   Heap Blocks: exact=600
   ->  Bitmap Index Scan on t_x_idx  (cost=0.00..89.50 rows=5000 width=0) (actual time=110.868..110.868 rows=601 loops=1)
         Index Cond: (x ~ '123456'::text)
 Planning time: 0.703 ms
 Execution time: 113.564 ms
(8 rows)

postgres=> explain analyze select * from t where x ~ '666666';
                                                         QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on t  (cost=54.75..18107.92 rows=5000 width=22) (actual time=137.143..18111.609 rows=462 loops=1)
   Recheck Cond: (x ~ '666666'::text)
   Rows Removed by Index Recheck: 36258389
   Heap Blocks: exact=39454 lossy=230592
   ->  Bitmap Index Scan on t_x_idx  (cost=0.00..53.50 rows=5000 width=0) (actual time=105.962..105.962 rows=593708 loops=1)
         Index Cond: (x ~ '666666'::text)
 Planning time: 0.420 ms
 Execution time: 18111.739 ms
(8 rows)

postgres=> explain analyze select * from t where x ~ '666';
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on t  (cost=54.75..18107.92 rows=5000 width=22) (actual time=102.813..17285.086 rows=593708 loops=1)
   Recheck Cond: (x ~ '666'::text)
   Rows Removed by Index Recheck: 35665143
   Heap Blocks: exact=39454 lossy=230592
   ->  Bitmap Index Scan on t_x_idx  (cost=0.00..53.50 rows=5000 width=0) (actual time=96.100..96.100 rows=593708 loops=1)
         Index Cond: (x ~ '666'::text)
 Planning time: 0.500 ms
 Execution time: 17300.440 ms
(8 rows)

A: You already have a great answer which explains why '%666666%' is almost a worst-case scenario for pg_trgm with your sample data.
It is hard to say if this worst-case is a "fair" test or not.  Sometimes the worst case is both inevitable and performance-sensitive. If that is the case for you, then maybe this is a fair test.  On the other hand, worrying about the performance of demonic queries rather than actual ones is often a waste of time.
But there are some things you can do to improve the worst case performance.

Heap Blocks: exact=39064 lossy=230594

The lossy blocks here are horrible for performance.  If you increase "work_mem" until those go away, it will probably close most of the gap between the index and the seq scan, or maybe even reverse it.  And it doesn't take very large settings, in my hands 20MB is enough.  That is a pretty conservative setting on a modern server.
If your table is larger than can be cached in RAM, then you will spend a lot of time reading data from disk.  If that is the case, increasing the setting of "effective_io_concurrency" might also help close the gap between the worst-case use of the index and the seq scan.
Another thing to know is that the seq scan is using 2 parallel workers.  So while it is finishing twice as fast, it might be using 3 times as much resources to do it.  (I don't understand why the index isn't using parallel bitmap scan--I would think it would be eligible)
If you can get the worst-case use of the index to be about the same as seq scan, and the average case to be far better, you have come out way ahead.


text:
Q: Accessing database from a Windows Service I have this ASP.NET app, in which I use Entity Framework to connect to the DB. Inside this app I have a class which provides different operations on the DB (add, remove etc). Everything works dandy. Now I needed to create a Windows Service which once a week updates the DB with info gathered from a repository. I thought that I could add my ASP.NET dll as a reference to my windows service, so that I could use the operations I defined there. But I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid
I read in some other thread that I should copy the connect string to the app.config, but I don't have any app.config file in my windows service project. How can I use the EDM operations I defined in the class in both the ASP app and the windows service?

A: Dude u need to create an app.config in that case . Copy the connection string in the web app to the app.config with the same name. See when the windows service is running and the EF tries to create data context it doesnt find any and hence it shows the error. So u should add one app.config file and add the connectionstring to it appropriately.


text:
Q: Custom toolbar to back press icon and function in fragment android I have created one fragment mybillList.java with mutliple list. After i clicking any item, it will move to mybillDetails.java.
I don't want drawer menu on mybillDetails.java.In this fragment, i need back press icon(with function) instead of drawer menu.

mybillList.java
I have tried getSuppotActionBar().setDisplayHomeAsUpEnabled(true);

mybillDetails.java

A: If you meant closing the activity when clicked back button in action bar, try this
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

if not, add some stuff instead of finish().

A: Try this it will help you...
 mActionBar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnBackPressed();
        }
    });


text:
Q: How to filter out (broken) HTML Tags in ElasticSearch's Highlights? I'm having trouble with the ElasticSearch Grails Plugin,
namely the highlighting Feature.
It is returning text with HTML tags, which would not be a big problem, but it is returning broken, cut-off HTML tags as well.
i.e. "href=google.de> Link <a"
Those can't be easily filtered out with a RegEx.
The solution to this seems to be a custom analyzer like this:
'{
   "index" : {
      "analysis" : {
         "analyzer" : {
            "test_1" : {
               "char_filter" : [
                  "html_strip"
               ],
               "tokenizer" : "standard"
            },
            "test_2" : {
               "filter" : [
                  "standard",
                  "lowercase",
                  "stop",
                  "asciifolding"
               ],
               "char_filter" : [
                  "html_strip"
               ],
               "tokenizer" : "standard"
            }
         }
      }
   }
}'

From HTML Strip in Elastic Search
The question is how do i get the above into the GRAILS elasticsearch plugin ?
(or any other solution for that matter)

A: try to use:
"number_of_fragments": 0
which will return all the content


text:
Q: Correct way to programmatically update constraints when the device orientation changes? I'm using storyboard and autolayout, and setting the constraints in IB as IBOutlet in the corresponding view controller. I'm reading several posts regarding how to update the constraints to be different in portrait and in landscape but I'm still not sure of how should I do this:

*

*Should I set the new constraints in -viewWillTransitionToSize:withTransitionCoordinator: method, or in updateViewConstraints method?

*When the new constraints are set, should I call [self.view setNeedsUpdateConstraints];, or layoutIfNeeded, or setNeedsLayout?

*How should I update, for example, the constant of a certain constraint:
self.myConstraint.constant = 30.0
or doing:
[self.view removeConstraint:self.passwordViewHeight];

self.passwordViewHeight = [NSLayoutConstraint constraintWithItem:self.passwordView
                                                      attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil
                                                      attribute:NSLayoutAttributeNotAnAttribute
                                                     multiplier:1.0
                                                       constant:34.0];

[self.view addConstraint:self.passwordViewHeight];

Thanks in advance

A: Orientation change be detected using the method viewWillTransitionToSize. This method will be called when the device orientation is about to change.
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator (id<UIViewControllerTransitionCoordinator>)coordinator{
      //change constraints
}

Alternatively, if you want to change the constraints after the orientation changes, use the coordinator object's animateAlongsideTransition method in the viewWillTransitionToSize method.
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
    [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        //change constraints
    }];
}

A: The best way would be to change the constant instead of removing the constraint and recreating it again.  Just adding or subtracting from the constant is much faster in the long run as well.  What you would want to do is something like:
[self.view layoutIfNeeded];
self.myConstraint.constant = 30.0;
[self.view layoutIfNeeded];

It is recommended that you call layoutIfNeeded before and after you change the constant as well.  This is because you may have some constraint that has not yet been done and will do so then, before you change more constraints.

A: The best idea will be use Size Classes in Interface Builder to achieve autorotation change.
https://www.codefellows.org/blog/size-classes-with-xcode-6-one-storyboard-for-all-sizes


text:
Q: Decrypting file in Java with pre-existing AES key I am trying to do something pretty simple. I encrypted a file in Windows using AxCrypt. In my Android application, I want to decrypt this file.
The 128bit AES key generated by AxCrypt is
CWTr 45Qg eHhy n23d YPC3 DjRi IxUe bt77 TVzQ NtSh HEc=

I assume this a Base64 encoded string but maybe I'm wrong. I plugged it in to my code below with the spaces but I also tried without the spaces and I get the same result.
The java code to decrypt the file is below. The decryption process starts but errors out with "last block incomplete in decryption" and the resulting file (an mp4 video) cannot be played.
Java code:
       try {
            Utils.logDebug(TAG, "Decrypting!");
            File encfile = new File(getFilesDir() + "/encrypted.axx");
            int read;
            if (!encfile.exists())
                encfile.createNewFile();
            File decfile = new File(getFilesDir() + "/decrypted.mp4");
            if (!decfile.exists())
                decfile.createNewFile();
            FileInputStream encfis = new FileInputStream(encfile);
            FileOutputStream decfos = new FileOutputStream(decfile);
            Cipher decipher = Cipher.getInstance("AES");
            byte key[] = Base64.decode("CWTr 45Qg eHhy n23d YPC3 DjRi IxUe bt77 TVzQ NtSh HEc=", Base64.DEFAULT);
            SecretKey skey = new SecretKeySpec(key, 0, key.length, "AES");
            decipher.init(Cipher.DECRYPT_MODE, skey);
            CipherOutputStream cos = new CipherOutputStream(decfos, decipher);
            while ((read = encfis.read()) != -1) {
                cos.write(read);
                cos.flush();
            }
            cos.close();
            Utils.logDebug(TAG, "Done decrypting!");
        } catch (Exception e) {
            Utils.logError(TAG, "TESTING error: " + e.getMessage());
        }

A: AxCrypt encrypts in CBC mode, as well as compresses, MACs and a number of other details. To decrypt this you'll need to review http://www.axantum.com/AxCrypt/faq.html and their published source code here.
http://www.axantum.com/AxCrypt/SourceCode.html


text:
Q: Terminal screen coordinates in python I'm newbie in using curses lib. I want to make a python program (running in a DOS terminal) that can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there. I tried to call a shellscript from python to do it, but I beleive it may exist a better way for doing it.

A: If all you want to do is rewrite the current line, just print a return char "\r". For example, this prints "ABCdef":
# print 'abcdef' then backup to start of line, then print 'ABC'
# (then print the normal cr/lf that 'print' always does)
print "abcdef\rABC"

(Also helpful to know that you can suppress the cr/lf by ending your print with a trailing comma...)
.


text:
Q: i want to take rdp of linux and when i do print on the Linux i should receive the print on local system I want to have RDP of Linux machine and when i print on Linux i should get print on local system.
I do not want to share the printer on the network. how can I do this if you have any suggestion it will be helpful for me
I tried XRDP, RDESKTOP, FREERDP, VNCSERVER, FLEXIHUB and USB over network


text:
Q: "No smoking allowed" or "No smoking is allowed"? As my opinion, "no smoking is allowed" must be correct , because it's "passive voice" . Then I saw a title on 9gag.com that was "NO penguins allowed". So what grammar point is here?

A: A complete sentence would be "Penguins are not allowed" or its variation "No penguins are allowed".
However, on signs you can often find abbreviated sentences in which the verb is omitted (and often "be" can be implied). Common examples are "(there is) no entrance", "pedestrian crossing (is ahead)", "road (is) blocked".
A sign saying "no penguins" would be unusual (and possibly funny) due to its content, but its syntax is common.

A: Both "No smoking is allowed"  and "No smoking allowed" are incorrect if the implied meaning is "Smoking is not allowed"
Both of these mean Not Smoking is permitted, or smoking is not compulsory.

A: No Smoking Allowed OR No Smoking is Allowed are BOTH wrong.
The sign should read: No Smoking or Smoking is not Permitted.
If "NO" Smoking is Allowed, what about smoking?
The grammar is wrong (similar to a Double-Negative).


text:
Q: Program compiles but I think switch is ignored. I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

//print all the menu options
void print_menu()
{
    cout<<"\nRCNJ Registrar Menu:"<<"\n"
        <<"\n"
        <<"[1] Add a student"<<"\n"
        <<"[2] Display all students"<<"\n"
        <<"[3] Display by year"<<"\n"
        <<"[4] Display statistics"<<"\n"
        <<"[5] Quit"<<"\n";

}

//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
    cout<<"Please enter the sudent's name: ";
    cin >> student_name;
    cout<<"\n";
}

//validate and return gpa
double get_gpa()
{
    double student_gpa = 0;

        cout<<"Please enter the GPA: ";
        cin >>student_gpa;
        cout<<"\n";

            while (student_gpa > 4 || student_gpa < 0)
            {
                cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
                cin >> student_gpa;
                cout<<"\n";
            }

    return student_gpa;
}

//validateand return year
int get_year()
{
    int student_year = 0;

    cout<<"Please enter the year: ";
    cin >> student_year;
    cout<<"\n";

        while (student_year >2016 || student_year <1972)
        {
            cout<<"Please enter a valid year (min 1972, max 2016): ";
            cin >> student_year;
            cout<<"\n";
        }

    return student_year;
}

//generate the student's R#
int generate_number()
{
    int r_number;

        srand (time(NULL));
        r_number = rand() % 89999 + 10000;

    return r_number;
}

//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
    string student_name;
    double student_gpa;
    int student_year;
    int r_number;

    int s_name, s_gpa, s_year, r_num;

    get_name(student_name);
    get_gpa();
    get_year();
    generate_number();

}

//display all students in the proper format
void print_all()
{

}

//get a year as selection and print all students that are the same year
void print_by_year()
{

}

//display statistics based on entered students
void print_statistics()
{

}

//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
    menu_choice = 0;

    cout<<"\n"
        <<"Selection: ";
    cin >> menu_choice;
    cout<<"\n";

        while (menu_choice > 5 || menu_choice< 1)
        {
            cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
            cin>> menu_choice;
            cout<<"\n";
        }

    return menu_choice;
}

int main()
{
    string student_name;
    double student_gpa;
    int student_year;
    int r_number;
    int menu_choice;

    int s_name=0;
    int s_gpa=0;
    int s_year=0;
    int r_num=0;

                string nameArray[42];
            s_name++;

            double gpaArray[42];
            s_gpa++;

            int yearArray[42];
            s_year++;

            int ramapoArray[42];
            r_num++;

        print_menu();
        get_selection(menu_choice);

            switch (menu_choice)
            {
                case 1:
                input_new_student();

                nameArray[s_name] = student_name;
                gpaArray[s_gpa] = student_gpa;
                yearArray[s_year] = student_year;
                ramapoArray[r_num] = r_number;
                break;
            }

return 0;
}

A: I dont have permission to comment, hence adding it here.
In you main(),
        get_selection(menu_choice);
            switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?


text:
Q: gradle: Exclude all - except one file In a gradle build I would like to exclude all files except one. I tried to do it like this:
processResources {

    // exclude everything
    exclude '*.*'

    // except this file
    include 'fileA.xml'
}

..but it does not seem to work - all files are excluded. Is this possible in some way?
Thanks for your help and input.

A: Remove the 'exclude' part, because when you use 'include', you don't have to use 'exclude' patterns - gradle automatically excludes all others.


text:
Q: Downloaded files not launching in Chrome - Why? Strange behavior in Chrome, in OSX Mountain Lion.
After I download a file, it appears in the bottom bar of the browser, normally I can just click on the file and it launches. Or click the small arrow to the right and 'reveal in finder'. However, both of those options are not working anymore. And I can't seem to figure out why.
I've flushed the cache, cookies, etc.. Restarted. And to no avail.
Any idea what may be going on here?

A: Had similar problem. Files were donwloaded in 'Downloads' but when right-clicking on 'Show in Folder' it showed the Desktop.
I did the following to make it work as normal.
In Chrome, go to Preferences, then go to the bottom and click on Advanced, then go to the Download section.

Double check if the path is correct. (if not, then that might have been your problem).
Then set the 'Ask where to save each file before downloading' on On
Go to a website and download and image or go to your Webmail and download an attachment.
Save the file to the right folder (in my case 'Downloads')
Then go back to the settings and set the 'Ask where to save each file before downloading' back to Off
Then the first will still go wrong, but the second and following times it will download it in the correct folder.
Versions:

*

*macOS Mojave 10.14

*Chrome Version 74.0.3729.169 (Official Build) (64-bit)

A: You said you flushed the cache... have you cleared the Download folder (and the download history)?
I've seen issues on Windows where launching downloads progressively becomes slower as the download location and history fill up.

A: Make sure Chrome is up to date and make sure the file has finished downloading before trying to open it.
If neither of these work, try re-installing Chrome and if that fails, just open it with Finder, by default it will be in your download folder.