text:
Q: C++ Program for Checking Correct HTML Tag Using Stack I have been trying to follow an example code on my data structure textbook.
It is a program to check  balance of parenthesis in C++ using a stack but it is not working as expected. Somehow I am having a problem with HTML tag matching algorithm.
#include <iostream>
#include <stack>
#include <vector>
#include <string>
using namespace std;

vector<string> getHtmlTags() {                                      //receives a string of html tags and divide them by "<, >"
    vector<string> tags;                                            //vector of html tags
    while (cin) {                                                   //reads the whole input
        string line;
        getline (cin,line);
        int pos = 0;                                                //current scanning position
        int ts = line.find("<",pos);                                //scans from the current scanning position
        while (ts!=string::npos) {                                  //repeat until end of string
            int te = line.find(">", ts+1);                          //scans for the end of a tag (<)
            tags.push_back(line.substr(ts,te-ts+1));                //save tag to the vector
            pos = te + 1;                                           //repositioning
            ts = line.find("<",pos);
        }
    }
    return tags;                                                    //return vector of tags
}

bool isHtmlMatched(const vector<string>& tags) {                    //checks if the html tags are correctly matched
    stack<string> S;                                            //implememted stack from above for opening tags
    typedef vector<string>::const_iterator Iter;                    //iterate through vector

    for (Iter p = tags.begin(); p != tags.end(); ++p) {
        if (p->at(1) != '/')                                        //is it the opening tag?
            S.push(*p);                                             //push to the stack
        else{
            if (S.empty()) return false;                            //there is nothing to match
            string open = S.top().substr(1);                        //opening tag excluding '<'
            string close = p->substr(2);                            //closing tag excluding '>'
            if (open.compare(close) != 0) return false;             //exception for fail to match
            else S.pop();                                           //pop matched element

        }
    }
    if (S.empty()) return true;                                     //everything has matched correctly - Correct
    else return false;                                              //some did not match correctly - Incorrect
}

int main() {

    int rep;                                                        //decides the number of trial
    cin >> rep;

    for (int i=1; i<=rep; i++) {                                    //loop up to the decided trial
        if(isHtmlMatched(getHtmlTags()))
            cout << "Correct" << endl;
        else cout << "Incorrect" << endl;
    }
}

It runs without a compilation error, but for some reason the console does not respond after I throw a list of HTML tags.
I would like to ask for help for improving these codes. Any ideas are appreciated.

A:
It runs without a compilation error, but for some reason the console does not respond after I throw a list of HTML tags.

It runs for me and it is showing correct output for a couple of test cases I tried.
The input I used was:
1

Did you by any chance forget to input an int before actually entering the html tags?
If not, can you show your input?


text:
Q: Access DynamoDB VPC Endpoint from Lambda running inside VPC I'm having difficulties accessing DynamoDB via VPC End point from my Lambda which is also running in the same VPC. I created a VPC End point for Dynamo and configured Route Table which is in the subnet (whose cidr block say 10.11.0.10/16).
My lambda Security group already have egress rule which will allow accessing that sunet. But still I'm getting timeout. Any help will be really appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FlexSlider Active Image in MainSlide not in SubSlide I have a problem with my carousel. And I'm using Flexslider plugins. If I tried to select different slides and the subslide pop-out, the active slide that I clicked in the main slide is not showing instead the 1st slide only. And, same as subslide when I close it.
I want to:

*

*When SLIDE BOX is displayed, the image clicked in MAIN-SLIDE is displayed in SUB-SLIDE.

*When the SLIDE BOX is closed, the image clicked in SUB-SLIDE is displayed in MAIN-SLIDE.

Please click the codepen for the sample.
Code:
https://codepen.io/venJ7/pen/yLYGvJG
$(function() {
        $('#slider').flexslider({
            directionNav: false,
            controlNav: true,
            animationLoop: false,
            slideshow: false,
        });
        $("#photo_box").hide();
        $("#slider ul li > a").on("click",function(){
                $("#photo_box").slideToggle(200);
                $('body').css({'overflow':'hidden','height':'100vh'});
                $('#carousel').flexslider({
                    animation: "slide",
                    directionNav: false,
                    controlNav: false,
                    animationLoop: false,
                    slideshow: false,
                    itemWidth: 100,
                    itemMargin: 5,
                    asNavFor: '#slider2'
                });
                $('#slider2').flexslider({
                    directionNav: false,
                    controlNav: false,
                    animationLoop: false,
                    slideshow: false,
                    sync: "#carousel",
                    start: function(slider){
                      $('body').removeClass('loading');
                    }
                });
        });
        $(".photo_close").on("click",function(){
                $("#photo_box").hide();
                $('body').css({'overflow':'auto','height':'auto'});
        });
        $("#slider img").on("click", function(e){
            var image_src = $(this).attr('src');
            $('#carousel img').each(function(key,val){
                var sub_img = $(this).attr("src");
                if (sub_img == image_src) {
                    $(this).parent("li").addClass("flex-active-slide");
                    $(this).find("flex-active-slide").click();
                }else{
                    $(this).parent("li").removeClass("flex-active-slide");
                }
            });
        });
    });


text:
Q: How To Improve Performance of SwiftMailer DKIM Signer? We send a Bible Daily Devotion to a large distribution each morning.  I believe the speed of our distribution process is limited by the DKIM Signer associated with Symfony/SwiftMailer. We send the same two part email (html & plain text) to each email address.  Each email is sent to only one email address with unique headers to assist with bounce processing.
Here is the process flow for each email we send:

*

*new \Swift_Message

*setSubject, setBody (html), addPart (plain text), addTextHeaders

*attachSigner for DKIM (Header/Relaxed, Body/Simple)

*send

How can I optimize this sequence to reduce processing time?  I know the DKIM processing is expensive. It would be great if the DKIM Body processing could be done only once as the Body of each email is the same.  The DKIM Header processing would need to be done for each email as the headers change from one email to the next.
What if I structured the code as follows:

*

*new \Swift Message

*setSubject, setBody (html), addPart (plain text)

*attachSigner for DKIM

*foreach email address

*

*delete existing headers

*addTextHeaders

*send

I know this will improve performance some as less code is executed per email.  Is Swift smart enough to know that the content of the email Body did not change?  Is it smart enough to not perform DKIM Body calculations for each email?  If so, this would result is a Big performance improvement that has the potential to improve our email send rate.

A: The problem is that PHP is single threaded.  I divided the email distribution list in half and created two temporary files.  I then ran exec("... &") against each of the two files.  The "&" at the end of the command string starts the command and returns immediately.  The result is two tasks sending half of the email distribution concurrently. I could see the two tasks running at the same time using htop.
This resolved our performance limitation.


text:
Q: J Query Simple Color Picker - use as background color selector I am trying to use the jQuery simple color picker to select and change the background color. I am new to HTML writing and nothing i have found seem to help me with this specific type of color picker. I have experimented with many diffrent color pickers but am unsure how to get the background to respond as well as the display box.
https://jqueryui.com/slider/#colorpicker.
The code i have used from the website below.
<!doctype html>

    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>jQuery UI Slider - Colorpicker</title>
    <link rel='stylesheet' href='https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css'>

<class='ui-widget-content' style='border:0;'>

        Simple Colorpicker

A: To achieve that you only have to replace #swatch with body in the refreshSwatch() function:

$(function() {
          function hexFromRGB(r, g, b) {
            var hex = [
              r.toString(16),
              g.toString(16),
              b.toString(16)
            ];
            $.each(hex, function(nr, val) {
              if (val.length === 1) {
                hex[nr] = '0' + val;
              }
            });
            return hex.join('').toUpperCase();
          }

          function refreshSwatch() {
            var red = $('#red').slider('value'),
              green = $('#green').slider('value'),
              blue = $('#blue').slider('value'),
              hex = hexFromRGB(red, green, blue);
              // $('#swatch').css('background-color', '#' + hex);  <-- replace this
              $('body').css('background-color', '#' + hex);     // <-- with this
          }
          $('#red, #green, #blue').slider({
            orientation: 'horizontal',
            range: 'min',
            max: 255,
            value: 127,
            slide: refreshSwatch,
            change: refreshSwatch
          });
          $('#red').slider('value', 255);
          $('#green').slider('value', 140);
          $('#blue').slider('value', 60);
        });
<!doctype html>

    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>jQuery UI Slider - Colorpicker</title>
    <link rel='stylesheet' href='https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css'>

  <class='ui-widget-content' style='border:0;'>

      Simple Colorpicker


text:
Q: Monomorphisms in the category of perfect groups Let P be the full subcategory of the category of groups (Grp) whose objects are the perfect groups, i.e. those groups for which every element is a product of commutators (but not necessarily itself a commutator). Then it is a well-known fact that P is a coreflective subcategory of Grp.

Does there exist a monomorphism in P that is not an injective function? If so, is there a full characterization of the monomorphisms in P?

In the case of DivAb, the category of divisible abelian groups, one well-known example of a non-injective monomorphism is the quotient map $\mathbb{Q} \twoheadrightarrow \mathbb{Q}/\mathbb{Z}$. In general, the monomorphisms in DivAb are exactly those for which the kernel in Ab, the category of all abelian groups, is reduced (i.e. has no nontrivial divisible subgroups).
Dually, of course, there are also many categories with non-surjective epimorphisms, with one well-known example being the inclusion $\mathbb{Z} \hookrightarrow \mathbb{Q}$ in the category of rings.

A: A morphism $f : G \to H$ is a monomorphism iff the kernel of $f$ in the usual sense has trivial commutator subgroup, or equivalently is abelian. Examples of such monomorphisms which aren't injective are given by suitable central extensions. In particular the universal central extension of a perfect group is again perfect. An explicit example is given by the extension $\widetilde{A}_5 \to A_5$ where $\widetilde{A}_5$ is the binary icosahedral group.


text:
Q: Getting the solver type and step size (for fixed step solvers) we are trying to integrate a simulation model into Simulink as a block. We have a custom continuous block which loads an m file that contains the functions Derivatives, Outputs etc.
My question is: is there a way to find out which solver is used currently and with which parameters? Our model won't be able to support variable time solvers and I would like to give a warning. Similarly, the model requires the fixed step time for initialization.
Thanks in advance.

A: You can get the current solver name using
get_param('modelName', 'SolverName');

Some of the other common solver parameters are
AbsTol
FixedStep
InitialStep
ZcThreshold
ExtrapolationOrder
MaxStep
MinStep
RelTol
SolverMode

You can find other parameters you may wish to query by opening the .mdl file in your favorite text editor and digging through it.

A: If I'm understanding your use case correctly, you are trying to determine the type of solver (and other solver params) for the top-level simulink system containing your block.
I think the following should give you what you want:
get_param(bdroot, 'SolverType');  % //Returns 'Variable-step' or 'Fixed-step'
get_param(bdroot, 'FixedStep');   % //Returns the fixed step size

Notice that for purposes of generality/reusability, this uses bdroot to identify the top-level system (rather than explicitly specifying the name of this system).
If you want to find out more about other model parameters that you can get/set, I would check out this doc.
Additionally, I'm interested to know why it is that your model doesn't support a variable-step solver?


text:
Q: toggling the focus from button to Text box using enter key to which an event is binding

$('#b').on('click', function() {
  $('#in2').focus();
  //setTimeout(function(){ $('#in2').focus(); },500);
});
$('#in2').on('keyup', function(event) {
  console.log(event.which);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="b">focus</button>
<input type="text" id="in1" />
<input type="text" id="in2" />

I have a key up function bound to button where I am shifting my focus to text field #in2 in the above example.
And I also have a key down event bound for text field #in2.
Problem: When I am using the enter key on the button, event bound to the text field(#in2) is getting called.
Can someone suggest me some solution except setTimeout?

A: If I understand your problem correctly and you don't want the function on keyup on #in2 called when Enter is pressed, just check whether the pressed key is enter and only execute it if it isn't?
$('#in2').on('keyup', function(event) {
  if(event.which != 13){
    console.log(event.which);
  }
});

Alternatively you could use onchange so that the function gets called when the content of the element changes (this would also work with copy-and-past for example)


text:
Q: How to read a xml file in android without internet connection? I would be glad if you help me.
I have an app. When I open the app, writing XML file to "sdcard/example.xml". (with internet connection)
But when I open the app without internet connection, the app does not read XML file.
Here is my code;
class RetrieveFeedTask extends AsyncTask<String, Void, String> {

    private Exception exception;

    protected String doInBackground(String... urls) {
        try {
            File xmlWriteSd = new File("/sdcard/example.xml");
            FileOutputStream fos = new FileOutputStream(xmlWriteSd);
            xmlDownload(fos,"http://someExample.com/rss/example.xml");
            xmlRead();
            return null;
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(String feed) {
    }
}

And the xmlDownload function is
public void xmlDownload(FileOutputStream fout, final String urlString) throws MalformedURLException, IOException {
    BufferedInputStream in =null;
    File file = new File("/sdcard/example.xml");
    if(!file.exists())//control
        return;
    try {

        in = new BufferedInputStream(new URL(urlString).openStream());

        final byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1) {
            fout.write(data, 0, count);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
}

and xmlRead function is;
private void xmlRead() {
    try {
        File fXmlFile = new File("/sdcard/example.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("item");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            final ExampleObject  = new YemekNesne();

            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                ExampleObject .setDate(eElement.getElementsByTagName("Date").item(0).getTextContent());
                ExampleObject .setmain(eElement.getElementsByTagName("main").item(0).getTextContent());
                ExampleObject .setsecond(eElement.getElementsByTagName("second").item(0).getTextContent());
                ExampleObject .setextra(eElement.getElementsByTagName("extra").item(0).getTextContent());
                ExampleObject .setExample(eElement.getElementsByTagName("Example").item(0).getTextContent());
                listOfExample.put(ExampleObject .getDate(),ExampleObject );//hash map
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

How can i (ONLY) read xml file without internet?

A: Your approach is logically incorrect.Try implementing this logical procedure.

*

*Check if there is an internet connection available or not.

*If there is a internet connection download , put in SD card and read XML.

*If there is no internet connection, check if the xml is available in SD card or not,if available read xml file.

in your case if there is no internet connection "xmlDownload" will throw exception and will not execute "xmlRead" funciton.

A: It is because when there is no connection, your code :
        try {
        File xmlWriteSd = new File("/sdcard/example.xml");
        FileOutputStream fos = new FileOutputStream(xmlWriteSd);
        xmlDownload(fos,"http://someExample.com/rss/example.xml");
        xmlRead();

Catches an exception on xmlDownload(..); and does not perform the xmlRead();
you can solve this in many ways, I suggest you just put your xmlRead() on a finally and remove the first return like this :
   try {
        File xmlWriteSd = new File("/sdcard/example.xml");
        FileOutputStream fos = new FileOutputStream(xmlWriteSd);
        xmlDownload(fos,"http://someExample.com/rss/example.xml");
        return null;
    } catch (Exception e) {
        this.exception = e;
    } finally {
    try{
    xmlRead();
    } catch (Exception e) {
        this.exception = e;
        return null;
    }
    }

Again this is not the best way to do it, the best way would be to implement a test on connectivity before doing any download or read and see what you want to do based on the result.


text:
Q: Multi level array assignment Here is the example PHP array representation
array(
 "test1" => array(
             "test1subtest1" => array(..)
            ),
 "test2" => array(
             "test2subtest1" => array(..)
            )
 )

So, here is the question: is there any tool in PHP which can be used to assign values to multidimensional array with random depth and index names? It suppose to look like this:
$valuetoassing = "TESTVALUE";
$testarray     = array();
array_assign_multidimensional($testarray, $valuetoassing, array("test1", "test1subtest1", "test1subtest1subtest1"));

Problem is that I do not know what depth the array will have, so I can not code it. Index names are also generated at the run time.
EDIT: I figured that my particular case can be solved using some kind of linked list (stored as array with items that contain actual data and pointer to the index of the next element), but I'm sure I'll meet this problem again in the future so I will not close the question right now.

A: This is pretty easy to do using references.
function array_assign_multidimensional(&$input_array, $value, $list){
        $assignee = &$input_array;
        foreach($list as $key){
                $assignee = &$assignee[$key];
        }
        $assignee = $value;
}

$input = array(
        'firstLayer' => array(
                'secondLayer' => array(
                        'test' => 'old'
                )
        ),
        'randomOutlyingValue' => ''
);

array_assign_multidimensional($input, 'new', array('firstLayer', 'secondLayer', 'test'));

var_dump($input);

/*
array(2) {
  ["firstLayer"]=>
  array(1) {
    ["secondLayer"]=>
    array(1) {
      ["test"]=>
      string(3) "new"
    }
  }
  ["randomOutlyingValue"]=>
  string(0) ""
}
*/


text:
Q: Xml Serialization of ReadOnlyCollections I have some container classes that expose their collections through a ReadOnlyCollection. Custom Methods are provided to Add and Remove from the collection which also perform some custom logic.
For example:
public class Foo
{
    List<Bar> _barList = new List<Bar>();

    public ReadOnlyCollection<Bar> BarList
    {
        get { return _barList.AsReadOnly(); }
    }

    public void AddBar(Bar bar)
    {
        if (bar.Value > 10)
            _barList.Add(bar);
        else
            MessageBox.Show("Cannot add to Foo. The value of Bar is too high");
    }
    public void RemoveBar(Bar bar)
    {
        _barList.Remove(bar);
        // Foo.DoSomeOtherStuff();
    }

}

public class Bar
{
    public string Name { get; set; }
    public int Value { get; set; }
}

This is all well and good but when i come to serialise Foo with the Xml Serializer an exception is thrown.
Can anyone offer a good way of going about this?
Thanks

A: Indeed, that won't work. So don't do that. Additionally, there are no hooks to detect xml serialization except the oh-so-painful IXmlSerializable.
So either:

*

*don't use a read-only collection here

*implement IXmlSerializable (tricky)

*have a dual API (one read-only, one not; serialize the "not" - tricky as XmlSerializer only handles publicx members)

*use a separate DTO for serialization

A: You can't deserialize ReadOnlyCollection because it does not has Add method.
To fix that use a second property for serialization:
[XmlIgnore()]
public ReadOnlyCollection<Bar> BarList
{
    get { return _barList.AsReadOnly(); }
}

[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
//[Obsolete("This is only for serialization process", true)]
[XmlArray("BarList")]
[XmlArrayItem("Bar")]
public List<Bar> XmlBarList
{
    get { return _barList; }
    set { _barList = value; }
}

A: XML Serialization only serializes properties that have a getter and a setter.
You can use the SoapFormatter, BinaryFormatter or  DataContractSerializer.


text:
Q: UIPickerView touch issue in iOS 7 I have an issue with UIPickerView specifically in iOS 7.  I have a picker view with 5 columns. For some columns, when the user touches any item, the PickerView doesn't scrolls to that item. The same issue is found in UIDatePickerView too. Any help is appreciated.

A: This blog post will shed some light on the changes to the pickerViews.
http://blog.ittybittyapps.com/blog/2013/09/20/lifting-the-lid-on-ios-7s-uipicker/
The changes to the picker architecture were significant and if you need to try to fix it, you might have to build your own picker views.
There are a number of projects on github you could use to roll your own, such as AFPickerView, https://github.com/arkichek/AFPickerView (but clearly that's not the iOS7 kind of picker)


text:
Q: Does iOS keychain storage persist when restoring an app to a new device? My question is directly related to this one but is different: iOS: keychain on new devices or on restores.
The poster is curious if you store information in keychain storage, does it get backed up to iTunes and iCloud so that when you restore it to another device the data are persisted.  A partial answer to the OP's own question was:

But now I read that the keychain is only restored if the backup is encrypted in iTunes (don't know about iCloud backups).

The accepted answer was:

You can transfer data using the iCloud, but this is NOT really secure! Save this data ENCRYPTED on your server and let the app read this data would be a solution. Btw. you shouldn't save sensible data unencrypted in the keychain. The keychain can be read really easy after jailbreak.

Is whether the backup is encrypted or not determined by the developer's access to encrypt the data in code or by how the iTunes or iCloud user handles their backups?  The answer to this is very important to me because I am trying to set an initial launch date of an app that determines how long before they have to resubscribe with in-app subscriptions.  This piece of information must be shared between old and new devices and also remain on a single device even if the app is removed for a time period.

A: The following text was from Apple's doc:
Keychain (this includes email account passwords, Wi-Fi passwords, and passwords you enter into websites and some other applications. If you encrypt the backup with iOS 4 and later, you can transfer the keychain information to the new device. With an unencrypted backup, you can restore the keychain only to the same iOS device. If you are restoring to a new device with an unencrypted backup, you will need to enter these passwords again.)


text:
Q: Displaying page Name in the URL instead of page ID in yii? How to display Page Name in the url instead of Page ID
For example, It Should be

localhost/mysite/index.php/page/about

Instead of

localhost/mysite/index.php/page/1

I have tired from edit actionview()
public function actionView($id)
{
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
}

A: You can create links to ANY url that you like. The issue is how you deal with the data that is passed.
So in your view, create a link.
<a href="<?php echo Yii::app()->createUrl('/mycontroller/view/', array('page'=>'about')); ?>">About Us

This will call the controller action actionView(). You can then handle the page in there.
public function actionView($page)
{
   // Load the model with the required page tag.
   $pageDetails = Article::model()->findByAttributes(
       array('page_name' => $page)
   );
   // Display the page
   $this->render('view',array(
       'model'=>$pageDetails
   ));
}

A: Updated Answer
Hope you are making your website SEO friendly with pretty URL. If your pages are static web pages such as about, faq, privacy..., you can implement the above answer provided by crafter. In this case page names should unique.
Another way (but not exactly what you want) is url rewriting with native yii feature urlManager. In this case  page id will appear in URL like bellow.

localhost/mysite/index.php/page/1/about
localhost/mysite/index.php/page/2/britain-to-support-italys-intelligence-effort-on-migrants

If you observe, most of the News website following the same url structure.
Ex: http://www.telegraph.co.uk/finance/economics/11682277/Greeks-admit-they-will-default-at-the-end-of-the-month-as-central-bank-turns-on-government.html
To do this this in application, you have to write urlManager rules.
    'urlManager' => array(
        'urlFormat'=>'path',
        'showScriptName'=>true,
        'rules' => array(
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',

            //We are adding pretty url for article
            'page/<id:\d+>/<title:[a-zA-Z0-9\-_]>' => 'page/view',
        ),

I am assuming bellow is you Article database table
        id     title     description       keywords     status
        -------------------------------------------------------
        1      about     some big text     some keys    active

Now i am making the URl dynamically
        <?php
        //In Controller
        //Fetch articles and send them to view
        $articles=Articles::model()->findAll();
        ?>

        <?php
        //In View
        //Iterate articles
        foreach($articles as $article)
        {
              $id=$article->id;
              $title=$article->title;

              //Make structured Url.
              // Replaces all spaces with hyphens and change text to lowercase .
              $titleInUrl= strtolower(str_replace(' ', '-', $title));

              // Removes special chars.
              $titleInUrl=preg_replace('/[^A-Za-z0-9\-]/', '', $titleInUrl);
              ?>
              <a href="<?=yii::app()->baseUrl;?>/page/<?=$id;?>/<?=$titleInUrl;?>">$title
              <?php

        }
        ?>

You can also change URL pattern as you want. Ex i need url like

localhost/mysite/index.php/page/about-1

For this i have write/change rule in urlManager as
 'page/<title:[a-zA-Z0-9\-_]>-<id:\d+>' => 'page/view',

Hope it will help you for your problem.


text:
Q: AngularJS a directive for input type = number that watches for changes the context: I am developing a mobile version of my app. I want a user to be able to enter numeric fields with their numeric keybord of their phone/tablet. AngularJS makes input fields with type = "number" unreachable for any non-integer data (which is any, because input is a string).

the idea: I want to make a directive that will somehow (using $watch or $parsers or any other ancient sorcery) convert input string to number.

the issue: My directive does not trigger changes of $watch when I type anything in the input field. But when I change scope field from my cotroller $watch is triggered as planed.
controller:
        // code minimized and omitted for clarity
        .controller('carController', ['$scope', function ($scope) {
            $scope.car = {
                power : null,
                // other fields
            }
        }]);

directive
angular.module('numeric', []).directive('numeric', function () {
    return {
        restrict: 'A',
        require: 'ngModel',

        scope: {
            model: '=ngModel'
        },
        link: function (scope, element, attrs, ngModelCtrl) {
            // parsers does not affect anything
            ngModelCtrl.$parsers.push(function(value) {
                return parseInt(value);
            });

            // watcher does not watch
            scope.$watch('model', function(newVal, old) {
                if (typeof newVal == 'string') {
                    scope.car.power = parseInt(newVal);
                }
            }, true);

        }
    };
});

html
    <div ng-controller="carController">
     <input
            ng-model="car.power"
            numeric
            name="power"
            type="number"
            pattern="[0-9]">
       </div>

Here is a fiddle that demonstrates such behavior http://jsfiddle.net/xo94sw7m/1/
the question: what am I missing and how to make directive work as planned?

What I have tried: using $formatters-$parsers,using different approaches to $watch (using scope:false, isolated scope, trying to watch scope changes using attrs and etc), nothing seems to work so far

A: myApp.directive('number', ['$parse', function($parse) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {

            ngModelController.$parsers.push(function(data) {
                return parseInt(data);
            });
            ngModelController.$formatters.push(function(data) {
                if (data) {
                    var model = $parse(attrs['ngModel']);
                    model.assign(scope, parseInt(data));
                }
                return parseInt(data);

            });
        }
    }
}]);

Here is working fiddle


text:
Q: Can not bind Ctrl-o in Bash inside iTerm2 on macOS Sierra I am not able for the life of me to rebind Ctrl-o on iTerm2/Bash.
Here is my stty -a flags for cchars:
cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>;
eol2 = <undef>; erase = ^?; intr = ^C; kill = ^U; lnext = ^V;
min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T;
stop = ^S; susp = ^Z; time = 0; werase = ^W;

Here is my .inputrc:
set bind-tty-special-chars off
Control-o: "> output"

Rebind C-u works though, so the inconsistency is driving me crazy. Would appreciate it if someone could explain why to me.

A: short: the feature applies only to editing characters; discard is not an editing character.
longer: use the source.  There's a table in lib/readline/bind.c which has this entry:

  { "bind-tty-special-chars",   &_rl_bind_stty_chars,           0 },

which assigns the option name to the address of a variable.  The variable is tested a few places in libreadline, ultimately going to this function:

    /* Rebind all of the tty special chars that readline worries about back
       to self-insert.  Call this before saving the current terminal special
       chars with save_tty_chars().  This only works on POSIX termios or termio
       systems. */
    void
    rl_tty_unset_default_bindings (kmap)
         Keymap kmap;
    {
      /* Don't bother before we've saved the tty special chars at least once. */
      if (RL_ISSTATE(RL_STATE_TTYCSAVED) == 0)
        return;

      RESET_SPECIAL (_rl_tty_chars.t_erase);
      RESET_SPECIAL (_rl_tty_chars.t_kill);

    #  if defined (VLNEXT) && defined (TERMIOS_TTY_DRIVER)
      RESET_SPECIAL (_rl_tty_chars.t_lnext);
    #  endif /* VLNEXT && TERMIOS_TTY_DRIVER */

    #  if defined (VWERASE) && defined (TERMIOS_TTY_DRIVER)
      RESET_SPECIAL (_rl_tty_chars.t_werase);
    #  endif /* VWERASE && TERMIOS_TTY_DRIVER */
    }

You can see the stty names used in the structures: erase, kill and lnext.  There's no discard.  bash doesn't set it (or reset it).


text:
Q: CDK - Add policies to role with For each I'm trying to create a Role with some policies, which will differ from lambda to lambda. The ideal scenario would be to have a function where the role and policies are all created and then I'd just call the function and give it the name of the role and the policies I wanted attached, and it would create all of it. So far I have this:
Usage of lambda role creation:
...
    const lambdarole = this.createLambdaRole( 'Test Role', [
      'KMSLambdaPolicy',
      'S3LambdaPolicy',
    ]);
...

Role and policies creation:
  private createLambdaRole(roleName: string, policyName: string[]) {
    const role = new Role(this, 'Role', {
      roleName: roleName,
      assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
      description: 'Role for lambda access',
      managedPolicies: [],
    });

    const kmspolicy = new ManagedPolicy(this, 'KMSLambdaPolicy', {
      managedPolicyName: 'KMSLambdaPolicy',
      statements: [
        new PolicyStatement({
          effect: Effect.ALLOW,
          actions: [
            'kms:Decrypt',
            'kms:GenerateDataKey',
            'kms:DescribeKey'],
        }),
      ],
    });

    const s3policy = new ManagedPolicy(this, 'S3LambdaPolicy', {
      managedPolicyName: 'S3LambdaPolicy',
      statements: [
        new PolicyStatement({
          effect: Effect.ALLOW,
          actions: [
            's3:PutObject',
            's3:GetObject',
            's3:GetObjectAttributes'],
          resources: ['*'],
        }),
      ],
    });

    policyName.forEach(policyName => role.addManagedPolicy(policyName));

    return role;
  }

Currently I can't get it to work, and it gives the following error:

error TS2345: Argument of type 'string' is not assignable to parameter
of type 'IManagedPolicy'.

Is what I want even possible?
Thank you in advance for anyone willing to help!
SOLUTION FOUND
I managed to make it work with the code bellow:
policyName.forEach(policyName => {
  const importedPolicy = ManagedPolicy.fromManagedPolicyName(this, policyName, policyName);
  role.addManagedPolicy(importedPolicy);
});

Note: addManagedPolicy requires a scope, an id and a policy name. Since my policy ID's and names are the same, I just needed to call the array again (hence the this, policyName, policyName).

A: The addManagedPolicy expects an IManagedPolicy object, but you provided a string instead.
    // the managed policy definition is only needed once for your whole account,
    // if you want to reuse it.
    // It has to be unique if you want to map it by name.
    // the following is an example for a customer-managed policy.
    // the attribute `managedPolicyName` is the identifier for the
    // import later on.
    const kmspolicy = new ManagedPolicy(this, 'MP-KMSLambda', {
      managedPolicyName: 'KMSLambdaPolicy'
      // etc.
    });

    // the following role attachment can happen everywhere in your CDK application,
    // e.g. in another construct or stack.
    //
    // The policyNames list need to have the same identifier as in
    // your new ManagedPolicies before.
    const policyNames = ['KMSLambdaPolicy'];
    policyNames.forEach(policyName => {
       const importedPolicy = iam.ManagedPolicy.fromManagedPolicyName(this, `${role.roleName}-${policyName}`, policyName)
       role.addManagedPolicy(importedPolicy)
    });


text:
Q: Apply a text to the first item with a specific class name in all the li's I'm having an unordered list with multiple items, for which I have to apply a text only to the first item with class status.
Currently, the way I tried to do it, replaces the text to all items having the class status.
How should I write the loop to change the text only to the first found item with class status (example: text under Name 1 and text under Name 4 from the snippet below).

var str = document.querySelectorAll(".second-level > .status");
    for(i = 0; i < str.length; i++) {
        str[i].textContent  = "TEST ME";
    }
.name {
  font-weight: bold;
  color: blue;
}
.status {
  color: red;
}
ul {
  display: flex;
  margin-left: 1rem;
}

Name 1

Some text

+000 000 000 000

Name 2

Some text

+000 000 000 000

Name 3

Some text

+000 000 000 000

Name 4

Some text

+000 000 000 000

Name 5

Some text

+000 000 000 000

A: Just use querySelector. It returns the first element that matches the specified selector.

for (let el of document.querySelectorAll(".second-level")) {
  el = el.querySelector(".status");
  if (el != null) el.textContent = "TEST ME";
}
.name {
  font-weight: bold;
  color: blue;
}
.status {
  color: red;
}
ul {
  display: flex;
  margin-left: 1rem;
}

Name 1

Some text

+000 000 000 000

Name 2

Some text

+000 000 000 000

Name 3

Some text

+000 000 000 000

Name 4

Some text

+000 000 000 000

Name 5

Some text

+000 000 000 000

A: If you know that the first child with class .status will occur within the first M children you can use var str = document.querySelectorAll(".second-level .status:nth-child(-n+M)");. see: :nth-child()
For example in the snippet below:
var str = document.querySelectorAll(".second-level .status:nth-child(-n+3)");

var str = document.querySelectorAll(".second-level .status:nth-child(-n+3)");
    for(i = 0; i < str.length; i++) {
        str[i].textContent  = "TEST ME";
    }
.name {
  font-weight: bold;
  color: blue;
}
.status {
  color: red;
}
ul {
  display: flex;
  margin-left: 1rem;
}

Name 1

Some text

+000 000 000 000

Name 2

Some text

+000 000 000 000

Name 3

Some text

+000 000 000 000

Name 4

Some text

+000 000 000 000

Name 5

Some text

+000 000 000 000

A: You can try this:

var nodes = document.querySelectorAll(".second-level > .status");

if (nodes.length) {
  nodes[0].textContent  = "TEST ME";
}
.name {
  font-weight: bold;
  color: blue;
}
.status {
  color: red;
}
ul {
  display: flex;
  margin-left: 1rem;
}

Name 1

Some text

+000 000 000 000

Name 2

Some text

+000 000 000 000

Name 3

Some text

+000 000 000 000

Name 4

Some text

+000 000 000 000

Name 5

Some text

+000 000 000 000


text:
Q: Images over HTTPS endless issues - mixed content I've installed a SSL certificate on my site : https://whiskas.co.za and now I'm getting the mixed content issues, I've tried most of the stuff found on the www but no go :-(

Any help would be appreciated.
Thanks.


text:
Q: Arduino C++: QueueArray does not store String Objects? is there a specific catch with storing Arduino String objects into a QueueArray?
when I try the following code, Arduino just stops executing at "enqueue" function.
QueueArray <String> q;
String s = "blah";
q.enqueue(s);
Serial.println("checkpoint"); delay(1000);
Serial.println(q.peek()); delay(1000);

Same code works for storing integers, and even (char *). what am I missing?

A: by inspecting the headerfile (only template functions, so also source):
http://playground.arduino.cc/uploads/Code/QueueArray.zip
I believe the constructor of the queue gets you into this trouble.
I have had troubles allocating objects in the queue.
I have decided to only put the references in there as a number, and then on the recieving end set that as the address value of a pointer of the object type.
This is btw. a risky strategy!
why not just use enqueue the c_str attribute https://www.arduino.cc/en/Reference/CStr ?

Edit: this answer to a comment would bee too long:
The Arduino is a µProcessor and have a very limited memory (~2K).
(32K for your program, and similar in flash).
Remember that it is also a machine with a limited memory management.
so stack and heaps are both very small, and in general when the heap is used, it can get really fragmented very quickly.
As a C++ programmer that looks at your code, one might expect that the string is in fact stack allocated. (hint: there is no new keyword in there) so even if it internally would hold characters in the heap, this should allow you to assume that the string object would be destroyed when you exit the scope.
(you should also expect that it would clean up after it self, and deallocate the dynamic memory used for characters. Depending on your version of the libraries, this does in fact work, or there is a problem with re-allocate / deallocate, making stuff worse than we need to discuss here..)
learn the difference between heap and stack:
C++ Object Instantiation
you can do something with arduino strings minimize the ehap fragmentation, like reserving memory before doing string operations.
But every time you decide to use a string, you will most likely fragment the heap, especially if you let it stay alive after scope is exited (for use on the other end of the queue).
To avoid the fragmentation issues, (remember it's a small system), you could use enums or similar for predefined messages. However if you insist that you actually need to enqueue a string I have a better suggestion.
You could create a small global array of strings, to hold the strings that will be enquede. (whis will ofcourse limit the queue size, since no more messages can be in the queue, than the array of string objects allow..
This array will be stack allocated, but the characters referenced by each string would be heap allocated.
This allows you to let the reader of the queue clear the string, and thus free memory on the heap.
However as the array never leaves scope, the strings are never automatically deleted by the sender.
You would have to actively clear the string after recieving the string.
For this solution, there will be some constant overhead on the stack.
Alternatively (and in my opinion much better, since fragmentation is non-existing), you could use something like a global character buffer, reserved to allocating messages that is being transferred.
Before enqueueing, append the new message (c-styled null terminated string) after the last one currently in the buffer. The queue should contain the pointer to the message in the char array.
You must always test if there is room in the buffer for the string, before allocating some new message.
The way I do this is by having a global "recieved" pointer, that the worker will update when it reads the message.
It simply moves the pointer to the strings ending null character, when it's done treating it.
The producer will then have another local pointer used for remembering where it wrote the last time it wrote something.
Since the recieved pointer is global, the producer can always calculate the "distance" available between the pointers, and know how many characters can be written to the message buffer..
This is a simple circular buffer, so you need to handle overflowing etc. by adding a read and a write method.


text:
Q: webview_flutter 3.0.0 Problem Cant Solve It ( onWebViewCreated ) the problem
I'm using web view flutter 3.0.0  and it doesn't want to accept any thing for the  (  on Web View Created  ) .. ..
so please if someone can solve ill be thankful

A:   android {
    defaultConfig {
        minSdkVersion 19
    }
}
Using Virtual displays
Set the correct minSdkVersion in android/app/build.gradle (if it was previously lower than 20):

 android {
     defaultConfig {
         minSdkVersion 20
     }
 }
Set WebView.platform = AndroidWebView(); in initState(). For example:

 import 'dart:io';

 import 'package:webview_flutter/webview_flutter.dart';

 class WebViewExample extends StatefulWidget {
   @override
   WebViewExampleState createState() => WebViewExampleState();
 }

 class WebViewExampleState extends State<WebViewExample> {
   @override
   void initState() {
     super.initState();
     // Enable virtual display.
     if (Platform.isAndroid) WebView.platform = AndroidWebView();
   }

   @override
   Widget build(BuildContext context) {
     return WebView(
       initialUrl: 'https://flutter.dev',
     );
   }
 }

A: Remove the const keyword before the WebView widget.


text:
Q: Need help on understanding Razor syntax in a .cshtml page I have got an already developed MVC 4 application and I have to fix some bugs in this project. I am facing a trouble regarding a syntax which are written like this in a .cshtml page . I am not getting any clue for what purpose this syntax is written and I am getting confused with the MVC Viewmodel concept.
@Html.CheckBoxFor(m => m.RemoveImage) @PartnerNet.Resource.Client.ViewModel.RemoveLogo
<img src="@Url.Content("~/Content/Images/" + "no-logo.png")" alt="@PartnerNet.Resource.Client.ViewModel.NoLogo" />

if I refer the dll defination it is showing like this when I am exploring the dll.Please give some ideas.
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Runtime.CompilerServices;

namespace PartnerNet.Resource.Client
{
    [CompilerGenerated]
    [DebuggerNonUserCode]
    [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    public class ViewModel
    {
        public static string Address { get; }
        public static string AdminNotes { get; }
        public static string AlarmsActive { get; }
        public static string AlarmsHistory { get; }
        public static string AlarmStatus_1 { get; }
        public static string AlarmStatus_2 { get; }
        public static string AlarmStatus0 { get; }
        public static string AlarmStatus1 { get; }
        public static string AlarmStatus2 { get; }
        public static string AlarmStatus3 { get; }
        public static string AlarmStatus6 { get; }
        public static string AutoTreatment { get; }
        public static string AutoTreatmentCompletionStatus { get; }
        public static string AutoTreatmentLatest { get; }

A:
@Html.CheckBoxFor(m => m.RemoveImage)@PartnerNet.Resource.Client.ViewModel.RemoveLogo

It says it is creating a checkbox for your current viewmodel with the name called RemoveImage in your view model.
It then adds text from the PartnerNet resource file and then loads the actual image and adds the alt tag again from the resource file.
A resource file is an mvc settings type file where text based values can be stored - example their will be a value store for the removelogo entry.
Hope that helps.


text:
Q: AWS Amplify authorization based on db field value or relationship I am creating a webapp with Amplify ( GraphQL api ) and Quasar Framework.
Using Amazon Cognito for authentication.
Lets say the db has these entities:
A User who has his own profile where he can manage his own data, and even make it public if he turns the 'public' boolean field to true.
An Organization who have todos etc.
A User can become an Employee of one ( or maybe more ) organization(s) and should be able to manage for example the todos that belong to the organization where he became an employee.
I am stuck at figuring out how to add authorization rules to make this happen.
Owner authorization should be suitable for the user profile, but even there its not clear how to setup a rule that makes the profile public if the user sets the 'public' boolean field setting to true in his profile.
For example:
type Todo @model @searchable @auth(rules: [{allow: owner, operations: [read, create, update, delete]}]) {
  id: ID!
  Title: String!
  Description: String
}

This way if a user logs in he can manage and list his own todos, but how can I allow him to view and manage todos that belong to an organization where he is an employee ( employee would be a join table which connects the user and the organization )?

A: I have undertaken some research on this issue, and although it is far from complete, I would like to share it.

*

*Despite amplify docs say, that there is possibility to combine multiple autorization types, they don't specify explicitly, that you can't combine them in one request (my be, it's evident for them, but not for novice like me).

*When you configure your AppSync GraphQL API with amplify update api, you choose default authorization type. All subsequent requests from your front  by await API.graphql() will use this default unless you explicitly specify different type like this await API.graphql(Object.assign(graphqlOperation(listTodos),{authMode: auth_mode})), where auth_mode can take one of next values: "API_KEY", "AWS_IAM", "AMAZON_COGNITO_USER_POOLS" and "OPENID_CONNECT".

*There are two "true" public authorization types in Amplify - "API_KEY" and "AWS_IAM". To activate any of them (or both), you should do something like that:

    type Todo @model
     @auth(rules: [
        { allow: public },
        { allow: public, provider: iam},
        ])
        {
          id: ID!
          name: String!
          description: String
          owner: String
          editors: [String]
          entity: String
        }

*{ allow: public } stands for "API_KEY", { allow: public, provider: iam} - for "AWS_IAM".

*For "API_KEY"to work propery you should configure API KEY (for ex - with amplify update api). For "AWS_IAM" you should configure Cognito and enable unauthenticated identities in Cognito Identity Pool.

*After that, any request without prior user sign-in of the form await API.graphql(Object.assign(graphqlOperation(listTodos),{authMode: auth_mode})) with auth_mode=API_KEY or auth_mode=AWS_IAM will succeed (also updateTodo, createTodo and deleteTodo).

*In either case you can't implement your workflow with public field, enabled by user, "out of the box", because permission evaluation get accomplished prior to any database info gets available. For ex, IAM authorization uses unauthenticated role policy, generated for you by amplify update api. You can see it in your AWS console in IAM service.

*To partially implement your private/public workflow I can suggest to use so called dynamic group authorization(We assume "AMAZON_COGNITO_USER_POOLS" auth mode). In that case you implement "public" group in your Cognito User Pool and make any user member of this group (you can automate this by using post signUp hooks).

*Your @auth could be something like that

    type Todo @model
     @auth(rules: [
        { allow: owner },
        { allow: groups, groupsField: "groupsCanAccess", operations: [read] },
        ])
        {
          id: ID!
          name: String!
          description: String
          owner: String
          editors: [String]
          entity: String
          groupsCanAccess: [String]
        }

*When your user decides that it's time to go public, she request updateTodo with groupsCanAccess set to public. As  you can see, this is partial solution because to read todos your "public" user should be registered.

*To partially implement your employee-organization workflow I could suggest next approach (We again assume "AMAZON_COGNITO_USER_POOLS"):

  type User @model
  @auth( rules: [
  { allow: owner },
  { allow: groups, groupsField: "groupsCanAccess", operations: [read] },
  {allow: groups, groups: ["Admin"] }
      ]) {
      id: ID!
      owner: String! @auth(rules[{allow: groups, groups: ["Admin"] }])
      groupsCanAccess:[String]
      @auth(rules[{allow: owner},{allow: groups, groups: ["Admin"] }])
      todo: [Todo] @connection(keyName: "byUser", fields: ["owner"])

  type Todo @model
   (queries: null)
   @auth ({allow: owner, operations[delete]})
   @key [(name: "byUser", fields: ["owner", "description"])
      {
        id: ID!
        name: String!
        description: String
        owner: String! @auth(rules[{allow: owner}])
      }

*Here everybody can create, update and read Todo, but read operation is possible only through User (queries: null), so nobody can get particular id to update particular Todo except owner. There is though some little possibility that someone can guess this id and it's drawback of this approach. It's impossible to create Todo without owner (exclamation sign on field), and nobody can create Todo but owner (nobody can alter owner field but owner). Note that operations[delete] is important, because without that nobody can query Todo through User ( {allow: owner} equivalent to {allow: owner, operations[create,update,read,delete]}).

*Owner can do everything with User, but she can't create or delete User because she can't alter owner field protected by perfield @auth directive

*Admins can create User and set owner to particular user.

*Admins and owner can alter groupsCanAccess field. Every element in this array corresponds to some organization. When Admins or owner add some organization, every member of this group gains access to this User and to all of her Todos through this User. Drawback - owner can forbid access granted by Admins. Because Todos aren't protected from update - every group member can alter Todos of particular User.

*Operations of adding Cognito User Pool user to group performed by admins and are out of scope of this document. Drawback - only 300 Groups per Cognito Pool.

*And last - you of course have option to manually adjust resolvers, automatically generated by Amplify. You may for ex use "AWS_IAM" and organize owner check by analyzing $context.identity.cognitoIdentityId inside your rezolver mapping template. As you know - there is one-to-one correspondence between this Cognito Identity Pool paramener and user from User Pool. It's especially convinient when you need to store public and owner's Todos (there is some unique per Identity Pool cognitoIdentityId corresponding to unauthenticated user).

A: Have exact the same problem
My hopefully temporarily solution is : Adding a lamdaFunction : myResolver and adding this function to the graqphl-schema. in that function a can do all the filtering thru the databaseClient Class
the schema
 type Query {
  myqueryresolver(params: String): String @function (name: "myqueryresolver-${env}")
}

Now You define a lamda (In my case I use a generic form ....) in which you perform all the non standard queries.
You call this function :
const dataObj = await API.graphql(
    {
      query: myqueryresolver,
      variables:  {"params": JSON.stringify(params)}
    }
  );

All the public access goes thru this function call.
Additional hint
You can run it locally with "amplify mock" and you can see all the output from your console.log locally - no need to deploy during dev.


text:
Q: How do I tell CPAN.pm where to get modules? Here is the complete install command to CPAN and the output:
sudo perl -MCPAN -e "install Bundle::CPAN"
CPAN: Storable loaded ok (v2.13)
Going to read /home/delgreco/.cpan/Metadata
  Database was generated on Mon, 08 Dec 2008 03:27:10 GMT
CPAN: LWP::UserAgent loaded ok (v2.033)
CPAN: Time::HiRes loaded ok (v1.55)
CPAN: YAML loaded ok (v0.39)
Warning: YAML version '0.39' is too low, please upgrade!
I'll continue but problems are *very* likely to happen.
Your urllist is empty! The urllist can be edited. E.g. with 'o conf urllist
push ftp://myurl/'

Could not fetch authors/id/A/AN/ANDK/Bundle-CPAN-1.857.tar.gz
Giving up on '/home/delgreco/.cpan/sources/authors/id/A/AN/ANDK/Bundle-CPAN-1.857.tar.gz'
Note: Current database in memory was generated on Mon, 08 Dec 2008 03:27:10 GMT

        ...propagated at /usr/lib/perl5/5.8.5/CPAN.pm line 3417.

This worked for me, thanks...

cpan> o conf urllist
  http://cpan.yahoo.com/

Of course, the Bundle::CPAN install proceeded to fail on other dependencies, but at least I have a YAML 0.68 now.

A: When you first used the CPAN module, you were asked something along the lines of "Are you ready to proceed with interactive configuration?"  You probably answered "no."  Default configuration options were selected, and so no CPAN repository mirrors were configured for you to pull module tarballs from.
As others have noted, you can configure that option with the o conf urllist command inside the CPAN shell.
My personal preference is to create a "miniCPAN," a local repository that basically contains the latest version of each module (much smaller than pulling ALL of CPAN, which would contain many out of date versions of each module).  To do this, configure a CPAN mirror repository to use temporarily, install the CPAN::Mini module from it, then use the minicpan command-line program which will be installed to create your repository.  Now use o conf urllist pop to remove the CPAN mirror you configured, and o conf urllist push file:///path/to/your/minicpan to tell the CPAN module to install from your local mirror from now on.  You can put the minicpan command in cron to update regularly, or just run it from the command-line whenever you want to refresh.
The format of the minicpan command is
minicpan -l /path/to/your/local/minicpan-repository -r http://example.com/url/of/CPAN/mirror

A: This looks important:

Your urllist is empty! The urllist can be edited. E.g. with 'o conf urllist push ftp://myurl/'

Perhaps run sudo cpan, then o conf init or o conf urllist push http://cpan.yahoo.com/ (for example) to get your urllist straightened out?  Then try to do your installs.

A: At a guess:
sudo perl -MCPAN -e "install YAML"


text:
Q: Nginx uses if to match URL parameters auth_basic           "Administrator's Area";
auth_basic_user_file /www/server/nginx/.passwd;
location / {
    error_page 418 = @418;
    if ($args ~* "user/view/plugins"){
        return 418;
    }
}
location @418{
  auth_basic off;
}

I want to use nginx's if to determine if there are some values in the matching URL parameters, but my PHP code uses a pseudo-static technique. In normal requests, the parameters are directly in the/root background. The same request, different request methods, if cannot match the parameters
enter image description here


text:
Q: Handling MMDDYYYY format in integer format python Code asks user for date in MMDDYYYY format and works fine if they enter a date where both the month and year double digits (example: 11152003 = 2003/11/15) however. if I were to enter 522003 it should print 2003/02/05. I want some guidance that could help me solve this, not allowed to convert to string, or use if statements. Just % and division stuff.
userInput = int(input('Enter the date in the format MMDDYYYY: '))

year = userInput % 10000
userInput = int(userInput/10000)
day = userInput % 100
month = int(userInput/100)

print(f'The reformatted date: {year}/{month}/{day}')

A: 522003 is an invalid entry according to your original criteria, It would be something more like 05022003 which would be received as an int as 5022003.
Furthermore, to resolve this issue where you have one missing number, you can always get the reminder of dividing by 1000000, in this specific case ending up with: 22003, then, you can easily find how to find the year/day. And I believe this should be enough to figure out the rest (use the reminder if you want one side of the date, or the division if you need the other side)


text:
Q: Update changes of an Angular component that has been downgraded to AngularJS and re used in two different places I have an Angular Component that I have downgraded so it can be used in AngularJs. It is used in a pop up modal dialog, The downgrade is successful and the component is functioning as it is supposed to but the only problem is when the modal dialog is closed, these changes are not reflected in the Angular component.
Every time the component runs and also when the model dialog is opened the ngOnInit life cycle is used for async data.
in the application view the component is in angular enviroment and used like so:
<interaction-component [interactionComponentData] = "data"></interaction-component>

in the pop up model dialog it is in angularJS enviroment and used like so:
<interaction-component [interaction-component-data] = "data"></interaction-component>

Say i have an interaction button that when clicked it displays a count in the component's view, when this action is performed and the component is running in Angular it updates the count and when the model dialog is launched - the component is running in AngularJs. Becuase of the ngOnInit - the count will be updated everytime the component runs/re-runs.
Before the model dialog is launched this component has a count of 3. Modal Dialog launches the count is still 3, now i click on the component's interaction button and increment the count to 4. In the dialog I see a count of 4 but when the dialog is closed the same component in Angular still has a like count of 3.
this is what's happening:
AngularJs count 3
Angular count 3
click and increment count in modal dialog to 4
AngularJs count 4
Angular count 3
close model dialog
Angular count 3 ( this count should be 4)
Is it possible for theses changes to keep in synch so when the changes are made in Angular are reflected in AngularJS (vice versa)?

From comments

changes are applied on depending on the toggleClick method which does many things, increments the count, toggles like: true || false. and then communicates with the server and makes a PUT. here is an extract from the method its self:

toggleClick(): void {
    this.interactionComponentData.liked = !this.interactionComponentData.liked;
    this.interactionComponentData.count = this.interactionComponentData.liked ? this.interactionComponentData.count + 1 : this.interactionComponentData.count - 1;
}

then the ngOnIt makes a request to get the changes applied using the toggleClick method.

ngOnInit(): void {
    this.interactionComponentData = post.get({}, {}, endpoint);
    //Other code for DOM use
}

what I am trying to achieve here is when the modal dialog is open, when the button in the interactionComponent is clicked, both of the component are updated. In the modal popup Dialog and outside the modal popup dialog. Please note in the modal dialog the component is downgraded, outside the modal popup dialog it is not.


text:
Q: Can I edit bootstrap modal without using JS/Ajax? I am basically performing CRUD operation, in which I'm adding the data from modal which successfully added as well as fetching successfully but I want to edit there is a problem to get the id. I want to do this without using JS/AJAX, is it possible to edit the record in a bootstrap modal?

list page start, where data fetching from DB

                                Sr#
                                Room Name
                                Status
                                Actions

';
            //-----------------------------------------------------
            $sql    = $conn->query("SELECT * FROM rooms");
            $srno = 0;
            //-----------------------------------------------------
            while($values = mysqli_fetch_array($sql)) {
            //-----------------------------------------------------
            $srno++;
            //-----------------------------------------------------
            echo '

                                '.$srno.'
                                '.$values['room_name'].'
                                ';
                                    if($values['room_status'] == 1)
                                    {
                                        echo'Active';
                                    }
                                    else if($values['room_status'] == 2){
                                        echo'Inactive';
                                    }
                                    echo "id:".$id = $values['room_id'];
                                echo'

                                    <input type="text" name="id" value="'.$values['room_id'].'">

                                        <button class="item" data-toggle="modal" data-target="#update_room" data-id="'.$values['room_id'].'">

                                        </button>

';
                        }
                        echo'

list page end

Modal start, to edit the record
 <?php
    //-----------------------------------------------------
    $sql    = $conn->query("SELECT * FROM rooms WHERE room_id ='".$_GET['id']."'");
    $srno = 0;
    //-----------------------------------------------------
    ($values = mysqli_fetch_array($sql));
    echo'

 Add Room

                    <button type="button" class="close  text-white" data-dismiss="modal" aria-label="Close" >
                        ×
                    </button>

                    <form action="#" class="form-horizontal" id="form" enctype="multipart/form-data" method="post" accept-charset="utf-8">
                        <input type="text" name="room_id" id="room_id" value="id:'.$_GET['id'].'">

                                Room Name *
                                <input type="text" class="form-control" required name="room_name" value="'.$values['room_name'].'"/>

                                Status *

                                    <input type="radio" name="room_status" value="1" ';
                                    if($values['room_status'] == 1)
                                    {echo'checked'; }echo'>
                                    Active

                                    <input type="radio" name="room_status" value="2" '; if($values['room_status'] == 2) {echo'checked'; }echo'>
                                    Inactive

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" name="submit_room">Submit</button>

                </form>

    ';
    ?>

modal end

A: Well, If you don't want to use ajax you have to submit a form to your bootstrap modal data Into a page and get them with get or post method and include them in php.
Like THis:
list page:
<form method="post" action="modal.php">

 <input name="data">

 <button type="submit">submit</buttton>
</form>

modal Page:
//get data from list page
$data = $_POST["data"];
//Your Codes and data in your modal body


text:
Q: Nativescript PhotoSlider Extension / Plugin Is there any plugin or extension for smooth photoslider in nativescript? I tried using swipe direction but I want a smooth sliding effect on photos. Thanks :)

A: Do you want a horizontal slider where the user can slide the images from the side?
If so, a simple ScrollView will do.
<Page>
 <ScrollView orientation="horizontal">
   <Image src="~/image1.png" />
   <Image src="~/image2.png" />
   <Image src="~/image3.png" />
   <Image src="~/image4.png" />
 </ScrollView>
</Page>

Also see the documentation of the ScrollView: https://docs.nativescript.org/ApiReference/ui/scroll-view/HOW-TO.html

A: You can use Gesture for this process
import { SwipeGestureEventData } from "ui/gestures";
export class XXX{
public direction: number;
private images:any[] = ["image url", "image url","image url","image url"];
public current_image;
private image_lenght;
private current_image_count=0;

constructor() {
    this.image_lenght = this.images.length;
    this.current_image = this.images[this.current_image_count];
}

private onSwipe(args: SwipeGestureEventData) {
      direction = args.direction;
    /*left to right direction = 1
    right to left direction = 2
    top to bottom direction = 8
    bottom to top direction = 4*/

    switch (this.direction) {
        case 1:
            if(this.current_image_count != 0)
                this.current_image_count --;
            break;

        case 2:
            if(this.current_image_count < (this.image_lenght) -1)
                this.current_image_count ++;
            break;

        case 4:
            // code...
            break;

        case 8:
            // code.
            break;

        default:
            // code...
            break;
    }

    this.current_image = this.images[this.current_image_count];
  }
}

for more information about gesture in Nativescript angular refer here


text:
Q: Pushsharp send apple notification failed : SSL Stream Failed to Authenticate as Client I trying to send push notification to apple devices using Pushsharp library on ASP.NET MVC project hosted on IIS.
My code :
 public static void SendAppleNotification()
        {
            // Configuration (NOTE: .pfx can also be used here)
            byte[] arr = File.ReadAllBytes("D:\\MySoftware\\pa_Dev.pem");

            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
     arr, "1234");

            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {

                aggregateEx.Handle(ex => {

                    // See what kind of exception it was to further diagnose
                    if (ex is ApnsNotificationException)
                    {
                        var notificationException = (ApnsNotificationException)ex;

                        // Deal with the failed notification
                        var apnsNotification = notificationException.Notification;
                        var statusCode = notificationException.ErrorStatusCode;

                        Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");

                    }
                    else
                    {
                        // Inner exception might hold more useful information like an ApnsConnectionException
                        Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
                    }

                    // Mark it as handled
                    return true;
                });
            };

            apnsBroker.OnNotificationSucceeded += (notification) => {
                Console.WriteLine("Apple Notification Sent!");
            };

            // Start the broker
            apnsBroker.Start();

                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = "660E4433785EFF2B2AA29D5076B039C969F1AADD839D79261328F40B08D26497",
                    Payload = JObject.Parse("{\"aps\":{\"badge\":7}}")
                });

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();

        }

Notes :
1- Tried to change pem extension into p12 and same issue still occurred.
2- I tried to send push notification using https://pushtry.com/ and its working fine so issue not from certification file or password.
The issue inside pushsharp or there is configurations missing must done on my machine, Any one have idea ?

A: This just happened to me as of 23 July, 2019. It looks like Apple is now enforcing TLS 1.2 for the sandbox voip push notification server at
gateway.sandbox.push.apple.com - port 2195
feedback.sandbox.push.apple.com - port 2196

I found that I had to check out the latest code from https://github.com/Redth/PushSharp (master branch), build it, and then manually add a reference to the built DLLs in my project.
Previously I was incuding the NuGet PushSharp package, which is now 3 years old and hasn't been updated. If you look at the recent commits on the master branch there is some change there related to Apple and TLS, so I am certain this has fixed it.

A: My issue fixed by generating p12 file from pem using the below command not by renaming the file extension.
openssl pkcs12 -export -inkey sofwareKey.pem -in software_Prod.pem -out cert_key.p12

see more
https://www.paypal.com/us/selfhelp/article/how-do-i-convert-my-pem-format-certificate-to-pkcs12-as-required-by-the-java-and-.net-sdks-ts1020
may helpful to anyone.

A: i think the issue related to the Push Sharp so please try this solution by changeing the SSl3 to Tls in the class called ApplePushChannel.cs
and here is the change
  The orginal code in the file is
  stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Ssl3, false);

 replace it with

 stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Tls, false);

Hope this will hellp you


text:
Q: Create dynamically table with 3 columns I have array of objects:
var arr = [{id:1, name:Mike },{id:2, name:Tom},{id:3, name:Herman},
           {id:4, name:Ursula},{id:5, name:Sam},{id:6, name:Jenny},
           {id:7, name:Helga},{id:8, name:Nikolas},{id:9, name:Surgen},
           {id:10, name:Jorg}]

I need to generate dynamically table that display items in array above.
The table should contain 3 columns and rows according to the numbers of items in array.
For example, for arr above I want my table to be:

Mike	Tom	Herman

Ursula	Sam	Jenny

Helga	Nikolas	Surgen

Jorg	Empty	Empty

Or if my array is:
var arr = [{id:1, name:Mike },{id:2, name:Sam},{id:3, name:Herman},
           {id:10, name:Jorg},{id:2, name:Tom}] ;

The table is:

Mike	Sam	Herman

Jorg	Tom	Empty

How can I implement tables that has 3 columns and and rows according to the numbers of items in array.

A: Calculate the amount of empty cells by dividing the array length by 3, rounding up, and subtracting the length.
Iterate the array using a for loop up to the length of the array + the empty cells amount, and add a new
 whenever the index % 3 equals 0 (the index is divisible by 3).

var arr = [{"id":1,"name":"Mike"},{"id":2,"name":"Tom"},{"id":3,"name":"Herman"},{"id":4,"name":"Ursula"},{"id":5,"name":"Sam"},{"id":6,"name":"Jenny"},{"id":7,"name":"Helga"},{"id":8,"name":"Nikolas"},{"id":9,"name":"Surgen"},{"id":10,"name":"Jorg"}];

var table = $('
');
var tr;
var empty = Math.ceil(arr.length / 3) * 3 - arr.length;

for(var i = 0; i < arr.length + empty; i++) {
  i % 3 === 0 && (tr = $('
').appendTo(table));

  tr.append('' + (i < arr.length ? arr[i].name : 'empty') + '	');
}

$('#here_table').append(table);
table {
  border-collapse: collapse;
}

td {
  border: 1px solid black;
}

A: Use modulus operator %

var arr = [{id:1, name:"Mike" },{id:2, name:"Tom"},{id:3, name:"Herman"},
           {id:4, name:"Ursula"},{id:5, name:"Sam"},{id:6, name:"Jenny"},
           {id:7, name:"Helga"},{id:8, name:"Nikolas"},{id:9, name:"Surgen"},
           {id:10, name:"Jorg"}];
var str =  "
";
for(var i in arr){
  if(i%3==0)
    str +=  "
";
  str +=  ""+arr[i].name+"	";
  if((i+1)%3==0)
    str +=  "
";

}
str +=  "
";
document.querySelector("#here_table").innerHTML = str;
tr td{
  width:10%;
}

A: Just create a JavaScript function to create that table
Here, I'm using jQuery library to append the element but you can also use JavaScript directly to add the element.

// Object Array
var arr = [
    { id: 1, name: "Mike" },
    { id: 2, name: "Tom" },
    { id: 3, name: "Herman" },
    { id: 4, name: "Ursula" },
    { id: 5, name: "Sam" },
    { id: 6, name: "Jenny" },
    { id: 7, name: "Helga" },
    { id: 8, name: "Nikolas" },
    { id: 9, name: "Surgen" },
    { id: 10, name: "Jorg" }
];

// Generating the table creation HTML code
function createTable(array) {
  var tableString = "

";
  var numOfCells = Math.ceil(arr.length / 3)*3;
  for (var i = 0; i < numOfCells; i++) {
    if (array[i]) {
      tableString += "" + array[i].name + "	";
    } else {
      tableString += "Empty	";
    }
    if ((i + 1) % 3 === 0) {
      tableString += "

";
    }
  }
  tableString += "

";
  return tableString;
}

// Appending that DOM element to the div 'here_table'
$('#here_table').append(createTable(arr));


text:
Q: Debugger say something wrong with outlet My Problem: When I build and run my program in the simulator it instantly crashes.
Debugger says:

"Thread 1: internal ObjC exception breakpoint (-3)

Code Problem: "@IBOutlet weak var Record_Minutes: UIButton!"
import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate,
AVAudioPlayerDelegate {

@IBOutlet weak var TextField_Mintues: UITextField!
@IBOutlet weak var Record_Mintues: UIButton!
@IBOutlet weak var Record_Unlimited2: UIButton!
@IBOutlet weak var playButton: UIButton!


text:
Q: Theme save png Access Denied I am using codenameone on windows 10 as aplugin on netbeans 8.2 .
I cannot save png image as simple Image with error access denied. I can save only as multiimage.
I would like to save it as simple image because of the smaller size of the application.
Do I have to setup something?
After Shai Almog suggestion I am posting the screehshot of the error

 and the the output of command line tool:
java.io.FileNotFoundException: res\theme\eiep-logo.png (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at com.codename1.ui.util.EditableResources.writeToFile(EditableResources.java:865)
    at com.codename1.ui.util.EditableResources.saveXMLFile(EditableResources.java:955)
    at com.codename1.ui.util.EditableResources.saveXML(EditableResources.java:1474)
    at com.codename1.designer.ResourceEditorView$SaveResourceFileAction.exectute(ResourceEditorView.java:4355)
    at com.codename1.ui.resource.util.BlockingAction.run(BlockingAction.java:88)
    at java.lang.Thread.run(Unknown Source)

A: You can uncheck the XML Team Mode option in the File menu of the designer tool to workaround this.
The question is why is that file missing from the directory, did you remove/prune files from that directory?


text:
Q: How run pre-trained darknet yolov4 model using python script? I am developing a napari plugin in Python language. This plugin makes a object detection using darknet Yolov4. Before making a napari plugin, I started to write a notebook which making inference. My environment is windows 10.
I followed instruction in this website. But, my problem is focused on this command :
Folder_darknet='C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/darknet/'

os.chdir(Folder_darknet)

!chmod +x ./darknet

!./darknet detector test "C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/obj.data" "C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/yolov4-tiny-test.cfg" "C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/backup/yolov4-tiny-train_best.weights" -thresh 0.20 -dont_show -out "C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/Prediction.csv" < "C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/test.txt"

I used subprocess python library to run windows command line but I can't handle it :

No command is recognized as an internal or external command

Here the code :
Folder_darknet='C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/darknet/'

os.chdir(Folder_darknet)

subprocess.run([".\darknet","detector","test","C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/obj.data","C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/yolov4-tiny-test.cfg","C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/backup/yolov4-tiny-train_best.weights","-thresh","0.20","-dont_show","-out","C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/Prediction.csv","<","C:/Users/User/OneDrive - Université de Bourgogne/Documents/Stage/yolo/main_folder/Model_ALL_views/test.txt"],shell=True)

You can find the full code in my notebook
Is it a good idea to use subprocess to execute the darknet command ?
Kindly help me, I will be highly grateful to all of you.
Thanks you for your support.
Best,


text:
Q: AppController alternative for Cocos2d 3.0 Here is my Cocos2d 2.0 calls. What's alternative for this in Cocos2d 3.0
    AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];

    [[app navController] presentModalViewController:achivementViewController animated:YES];

A: In Cocos2d 3.0, use CCAppDelegate instead of AppController:
CCAppDelegate *app = (CCAppDelegate*) [[UIApplication sharedApplication] delegate];

[[app navController] presentModalViewController:achivementViewController animated:YES];

A: AppController is again renamed to AppDelegate:
#import "AppDelegate.h"

AppDelegate * app = (((AppDelegate*) [UIApplication sharedApplication].delegate));

[[app navController] presentModalViewController:achivementViewController animated:YES];


text:
Q: MediaElement in a ResourceDictionary Windows 8 Metro App I'm creating a windows 8 metro styled app for the windows store.
I've got a resource dictionary (which has "code behind") which is merged in app.xaml as
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <view:TemplatesDictionary />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

I'm using the dictionary to access templates/color brushes and swap them out during runtime based on properties/states changing.
return App.Current.Resources["SomeKey"] as Windows.UI.Xaml.Media.SolidColorBrush;

or whichever type I need.
This has been working fine with pretty much anything so far, however I've run into issues when trying to do the same thing with MediaElements.
I've got
<MediaElement x:Key="SFX_ButtonSound" AutoPlay="False" Source="ms-appx:///Assets/Sound/UI Click Random.wav" Volume="1" />

then in code I've tried
(App.Current.Resources["SFX_ButtonSound"] as MediaElement).Play();

and nothing plays but it can access and find the key fine.
However, if I copy paste the media element into a page, changed x:key to x:name then
SFX_ButtonSound.Play();

It will play fine, can someone explain to me why this occurs? I'm assuming it doesn't function because an instance of the media element on the page hasn't been "created" or something like that.
I've not done much WPF/Silver-light development/UI dev. I mainly focus in just backend dev.
Edit: So in case anyone was wondering, the reason why I attempted to approach it this way was so that i could, in code, manage whether or not volume was muted via in-app control as well as other various things and so that everything could be in one centralized "place" and so in code, when needed, i could simply call something like
Media.PlaySFX(string)

and it would apply the current settings/variables I needed at the time. What i ended up doing to achieve this was create a User control which simply contained all my generic media elements (button clicks, ambient sounds, etc).
Then in each of my pages which required the sounds, I just created the control in the .resources area.
For the C# file for the user control it has a few functions to just play/stop/test logic.

A: I believe a MediaElement needs to be a part of visual tree to work, so indeed you need to add it somewhere. Maybe a Popup would work?


text:
Q: Sublime Text Vertical Line Highlighter In the good ol' Notepad++ days, I had this luxury of Bracket Highlighting, in which even the grey vertical lines connecting the brackets used to change to Red (or get highlighted), giving me a good view of the whole block.
Is there a way to have that in Sublime Text 3 ?

A: There is a way to do this using BracketHighlighter. More recent releases have the "content_highlight_bar" and "align_content_highlight_bar" settings, which allow you to have a vertical line connecting your paired brackets. You'll need to have configured your highlight styles so that brackets are marked with a unique color.
It's worth reading through the entire BracketHighlighter README as well as all the settings in Preferences -> Package Settings -> Bracket Highlighter -> Bracket Settings-Default to see what's possible. You'll need to play with your color scheme if you want to add BracketHighlighter-specific settings, but that's not too hard if you use the tmTheme Editor.


text:
Q: App crashing when adding getCheckedRadioButtonId() I have a navigation activity made up of fragments, and I have a button that is attached to an onClickListener, which runs the onClick method. The app opens normally and so does the fragment, but whenever I click the button, the app crashes
public class FirstFragment extends Fragment implements View.OnClickListener {

View myView;

private RadioGroup radioGroup;
private Button btnDisplay;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.first_layout, container, false);
    btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);
    return myView;
}

@Override
public void onClick(View v) {
    radioGroup = (RadioGroup) v.findViewById(R.id.radio);

    int selectedId = radioGroup.getCheckedRadioButtonId();
    }
}

Through some testing, I found that this line was causing an issue. I need this line because I want to pass selectedId into a radiobutton
int selectedId = radioGroup.getCheckedRadioButtonId();

Without this line, the app and fragment open normally, and the app doesn't crash when the button is clicked, I added a toast, and it worked fine without the line of code above. Could anyone explain how to fix this? Thank you

A: Put this line in onCreateview
radioGroup = (RadioGroup) v.findViewById(R.id.radio);

Like this
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.first_layout, container, false);
     radioGroup = (RadioGroup) myView .findViewById(R.id.radio);
    btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);
    return myView;
}

A: find your RadioGroup not in view that was clicked but in root view of the fragment, so this line:
radioGroup = (RadioGroup) v.findViewById(R.id.radio);

change to this:
radioGroup = (RadioGroup) myView.findViewById(R.id.radio);

hope it helps...


text:
Q: How to get gateway address on Android I use this code to get gateway:
DhcpInfo d;
WifiManager wifii;
wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE);
d=wifii.getDhcpInfo();
int gatewayip = d.gateway;

It works now, but DhcpInfo is deprecated as of API level 18.
Is there any other way to get the gateway address?

A: It suggests the use of ConnectivityManager.getLinkProperties as follows:
LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);

But, when I try to find more info about LinkProperties class, it is not available officially:
Anyway I found the following codes from here: http://ics-custom-settings.googlecode.com/git-history/65f22c5e653e1ee9767572d3ca938f9a1217801d/src/com/android/settings/Utils.java
/**
 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
 * @param context the application context
 * @return the formatted and comma-separated IP addresses, or null if none.
 */
public static String getWifiIpAddresses(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
    return formatIpAddresses(prop);
}

/**
 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
 * addresses.
 * @param context the application context
 * @return the formatted and comma-separated IP addresses, or null if none.
 */
public static String getDefaultIpAddresses(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    LinkProperties prop = cm.getActiveLinkProperties();
    return formatIpAddresses(prop);
}

private static String formatIpAddresses(LinkProperties prop) {
    if (prop == null) return null;
    Iterator<InetAddress> iter = prop.getAddresses().iterator();
    // If there are no entries, return null
    if (!iter.hasNext()) return null;
    // Concatenate all available addresses, comma separated
    String addresses = "";
    while (iter.hasNext()) {
        addresses += iter.next().getHostAddress();
        if (iter.hasNext()) addresses += ", ";
    }
    return addresses;
}

Update!
Ok, I found LinkProperties class over here http://developer.oesf.biz/em/developer/reference/eggplant/android/net/LinkProperties.html


text:
Q: How can I return multiple results from a single LinQ to SQL expression in one round-trip? I'm rewriting an ancient piece of code that I've inherited and I'm looking at a query that performs a massive join on large tables, and then does a series of grouping actions on the resulting table to "distill out" data:
INSERT INTO #teh_temp_table
SELECT * FROM teh_large_table
INNER JOIN teh_other_large_table

SELECT customer_id, customer_name FROM * #teh_temp_table
GROUP BY customer_id, customer_name
ORDER BY customer_name

SELECT city_id, city_name FROM * #teh_temp_table
GROUP BY city_id, city_name
ORDER BY city_name

-- repeated n-2 times ...

This large SQL statement is sent to the DB server with a ADO.NET SqlCommand, and the data is returned as n separate results in one network round trip.
I'm having difficulties translating this to LinQ to SQL. I've been attempting to do something similar to:
from tlt in teh_large_table
join tolt in teh_other_large_table on tlt.pkey equals tolt.fkey into teh_temp_table

from tmp in teh_temp_Table
group tmp by new { tmp.customer_id, tmp.customer_name } into customers

from tmp in teh_temp_table
group tmp by new { tmp.city_id, tmp.city_name } into cities

select new { customers, cities }

but the compiler complains. Is there a way to issue an equivalent LinQ query that not only retrieves the data but also returns it, in a single network round-trip? As you can imagine, I don't want to perform that big nasty join more than once.

A: Other than trying to force distinct on the result sets, I'm not seeing the advantage of using the Group operation here. Since LINQ to SQL can't return multiple results from LINQ, you could push them into a your temp table and then group the results based on some type. Would the following work for you:
var bigTable = from large in teh_large_table
               from other in teh_other_large_table
               select new { ??? }; // TODO: Supply needed columns here

var kvPairs = from customer in bigTable
              select new {Id = customer.Customer_id, Name = customer.Customer_name, Type="Customer"}
              .Union(
              from city in teh_temp_table
              select new {Id = city.City_id, Name = city.City_name, Type="City"}
              ).Distinct();

var groupedKvPairs = from pair in kvPairs
                     group pair by pair.Type into grouped
                     select new {pairType = key,
                                 vals = from row in grouped
                                        orderby row.Name
                                        select new { row.Id, row.Name}};

As an alternative, you could also set up a Stored Proc returning multiple results and then use the IMultipleResults interface to consume them. See http://www.thinqlinq.com/Default/Using-LINQ-to-SQL-to-return-Multiple-Results.aspx


text:
Q: Excel: How to group by Number and search for occurrence I want to count the occurrence of different Values grouped by a Reference#.
Given is the Excel below. The functions should search for same Reference# at column A.
Count the distinct values in column B and the Result should written in Column C.
How can I achive this functionallity ?
|-----A------|-------B-----|-------C------|
|Reference   |   Value     |   Result     |
|------------|-------------|--------------|
|1           |0815         |1             |
|1           |0815         |1             |
|1           |0815         |1             |
|2           |0816         |2             |
|2           |0817         |2             |
|2           |0817         |2             |
|3           |2020         |3             |
|3           |2021         |3             |
|3           |2022         |3             |
|-----------------------------------------|

A: If you want to count unique numeric values, then try in C2:
=SUM(--(FREQUENCY(IF(A$2:A$10=A2,B$2:B$10),B$2:B$10)>0))

Note: Enter through CtrlShiftEnter
More info here
If they are text values then:
=SUM(--(FREQUENCY(IF(A$2:A$10=A2,MATCH(B$2:B$10,B$2:B$10,0)),ROW(B$2:B$10)+1)>0))

Note: Enter through CtrlShiftEnter
More info here

If one has Excel O365:
=COUNT(UNIQUE(FILTER(B$2:B$10,A$2:A$10=A2)))

More info here

A: Use INDEX/MATCH to bring the number if match is found, if not add 1 to the max:
=IFERROR(INDEX($C$1:C1,MATCH(A2,$A$1:A1,0)),MAX($C$1:C1)+1)


text:
Q: Generators of the cyclic group ${\mathbb{Z}_p^*}$ Given two prime numbers ${p, q > 2}$, where ${p=2q+1}$, I have to show that the cyclic group ${G = \mathbb{Z}_p^*}$ has ${p-1}$ generators.
I know that ${|G| = p-1 = 2q}$ and that ${a \in G}$ is a generator iff ${a^2 \neq 1~\text{mod}~p}$ and ${a^q \neq 1~\text{mod}~p}$. So there have to be ${2q}$ solutions for these two equations, but I have no idea how to show that.
Can you give me a hint?

A: How many generators does a cyclic group of order $n$ have? What is the order of $({\bf Z}/p{\bf Z})^\times$?


text:
Q: Android loading 32 and 64 bit .so files Currently i have this setup.
../amreabi
...lib1.so
...lib2.so

../armeabi-v7a
...lib1.so

../armeabi-v8a
...lib1.so

../mips64
...lib1.so

../mips64
...lib1.so

../x86
...lib1.so

../x86_64
...lib1.so

The problem is that when i try to use .loadLibrary("2")) on a lets say 64 bit device (so armeabi-v8a), Android can't resolve it, because technically there's a "/armeabi-v8a" folder, but no "lib2.so" library inside.
So i'm wondering, how can i resolve this?
Edit1: Just an FYI, when you call System.loadLibrary("2") on a 64 bit device, but you only have a 32 bit library, Android will look for that 32 bit library and try to use it as a backup. So if i remove lib1.so, System.loadLibrary("2") will work perfectly fine.
Edit2: if i put lib2.so into a 64 bit folder, Android will throw an exception saying the library is 32bit compiled.


text:
Q: Guidance on creating a widget I would like to display some values into a widget in a similar way as the mechanical counters in a power meter. I have so far only  written a function to split the total value into a single digit corresponding to the required position, it looks something like this:
    unsigned long value; // variable holding the value to be displayed

    ....... get the actual value

    int firstPosition  = value % 10;             // 0-9
    int secondPosition = int(value*0.1) % 10;    // 0 - 9 * 10
    int thirdPosition  = int(value*0.01) % 10;   // 0 - 9 * 100
    int fourthPosition = int(value*0.001) % 10;  // 0 - 9 * 1000
    int fifthPosition  = int(value*0.0001) % 10; // 0 - 9 * 10000

Now the actual question, how can I perform the actual animation in order to get a similar behaviour as in a physical device? Has anybody done something similar?
Please note that I am using Qt libraries, just in case it makes a difference.
Cheers.

A: See the analog clock tutorial at http://qt-project.org/doc/qt-5.0/qtwidgets/widgets-analogclock.html
A one second timer is used to animate the clock, by calling update().
During the paintEvent() the widget is drawn for the current time.


text:
Q: Powershell: need assistance with output if item is not found I have a script that searches a csv file and returns a Payrol Dept Number based on a user inputting the employee First and Last name. I want to be able to tell the user that no name matches their query if the First and Last name does not return a result. I've tried different if/else statements but have not gotten it to work. Here is what I have:
$csv = import-csv c:\employees.csv
$First = read-host 'What is the users first name?'
$Last = read-host 'What is the users last name?'
$csv | Where-Object { $_.last -eq $Last -and $_.'First Name' -eq $First } |
Select-Object -Expand 'Payroll Department Number'

A: Save the result from Where-Object to a variable and check if it's empty. Ex:
$csv = import-csv c:\employees.csv
$First = read-host 'What is the users first name?'
$Last = read-host 'What is the users last name?'
$res = $csv | Where-Object { $_.last -eq $Last -and $_.'First Name' -eq $First }

if($res) { $res | Select-Object -Expand 'Payroll Department Number' }
else { Write-Host "User does not exist" }