text:
Q: Converting Numbers from Western Arabic Digits "1,2,3..." to Eastern Arabic Digits "١, ٢, ٣...."  I need to convert date stored in database into Hijri and display the same in Arabic
I used the Culture to convert the date which it does but it still display date as English numbers
Example
Gregorian Date = 19/01/2012
Its equivalent date in Hirji is 25/02/1433
Following code snippet converts but displays same as  25/02/1433 While i want it in Arabic numbers something like ٢٥/٠٢/٢٠١٢"
string sDate
DateTime dtt = Convert.ToDateTime("19/01/2012");
CultureInfo ci = new CultureInfo("ar-SA");
sDdate = dtt.ToString("d", ci);

Is there a was it converts date to Hijri and display same as Arabic
I need this for a web project which i am developing in ASP.NET c#

A: you should convert the HijriDate to a string, assume its name is stringHijriDate. Then use a function like below to convert its digits to arabic digit:
  public static string ToArabicNumber(this string inputString)
    {
        string[] arabicDigits = CultureInfo.GetCultureInfo("fa-IR").NumberFormat.NativeDigits;
        var arabicNumberBuilder = new StringBuilder();
        foreach (char c in inputString)
        {
            if (char.IsDigit(c))
                arabicNumberBuilder.Append(arabicDigits[int.Parse(c.ToString())]);
            else
                arabicNumberBuilder.Append(c);
        }
        return arabicNumberBuilder.ToString();
    }

the result string will be something like '٢٥/٠٢/٢٠١٢'

A: The CultureInfo class will not help you in either parsing or formatting the numbers to eastern Arabic ("٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩") nor to western Arabic ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"). You have to manually convert it, Here is a little function which will do that for you in a neat way:
public string ConvertToEasternArabicNumerals(string input)
    {
        System.Text.UTF8Encoding utf8Encoder = new UTF8Encoding();
        System.Text.Decoder utf8Decoder = utf8Encoder.GetDecoder();
        System.Text.StringBuilder convertedChars = new System.Text.StringBuilder();
        char[] convertedChar = new char[1];
        byte[] bytes = new byte[] { 217, 160 };
        char[] inputCharArray = input.ToCharArray();
        foreach (char c in inputCharArray)
        {
            if (char.IsDigit(c))
            {
                bytes[1] = Convert.ToByte(160 + char.GetNumericValue(c));
                utf8Decoder.GetChars(bytes, 0, 2, convertedChar, 0);
                convertedChars.Append(convertedChar[0]);
            }
            else
            {
                convertedChars.Append(c);
            }
        }
        return convertedChars.ToString();
    }

Now alter your code a little to look like this:
string sDate
DateTime dtt = Convert.ToDateTime("19/01/2012");
CultureInfo ci = new CultureInfo("ar-SA");
sDate = ConvertToEasternArabicNumerals(dtt.ToString("dd/MM/yyyy", ci));

And things will work just fine.
BTW, the code for the function was taken from here.

A: I use DigitSubstitution to switch between Hindi(called Arabic sometimes) numbers and English numbers :
bool UseHindiNumbers;
//...
if (UseHindiNumbers)
  Thread.CurrentThread.CurrentCulture.NumberFormat.DigitSubstitution = DigitShapes.NativeNational;
else
  Thread.CurrentThread.CurrentCulture.NumberFormat.DigitSubstitution = DigitShapes.None;

A: you will need to set page's UI culture to arabic

A: Private Function DigitContext(ByVal Vl As String) As String
    Dim ks As String
    Dim c As Integer
    Dim t As Integer
    ks = "" 'reset the returned string
    For t = 1 To Vl.Length
        c = AscW(Vl.Substring(t - 1, 1))
        Select Case c
            Case &H30 To &H39
                ks = ks & ChrW(c + &H630)
            Case 46
                ks = ks & ChrW(1548) '&H060C 'ks = ks & ","
            Case Else
                ks = ks & Mid(Vl, t, 1)
        End Select
    Next
    Return ks

End Function


text:
Q: Error: Couldn't lookup symbols when calling an stl method in LLDB When I wanted to alter the execution of the program I am debugging by resizing a vector, but I got an error:
(lldb) expression std_vector_foo.resize(1)
error: Couldn't lookup symbols:
  std::vector<string_id<mtype>, std::allocator<string_id<mtype> > >::resize(unsigned long)

Strangely enough the following runs fine:
expression std_vector_foo.reserve(1)

A: There are two ways to work around the absence of template methods that you want to call.
The most straightforward - if it works for you - is to turn on building the "stl module" for use in the expression parser by putting:
settings set target.import-std-module true

in your ~/.lldbinit.  This will cause lldb to build a "clang module" for the stl libraries, from which lldb can build needed specializations on demand.  This is, however, a fairly new feature, and was quite tricky to get working, so YMMV...  I don't know if the GNU STL is modularizable, so it may only work with a recent version of the clang STL.  ""Modules" turns out to be a highly overloaded term; in this context it means the clang feature:
https://clang.llvm.org/docs/Modules.html
If you do find problems with this, please file bugs with http://bugs.llvm.org.
The brute force way to make these methods available if this doesn't work is to put the equivalent of:
template class std::vector<string_id<mtype>>;

for whatever type you were trying to access the methods of into one of your source files.  That forces the compiler to emit a complete version of this class specialization, leaving you with methods you can call.  Of course, this will also bloat your code and you have to do it specialization by specialization, so it isn't a general solution.  Still, it's a useful trick to keep in your back pocket.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binding from integer number of days to the WPF UserControl showing both value and unit (Day, Week, Month) In our WPF application which follows MVVM pattern, there is one property in the ViewModel, which is an integer value representing the number of days. And we would like to present this value in such pattern in WPF: it should contain one TextBox and one ComboBox, where the text in TextBox represents the values of the time and the value in ComboBox represents the unit. For example, property value 5 will show as [5][Day], while value 14 shows as [2][Week]. This should be a two-way binding since we want the user to modify it too. Of course such mapping is not one-to-one, 14 can also be represented to [14][Day]. But the principle is the bigger unit has higher priority.
Now weirdly I don't even know what to start with, especially when I want to follow MVVM. Because I only have one value which binds to to destination. And since it is such a simple value, there is no point to create a class as the DataContext of such UserControl
Anyone can give me some hint? Thanks!

A: All this work should be done in ViewModel, make the initial integer property private, add two new properties UnitsCount and UnitsType.
private UnitsTypeEnum unitsType = UnitsTypeEnum.Days;
private int unitsCount = 0;

public int UnitsCount
{
    get { return unitsCount; }
    set
    {
        /* set the number of days based on this new value and UnitsType */
        unitsCount = value;
        NotifyPropertyChanged("UnitsCount");
    }
}

public UnitsTypeEnum UnitsType
{
    get { return unitsType; }
    set
    {
        /* set the number of days based on this new value and UnitsCount */
        unitsType = value;
        NotifyPropertyChanged("UnitsType");
    }
}

Now make sure in constructor you initialize correctly the UnitsCount and UnitsType properties for the first time.


text:
Q: Page Redirection Issue- Cakephp3 using Jquery I have a page where I have kept a dropdown where user can switch over languages. I am using theme so I have kept this dropdown on login.ctp page and posting form values to controller's method using Jquery. I have two form elements within login.ctp I don't know but my dropdown form element is not reaching to particular controller instead it is redirecting to login controller.
login.ctp
 <form id="locale_form" method="post" action="changeLanguage">

  Please Select Language
    <select id="languageselect" name="languageselect">
        <option name="select" value="lang">Select A Language</option>
        <option name="en_EN" value="en_EN">English</option>
        <option name="de_DE" value="de_DE">German</option>
    </select>

  </form>

              <?= $this->Flash->render('auth') ?>
            <?= $this->Form->create('',['class'=> 'form-login','id'=>'login_form']) ?>
-----------------Login Form Code----------------

Using Jquery onchange I am making switch over languages.

My Userscontroller withing that method:
use Cake\I18n\I18n;

class UsersController extends AppController
{
 public function changeLanguage()
    {
         /*I18n::locale('de_DE');
         echo "reached here";*/
         print_r($this->request->data());die();
        if ($this->request->is('post'))
        {

            $lang = $this->request->data('languageselect');
            $this->request->session()->write('locale', $lang);
            I18n::locale($lang);
            return $this->redirect(['action' => 'login']);
        }

    }

I don't know why But my form element with id="locale_form" is not reaching to its action element. I am using Cakephp3 and I don't know where I have messed up.

A: Add this method changeLanguage to allow like below.
$this->Auth->allow('changeLanguage');


text:
Q: return String from database with CodeIgniter This is my Model :
function getAvenuName($id) {
        $this->db->distinct();
        $this->db->select('admin.username');
        $this->db->from('personal_closest');
        $this->db->join('admin', 'admin.id = personal_closest.avenu_id', 'left');
        $this->db->where('personal_closest.avenu_id', $id);
        $query = $this->db->get();
        return $query->result();
    }

This is my Controller :
foreach ($listofcloset['postByUser'] as $key => $value) {
            $listofcloset['postByUser'][$key]['calculatetime']   =  $this->calculatetime(strtotime($value['postdatetime']));
            $listofcloset['postByUser'][$key]['countcomments']   =  $this->countcomments($value['id']);
            $listofcloset['postByUser'][$key]['comments']        =  $this->comments->sltpostcomments($value['personal_closest_id']);
            $listofcloset['postByUser'][$key]['countCloset']     =  $this->closet->countCloset($value['id']);
            $listofcloset['postByUser'][$key]['givencool']       =  $this->checkCoolIsGiven($this->session->userdata('user_id'),$value['user_id'],$value['personal_closest_id']);
            $listofcloset['postByUser'][$key]['givencloset']     =  count($this->closet->selectIdbycloset($this->session->userdata('user_id'),$value['user_id'],$value['personal_closest_id']));
            if (empty($listofcloset['postByUser'][$key]['username'])){
                $listofcloset['postByUser'][$key]['username'] = $this->personal_closest->getAvenuName($value['avenu_id']);
            }
        }

When i go to take the username i've a problem with array to string conversion. I'm trying to found a solution to take just the String instaed the array.
That's the result:
[username] => Array
            (
                [0] => stdClass Object
                    (
                        [username] => USER1
                    )

            )

A: This should get it :)
function getAvenuName($id) {
    $this->db->distinct();
    $this->db->select('admin.username');
    $this->db->from('personal_closest');
    $this->db->join('admin', 'admin.id = personal_closest.avenu_id', 'left');
    $this->db->where('personal_closest.avenu_id', $id);
    $query = $this->db->get();
    $result = $query->row();
    return $result->username;
}

A: Use following code you will get direct array
function getAvenuName($id) {
    $this->db->distinct();
    $this->db->select('admin.username');
    $this->db->from('personal_closest');
    $this->db->join('admin', 'admin.id = personal_closest.avenu_id', 'left');
    $this->db->where('personal_closest.avenu_id', $id);
    $query = $this->db->get();
    return $query->row_array();
}


text:
Q: C# Winforms: Multiple top level windows and ShowDialog() I have a Winforms application that uses show multiple top-level windows:
Form1 form1 = new Form1();
form1.Show();
Form2 form2 = new Form2();
form2.Show();
Application.Run();

Inside one of the event-handlers in Form1, I would like to be able to show a modal dialog:
Dialog dialog = new Dialog();
dialog.ShowDialog(form1);

without suspending the other top-level window.
Is this possible?

A: You'd need to run each top-level window on its own STA thread to achieve that, I believe.

A: There is a simple solution that seems to work properly. You can simply check if we are being disabled and re-enable if needed.
    [DllImport("user32.dll")]
    private static extern void EnableWindow(IntPtr handle, bool enable);

    protected override void WndProc(ref System.Windows.Forms.Message msg)
    {
        if (msg.Msg == 0x000a /* WM_ENABLE */ && msg.WParam == IntPtr.Zero)
        {
            EnableWindow(this.Handle, true);
            return;
        }

        base.WndProc(ref msg);
    }

A: If you need an alternate method to running multiple UI threads, you can handle the WM_ENABLE message and use the EnableWindow method to prevent the Form from being disabled.

A: Once you show a modal dialog, it will make all other windows on the same STA thread unusable.  The reason behind this is the modal dialog will start intercepting all messages for that particular thread.  The other top level windows will not be able to respond until the modal dialog is closed.


text:
Q: Reported speech: unnecessary past tense? The following is an excerpt from a textbook in Korea. I'm wondering if this is an unnecessary past tense for the reported speech--or possibly wrong.

When I moved to Korea, one of the first things my coworker taught me
  was how to say my address. I didn't understand why it was so
  important. They explained that I'd often give it over the phone when I
  ordered things to be delivered.

Is the past tense necessary at all? Ordering food over the phone is not a one-time event and there is all likelihood that the writer will order more food in the future--not to mention that I'd never explain it like that. (I'd just say "You'll need it when you order food.)
What do you guys think?

A:

*

*They explained [that I would often give it over the phone when I ordered things to be delivered].

Let's imagine this, that last week your coworker(s) said something like this to you:

*

*"Because you will often give it over the phone when you order things to be delivered."
Now you are reporting to us (the readers) what had been said. There are two common choices:

*

*They explained [that I will often give it over the phone when I order things to be delivered].

*They explained [that I would often give it over the phone when I ordered things to be delivered].
In #1, the reported indirect speech has not been backshifted; while in #2 (which is the same as your original example), the reported indirect speech has been backshifted. (Note: backshifting involves replacing a present-tense verb with a preterite, which is a past-tense verb.)
Without any surrounding context--that is, just looking at those two versions alone on a white sheet of paper--both versions would seem to be grammatical. I'd think that the #2 version with the backshift would be the default, and there would have to be a specific reason why the speaker would intentionally use the #1 version (the non-backshifted version).
Backshifting in a subordinate clause can occur when either one of the following conditions is true:

*

*A.) The tense of the matrix clause is a type of past-tense.

*B.) The time of the matrix clause situation is in the past time sphere.
In your case, both of those conditions are true--the matrix clause is "They explained X", and it uses the preterite "explained" and it is about a situation that occurred in the past. And so, backshifting can occur.
In general, depending on the purpose of the sentence, there can be a preference for either the non-backshifted version or for the backshifted version. Sometimes the non-backshifted version might be considered to be "much more widely appropriate" than the backshifted version. Sometimes the backshifted version is obligatory.
For more info on backshifting, here is a related post, which also includes pointers to other related posts:

*

*https://english.stackexchange.com/a/167929/57102

A: This is an 'historical' narrative, set at the past time when the writer moved to Korea, so the head clause of this sentence, They explained ..., is set in the past. The remainder of the sentence is indirect speech, in which the clause expressing what was spoken (and that clause's dependents) must be backshifted to the past tense of its head clause.
If the writer had expressed this as direct, quoted speech instead of indirect speech he would have written:

They explained "You will often give it over the phone when you order things to be delivered."

For indirect speech, then, the I'd often give it clause represents a futurive present-tense will backshifted into the past tense, a "future-in-past". Likewise, the when you ordered clause represents a "relative present" form, order, backshifted into the past tense.

A: You are confusing between the non-actuality of subjunctive speech and the non-specificity of non-finite speech.
What you are reading is a sentence with subjunctive retrospection.
One of the difficulties I find in students of English from the far-east is their failure to see the significance, beauty and importance of subjunctive speech, as their native tongues probably do not have subjunctive speech.

*

*Subjunctive speech operates in imaginary time, where the actuality of events described are unbounded. Unbounded actuality means events do not need to take place. Because events are specified in imaginary time, there is no reality for events to take place.

*Non-finite speech is unbounded and non-specific in instance of time and object. That is, time of occurrence is unbounded and object is not specific.

*Non-finite speech is also subjunctive speech if the actuality of events in non-finite speech is unbounded. Non-finite subjunctive is like not having the cake and not specifying when, or if you even ever get eat it - unbounded time, object and actuality.
You should read my explanations

*

*subjunctive speech: The third conditional for "if I could"

*non-finite speech: Why "can" not "could" in "She was one of those people who can. . . ."?
Examples of subjunctive construction, are these present propositional speech

*

*If I ordered a pizza, would you eat it?

*Could you remove your shoes before you enter my house?

Within the braces are temporally and materially non-finite phrases (no specific time or house), to express the time-independence of the materialization of any such house. Since the {non-finite phrase} does not include an imaginary event, without an imaginary event, there is no subjunctivity to consider.

*

*I wanted {something}.

*I wanted {a house that is red}.

*I will want {a house that is red}.

*I have never seen {a house that is red}.

Subjunctive proposal for the present, without binding the action into actually happening:

*

*If I painted you a red house, would you give me your blue shoes?

Subjunctive retrospection of a past hypothesis, regardless if it did or when it happened:

*

*If I had painted you a red house, would you have given me your blue shoes?

Subjunctive future possibility:

*

*If I will have painted you a red house after our retirement next year, will you have given me your blue shoes?

Subjunctive retrospection of the past.

*

*I remember the wonderful time when he was still alive. I would often jump for joy when we ordered pizza.

Subjunctive non-finite:

*

*I advise that she {non-finite subjunctive}.

*I advise that she {go to school and acquire knowledge}.

*I advise that she {not go to school but stay home}.

*I advise that she {be home-schooled}.

*I advise that she {learn some manners}.

*I advise that she {start {nested non-finite}}.

*I advise that she {start {learning some manners}}.

Disclaimer:
Some people well-versed in understanding the term "subjunctive mood" applied to the English language is unaware of a more loosely defined "subjunctive" having a more general meaning in non-language specific linguistics. As they would attempt to shoot my explanation down due to my mere "wrongful" use of the term "subjunctive". Please refrain from doing that, no matter how wrong or maverick you think my use of the term is.
These topics on non-specificity are rather obfuscating at times and I hope I have not mistakenly assigned examples to categories where they do not belong. If I did, help me correct it.


text:
Q: Django Executing Python Script i am doing a copy cat with Need a minimal Django file upload example
i changed the view.py with my code to dump the csv file into sqlite database.
i have already created the table in default sqlite database.
import sqlite3
import csv
import sys
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

    gfile= csv.reader(open(newdoc))
    gon = sqlite3.connect("database.sqlite")
    gon.text_factory = str
    gon.execute("DELETE FROM abc where rowID > 0 ")
    gon.executemany("insert into abc values (?, ?, ?, ?, ?)", gfile)
    gon.commit()
    gon.close()*

    return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

my code is starting from first introduction of gfile
Error @ line 20 : Coercing to unicode : need string or buffer, Document Found
please help

A: You are passing Document instance to open. Instead you should pass the file, that was uploaded directly to csv.reader:
gfile = csv.reader(request.FILES['docfile'])


text:
Q: Nested Grid Example - Different Columns I am using the latest version of ui-grid ui-grid.info.
What is the best way to handle nested grids with the possibility of the nested child grid having different columns then the parent row.

A: Expandable Grids are probably the best approach. I have not tried this for more than one level but they work pretty well.
http://ui-grid.info/docs/#/tutorial/216_expandable_grid


text:
Q: Using #pragma to remove clang warnings based on clang check I want to remove/ignore a clang warning for a block of code and found multiple examples of how to use pragamas for this. For example if the warning is unused-variable you can disable it by using:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"

int a;

#pragma clang diagnostic pop

However the problem is that I do not get a warning in the output when building the repository, I only get to know which clang check it is that gives the warning... And I can not find any other questions or documentations where this is the case. This is what my output looks:
warning: Use of memory after it is freed [clang-analyzer-cplusplus.NewDelete]

I have tried hundreds of different combinations of how to ignore this but nothing works (using // NOLINT is not a viable option). Among the things that i have tried, here are some:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winline-new-delete"
#pragma clang diagnostic ignored "-Wmost"
#pragma clang diagnostic ignored "-Weverything"
#pragma clang diagnostic ignored "clang-analyzer-cplusplus.NewDelete"
#pragma clang diagnostic ignored "-Wclang-analyzer-cplusplus.NewDelete"
#pragma clang diagnostic ignored "-clang-analyzer-cplusplus.NewDelete"
#pragma clang diagnostic ignored "-W-NewDelete"
#pragma clang diagnostic ignored "-W-new-delete"

// code

#pragma clang diagnostic pop

Note, "fixing" the code is also not an option since it is third party code.

A: As mentioned in the comments the #pragma clang diagnostic approach can only be used to suppress compiler warnings. The warnings you refer to are coming from clang-static-analyzer which is now a part of clang-tidy.
The only two options to disable a specific clang-tidy check via code are the //NOLINT and //NOLINTNEXTLINE macros.
As you mentioned the code in question is third-party I will assume that you are not interested in analyzing it at all. Since you are using CMake this is easily done via .clang-tidy files. You can place a .clang-tidy file in the root directory of your project and list/configure the desired checks there like this:
Checks: '-*,cppcoreguidelines-*'

(this would enable all Cpp Core Guidelines checks).
Then in the directory where your third-party code is placed you can disable clang-tidy analysis via a .clang-tidy file placed in that directory. As .clang-tidy files cannot be empty or specify no checks, you can do this by "misconfiguring" a check like this:
Checks: '-*,misc-definitions-in-headers'
CheckOptions:
  - { key: HeaderFileExtensions,          value: "x" }

For more details on this approach see this answer.
Alternatively you can use the .clang-tidy file in the third-party directory to disable only some checks.

A: According to this, for Clang Static Analyzer you have to use:
#ifndef __clang_analyzer__
// code
#endif

A: Best approach that comes to my mind is a little dependent to your build system. Let's assume that you have a sample code like this:
Main file:
int main()
{
    // ...
    int *a = new int;
    *a = 10;
    delete a;

    if (::rand() < 10) {
        std::cout  << *a; //<-- clang tidy warning here
    }
    //...
}

This creates the clang tidy warning in the mentioned line. Now what You can do? Separate your code into 2 files:
File A:
void foo() {
    int *a = new int;
    *a = 10;
    delete a;

    if (::rand() < 10) {
        std::cout  << *a; //<-- clang tidy warning here
    }
}

Main file:
int main()
{
    // ...
    foo();
    //...
}

And now disable cland-tidy for File A. This is a sample, But I guess you understand my general idea. You cannot disable clang-tidy because it is in another library and you cannot touch that code for several reasons. //NOLINT does not work on function too. So just create a wrapper in a single file for using that library and disable clang-tidy in that wrapper file for whole file.


text:
Q: Android Click event not working in Ionic 3 firebase push notifications? I am using cordova-plugin-fcm-with-dependecy-updated this plugin for push notification. Notification receiving on top of the notification bar but when I click on it it will redirect to respected app but if (data.wasTapped) this is not firing what to do now ?
This is my notification payload.
{
blogID: "2601"
body: ""
click_action: "FCM_PLUGIN_ACTIVITY"
description: ""
deviceId: "eGKYSXRYkqY:APA91...."
redirect: "BlogDetails"
title: "Post created successfully"
wasTapped: false
}

Here is the notification code in app.component.ts file
 this.fcm.onNotification().subscribe((data: any) => {
      if (data.wasTapped) {
        console.log(":::Tapped::::", data);
        // Here click event not working
} else {
   // Notification received in ForeGround
    // This is working fine notification receiving
}

I also try with this payload mention in github repo
{
  "token": "[FCM token]",
  "notification":{
  "title":"Post created successfully",
  "body":"",
  "sound":"default",
 },
 "data":{"redirect":"BlogDetails","blogID":2609}
 ,
 "android": {
 "notification": {
  "icon":"fcm_push_icon",
  "click_action": "FCM_PLUGIN_ACTIVITY"
   }
 }
}

What I am doing wrong? thanks


text:
Q: How to raise 505 exception in ruby on rails in development? Is there a way to raise a 505 exception with ruby on rails in development?
I would like to testdrive my custom 505 exceptions but found no documentation on how to raise a 505 anywhere.

A: i am a little confused here. are you talking about a 505 status codes? or are you talking about raising exceptions?
i don't think that there is a 505 exception, so i assume you are talking about HTTP status code version not supported (http://en.wikipedia.org/wiki/List_of_HTTP_status_codes).
it could be as simple as this:
  def index
    render nothing: true, status: 505
  end

if you call an action like that you will get something like this as a response:
curl -I http://hamburg.onruby.dev:5000/
HTTP/1.1 505 HTTP Version not supported
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-UA-Compatible: chrome=1
Content-Type: text/html; charset=utf-8
X-Meta-Request-Version: 0.2.8
Cache-Control: no-cache
Set-Cookie: locale=de; domain=onruby.dev; path=/; expires=Sat, 11 Oct 2014 07:45:52 -0000
X-Request-Id: b8232480-5585-4e99-bc4c-44019e41db6a
X-Runtime: 0.010615
Connection: close
Server: thin 1.5.1 codename Straight Razor


text:
Q: .htaccess WordPress ignore directory and remove index.php from that directory So I know how to tell WordPress how to ignore a directory using the .htaccess file but I want to be able to remove the index.php from inside that directory too so I can access like this:
wordpresssite/directory/controller/function = wordpresssite/directory/index.php/controller/function
I've been trying but I'm clearly not very good at writing .htaccess files.
Thanks
My .htaccess file
The wordpress site is called smartronic and the subdirectory I want to ignore and remove index.php from is /mailin
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /smartronic/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} !^/(mailin|mailin/.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /smartronic/index.php [L]
</IfModule>

# END WordPress

At the moment going to smartronic/mailin takes me to the xampp root page or a 404 page

A: To insert index.php into a fixed URL, you can use a simple RewriteRule
RewriteRule ^mailin/controller /mailin/index.php/controller [L]

If controller is variable, you need to capture this part with (...) and append it after the substitution with $1
RewriteRule ^mailin/(.*)$ /mailin/index.php/$1 [L]


text:
Q: Removing custom meta data I wrote some code to add some custom meta boxes to my theme admin panel, and it works like a charm. The problem is I can't figure out how to make it so I can remove some of the data too.
Example:
I can upload multiple pictures in my acp and I would like that 'Remove' button actually works.
Image
Here is my functions.php:
<?php
add_action( 'init', 'bb_article_init' );
function bb_article_init() {
    $labels = array(
        'name'               => _x( 'Article', 'post type general name', 'your-plugin-textdomain' ),
        'singular_name'      => _x( 'Article', 'post type singular name', 'your-plugin-textdomain' ),
        'menu_name'          => _x( 'Articles', 'admin menu', 'your-plugin-textdomain' ),
        'name_admin_bar'     => _x( 'Article', 'add new on admin bar', 'your-plugin-textdomain' ),
        'add_new'            => _x( 'Add New', 'article', 'your-plugin-textdomain' ),
        'add_new_item'       => __( 'Add New Article', 'your-plugin-textdomain' ),
        'new_item'           => __( 'New Article', 'your-plugin-textdomain' ),
        'edit_item'          => __( 'Edit Article', 'your-plugin-textdomain' ),
        'view_item'          => __( 'View Article', 'your-plugin-textdomain' ),
        'all_items'          => __( 'All Articles', 'your-plugin-textdomain' ),
        'search_items'       => __( 'Search Articles', 'your-plugin-textdomain' ),
        'parent_item_colon'  => __( 'Parent Articles:', 'your-plugin-textdomain' ),
        'not_found'          => __( 'No articles found.', 'your-plugin-textdomain' ),
        'not_found_in_trash' => __( 'No articles found in Trash.', 'your-plugin-textdomain' )
    );

    $args = array(
        'labels'             => $labels,
        'description'        => __( 'Description.', 'your-plugin-textdomain' ),
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'article' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 5,
        'menu_icon'          => 'dashicons-list-view',
        'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
    );

    register_post_type('article' ,$args );
}
register_taxonomy("Categories", array("article"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Category", "rewrite" => true));

add_action("admin_init", "admin_init");

function admin_init(){
    add_meta_box("article-price-meta", "Price", "article_price", "article", "side", "high");
}
function article_price(){
    global $post;
    $custom = get_post_custom($post->ID);
    $price = $custom["article_price"][0];
    echo 'Price:';
    echo '<input name="article_price" value="'. $price.'" />';
}

add_action('save_post', 'save_details');
function save_details(){
    global $post;
    update_post_meta($post->ID, "article_price", $_POST["article_price"]);
}

function add_custom_meta_boxes() {
    function bb_article_images() {
        wp_nonce_field(plugin_basename(__FILE__), 'bb_article_images_nonce');

        $imgArray = get_post_meta(get_the_ID(), 'bb_article_images', false);
        foreach($imgArray as $img){
            $fileName = substr(strrchr($img['url'],"/"), 1);
            echo "<form action='functions.php' method='post'>";
            echo "<input type='hidden' name='fileName' value='".$filename."'>";
            echo $fileName;
            echo "<button type='submit'>Remove</button>";
            echo "</form>";
            echo "

";
        }
        $html = '
';
        $html .= 'Upload your images here.';
        $html .= '
';
        $html .= '<input type="file" id="bb_article_images" name="bb_article_images[]" value="" size="25" multiple />';
        echo $html;
    }
    add_meta_box(
        'bb_article_images',
        'Article images',
        'bb_article_images',
        'article',
        'side',
        'high'
    );

}
add_action('add_meta_boxes', 'add_custom_meta_boxes');

function save_custom_meta_data($id) {
    if(!wp_verify_nonce($_POST['bb_article_images_nonce'], plugin_basename(__FILE__))) {
      return $id;
    }

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $id;
    }

    if('page' == $_POST['post_type']) {
      if(!current_user_can('edit_page', $id)) {
        return $id;
      }
    } else {
        if(!current_user_can('edit_page', $id)) {
            return $id;
        }
    }
    $files = array_filter($_FILES['bb_article_images']['name']);
    $total = count($files);

    $is_image = true;

    if($total > 0) {

        $supported_types = array('image/jpeg');

        for($i = 0; $i < $total; $i++){
            $arr_file_type = wp_check_filetype(basename($_FILES['bb_article_images']['name'][$i]));
            $uploaded_type = $arr_file_type['type'];

            if(!in_array($uploaded_type, $supported_types)){
                $is_image = false;
                die("test");
            }
        }

        if($is_image) {
            for($i = 0; $i < $total; $i++){
                $upload = wp_upload_bits($_FILES['bb_article_images']['name'][$i], null, file_get_contents($_FILES['bb_article_images']['tmp_name'][$i]));

                if(isset($upload['error']) && $upload['error'] != 0) {
                    wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
                } else {
                    add_post_meta($id, 'bb_article_images', $upload);
                }
            }
        } else {
            wp_die("The file type that you've uploaded is not an image.");
        }

    }

}

add_action('save_post', 'save_custom_meta_data');

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');
?>

Few things came to my mind but I failed to make any work. Like creating custom nonce? and when it gets triggered through URL do a MySQL query for removal, Make a forms (as is now) and trigger them through POST, calling another php file, calling the functions.php, using some wp builtin functions...
Can you at least point me out at how should this be done?
Thank you a lot! :D


text:
Q: Uploading files with drag and drop is unstable I am creating a drag and drop uploader and I am using base64 to send the data to my server using a hidden field. (The file will be sent later, not as soon as its dropped).
Testing small image files and text files works really well, but when I try a 20MB zip or a 2MB WAV the whole this becomes unstable. Google Chrome crashes or displays a blank output box and firefox hangs for ages and eventually displays the base64 string. IE actually works for once and displays the string the fastest but still with an unacceptable wait time.
Is my code inefficient or is it something else?
Here is my code:

Drop files here

<input name="filebox" type="text" id="filebox" size="300">
<output id="list"></output>

This test page is live at: http://www.tabbicat.info/local/propellor/drop.html

A: Ok, I tried your live link and the same demo that is available at html5rocks, and both took around 2 seconds for a 23Mb file. I then tried to create that exact code at jsfiddle but for some reason the drag and drop did not want to function. So I used the file selector method instead. Again, it took just about 2 seconds to read in the file. All I can think is that you may possibly have some machine memory problems, like a lack of it or something, or maybe HDD transfer speeds? Or perhaps there is some issue in browser drag an drop code. :/
Anyway, you can see the file selector method at my jsfiddle
#progress_bar {
    margin: 10px 0;
    padding: 3px;
    border: 1px solid #000;
    font-size: 14px;
    clear: both;
    opacity: 0;
    -moz-transition: opacity 1s linear;
    -o-transition: opacity 1s linear;
    -webkit-transition: opacity 1s linear;
}
#progress_bar.loading {
    opacity: 1.0;
}
#progress_bar .percent {
    background-color: #99ccff;
    height: auto;
    width: 0;
}

<input type="file" id="files" name="file" />
<button onclick="abortRead();">Cancel read</button>

0%

var reader;
var progress = document.querySelector('.percent');

function abortRead() {
    reader.abort();
}

function errorHandler(evt) {
    switch (evt.target.error.code) {
        case evt.target.error.NOT_FOUND_ERR:
            alert('File Not Found!');
            break;
        case evt.target.error.NOT_READABLE_ERR:
            alert('File is not readable');
            break;
        case evt.target.error.ABORT_ERR:
            break; // noop
        default:
            alert('An error occurred reading this file.');
    };
}

function updateProgress(evt) {
    // evt is an ProgressEvent.
    if (evt.lengthComputable) {
        var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
        // Increase the progress bar length.
        if (percentLoaded < 100) {
            progress.style.width = percentLoaded + '%';
            progress.textContent = percentLoaded + '%';
        }
    }
}

function handleFileSelect(evt) {
    // Reset progress indicator on new file selection.
    progress.style.width = '0%';
    progress.textContent = '0%';

    reader = new FileReader();
    reader.onerror = errorHandler;
    reader.onprogress = updateProgress;
    reader.onabort = function (e) {
        alert('File read cancelled');
    };
    reader.onloadstart = function (e) {
        document.getElementById('progress_bar').className = 'loading';
    };
    reader.onload = function (e) {
        // Ensure that the progress bar displays 100% at the end.
        progress.style.width = '100%';
        progress.textContent = '100%';
        setTimeout("document.getElementById('progress_bar').className='';", 2000);
    }

    // Read in the image file as a binary string.
    reader.readAsDataURL(evt.target.files[0]);
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);


text:
Q: How to understand MediaCodec's user surface to improve codec performance? The mediacodec's official document said:

Data Types
Codecs operate on three kinds of data: compressed data, raw audio data and raw video data. All three kinds of data can be processed using ByteBuffers, but you should use a Surface for raw video data to improve codec performance. Surface uses native video buffers without mapping or copying them to ByteBuffers; thus, it is much more efficient. You normally cannot access the raw video data when using a Surface, but you can use the ImageReader class to access unsecured decoded (raw) video frames. This may still be more efficient than using ByteBuffers, as some native buffers may be mapped into direct ByteBuffers. When using ByteBuffer mode, you can access raw video frames using the Image class and getInput/OutputImage(int).

How to under stande this? you should use a Surface for raw video data to improve codec performance, What is native video buffers? How do I use Surface to improve encode or decode performance?

A: You can use the input surface of a codec for ecoding video frames, you can get this surface using createInputSurface() then (if you don't use NDK) you can get the canvas from the surface and draw frames on it or you can use NDK and copy frame data to the surface buffer, both of this approaches in the result will give you encoded frame data.
As for decoding you can create some surface in your UI and pass it to decoder using configure() it will allow the decoder to render a decoded frame into the surface so you won't need to copy decoded data from output buffers of decoder the only thing you should do is to pass true as "render" argument to releaseOutputBuffer() of the decoder.

A: When you use a surface you don't have to feed the byte buffers explicitly to the encoder. Encoder will directly grab the the input data from surface. Here are some of the examples of using it. BigFlake BigFlake is the best site for starting with. EncodeAndMuxTest
Hope this will help you to understand the concept.


text: Q: killed windows, trying to recover data through ubuntu windows got corrupted during a update, i am trying to access the data on the HDD to back it up to restore windows. the HDD is mounted already, but when i try and acces the HDD, it does not show any data. i tried to change the permissions to be able to view whats on the disk, but it does not let me. every time i change the permission and click apply, they change back to being blank. any info would help thank you. BTW i have Ubuntu 12.10


text:
Q: Missing JPG file slowing down page load This is a WordPress site
There is a JPG file located in sub directory that is slowing down page load.
EXAMPLE
mydomain.com/wp-content/uploads/2018/01/missing_file.jpg
File does not exist (missing-file.jpg)
Sub directories do not exist (2018/01/)
File load shows 404 in browser.
File / directory path shows up in performance test tools.
How do I get rid of all references to this missing directory and file?


text:
Q: PHP: Create individual arrays with all the duplicates of an array I have created some arrays that contain all the duplicates of some previous arrays. For example:
[475] => string(9) "038231370"
[5135] => string(9) "038231370"
[13236] => string(9) "038231370"
[5575]=> string(9) "038231370"
[4357]=> string(9) "038293950"
[10509]=> string(9) "038293950"
[6031]=> string(10) "0038303163"
[5529]=> string(10) "0038303163"
[534]=> string(10) "0038303163"
[5303] ...

As you can some duplicates are more than one time double. What I want to do is to create different arrays which will contain the same values and their keys.
function compare($array) {
    $per_array = array();
    $old_key    = NULL;
    $old_value    = NULL;
    foreach($array as $key => $value){

        if ($old_value === $value) {
            $per_array[$old_key]    = $old_value;
            $per_array[$key]        = $value;
        }
        else {(DO SOME TESTS)unset($per_array);}

        $old_value  = $value;
        $old_key    = $key;

    }
}

but I seem to miss something. Please any help would be important.
Well one example of my expected arrays is:

per_array(4) = { [475] => string(9) "038231370"  [5135] => string(9)
  "038231370"  [13236] => string(9) "038231370"  [5575]=> string(9)
  "038231370"  }
per_array(3) = { [4357]=> string(9) "038293950"  [10509]=> string(9)
  "038293950" }

and so on...

A: Here is a simple example of

*

*Unique Values

*Duplicate Values wit their keys

Code
$a = $u = $d = array();

// Build Temp Data with duplicates
for($i = "A"; $i < "M"; $i ++) {
    $a[$i] = mt_rand(0, 3);
}

//Simple Loop
foreach ( $a as $k => $v ) {
    in_array($v, $u) ? $d[$k] = $v : $u[$k] = $v;
}

var_dump($a); // Original array
var_dump($u); // Unique
var_dump($d); // Duplicate with their keys

Output
array (size=12)
  'A' => int 0
  'B' => int 2
  'C' => int 1
  'D' => int 2
  'E' => int 3
  'F' => int 3
  'G' => int 3
  'H' => int 2
  'I' => int 3
  'J' => int 1
  'K' => int 0
  'L' => int 0

array (size=4)
  'A' => int 0
  'B' => int 2
  'C' => int 1
  'E' => int 3

array (size=8)
  'D' => int 2
  'F' => int 3
  'G' => int 3
  'H' => int 2
  'I' => int 3
  'J' => int 1
  'K' => int 0
  'L' => int 0

A: Try this code :
$array_count = array();

foreach ($array as $key => $arr) :
    $array_count[$arr][] = $key;
endforeach;


text:
Q: List of footnotes in latex I was wondering if I'll have the option to add something like \listoffootnotes in my document like I can use \listoffigures or tables...
Anyone knows how?

A: I tried the example and it worked very well. Here is what I've done:
\usepackage{tocloft}

%% Footnotes-Listing %%
\newcommand{\listfootnotesname}{List of Footnotes}% 'List of Footnotes' title
\newlistof[chapter]{footnotes}{fnt}{\listfootnotesname}% New 'List of...' for footnotes
\let\oldfootnote\footnote % Save the old \footnote{...} command
\renewcommand\footnote[1]{% Redefine the new footnote to also add 'List of Footnote' entries.
    \refstepcounter{footnotes}% Add and step a reference to the footnote/counter.
    \oldfootnote{#1}% Make a regular footnote.
    \addcontentsline{fnt}{footnotes}{\protect
\numberline{\thefootnotes}#1}% Add the 'List of...' entry.
}

After tha I could use the command \listoffootnotes:

The tocloft-Package is Part of Texlive-Extra.

A: I haven't tried this, but from what I gather it should be possible to accomplish what you need using the tocloft package. See chapter 2.4 in the documentation for more details on creating custom lists.
Here is an example on how it can be done.


text:
Q: SurfaceView: ClassCastException, unable to start activity Trying to get an Android 2.2 application to start up with a SurfaceView as the base view with a button placed atop it located near the bottom of the screen.  So far, no luck.  It crashes every time it attempts to launch.  I've checked to make sure that the activity is registered in the manifest.
Here's my java code:
public class Dragable extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

and here's my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<SurfaceView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/surface_home"
    >
    <Button
        android:id="@+id/add_new"
        android:text="@string/add_new"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
    />
</SurfaceView>

and my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Dragable"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest>

and here's my error:
11-29 11:58:52.620: ERROR/AndroidRuntime(512): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.Dragable}: java.lang.ClassCastException: android.view.SurfaceView
Can't seem to find anything related doing searches on SO.  My appologies if this has been asked before.

A: Now I see the problem. SurfaceView is not a container, I mean it does not extends ViewGroup, so you can't put a Button inside a SurfaceView. What you can do is wrapping the SurfaceView and the Button within a RelativeLayout.

A: You are not using any container to place components. Use this and make changes
 <?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/surface_home"
>
<Button
    android:id="@+id/add_new"
    android:text="@string/add_new"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
/>
 </SurfaceView>
</FrameLayout>


text:
Q: Flutter RawKeyboardListener does not work in release mode I'm using RawKeyboardListener to capture keyboard events on web, it works fine in debug mode but when I build it for release it does not capture keyboard events. I tried it with a basic app:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<void> _onEventKey(RawKeyEvent event) async {
    if (event.runtimeType.toString() == 'RawKeyDownEvent') {
      if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft)) {
        _incrementCounter();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return RawKeyboardListener(
      focusNode: FocusNode(),
      onKey: (RawKeyEvent event) async {
        await _onEventKey(event);
      },
      autofocus: true,
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}

Is there anything i'm doing wrong?

A: Since generated javascript code is minified in release mode, there is no more type RawKeyDownEvent, but something like minified:qN.
Instead of
if (event.runtimeType.toString() == 'RawKeyDownEvent') {

you have to use a more accurate comparison:
if (event.runtimeType == RawKeyDownEvent) {

Here is fixed code (also removed unnecessary async/await):
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void _onEventKey(RawKeyEvent event) {
    // next line prints something like 'minified:qN' in production mode
    print(event.runtimeType.toString());
    // if (event.runtimeType.toString() == 'RawKeyDownEvent') {
    if (event.runtimeType == RawKeyDownEvent) {
      if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft)) {
        _incrementCounter();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return RawKeyboardListener(
      focusNode: FocusNode(),
      onKey: (RawKeyEvent event) {
        _onEventKey(event);
      },
      autofocus: true,
      child: Scaffold(
        appBar: AppBar(),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('You have pushed the button this many times:'),
              Text('$_counter', style: Theme.of(context).textTheme.headline4),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}


text:
Q: How would I store a byte[] array across reboots without SharedPreferences? This question is in a similar vein to my recent question (How would I store an ArrayList<String[]> in order to compare it to a new one later?), except I actually ended up coming up with a solution for that. The solution was to use MessageDigest to convert each part of each contact into a byte[] array, instead of trying to store the finalized ArrayList of String[] objects. It then does the same with the old contact list, and then compares the two calculated byte[] arrays for equality. The issue I'm dealing with now is that I wish to be able to store/retrieve specifically the "old contact book" byte[] array persistently across device reboots... but using SharedPreferences is off the table, since contact books could potentially be very large, and SharedPreferences is intended to be used for smaller key-value pairs (not to mention my peers have advised against it in this case).
I've tried using the FileOutputStream and FileInputStream classes, with a BufferedReader... but that seems to only work for Characters and Strings, not byte[] arrays. (reference documentation: https://developer.android.com/training/data-storage/app-specific#internal-access-files) In addition to the FileOutput/InputStream and BufferedReader classes I saw, there was something else about caching (https://developer.android.com/training/data-storage/use-cases#cache-non-media and https://developer.android.com/reference/android/content/Context#getCacheDir() , respectively) but I wasn't sure how to start with it based off of the documentation.
Is there a method that I can use to store and then retrieve (on reboot) a byte[] array, without using SharedPreferences?


text:
Q: how to use input in cmd i wrote a script in cmd (*.cmd) that copy some file to ftp server, its working and its fine. this is the code:
@echo off

# put the command lines in to txt file

echo cd wf/721/pages >> temp.txt

echo put C:\Users\tc99670\Desktop\tempwf\721\pages\channel.json >> temp.txt
echo put C:\Users\tc99670\Desktop\tempwf\721\pages\main-screen.json >> temp.txt
echo put C:\Users\tc99670\Desktop\tempwf\721\pages\settings.json >> temp.txt
echo put C:\Users\tc99670\Desktop\tempwf\721\pages\wihow to usefi.json >> temp.txt

echo quit >> temp.txt

# connect to ftp and running the all the command in the txt file

ftp -n -s:temp.txt 150.42.40.221

# deleting the txt file

del temp.txt

its working great but when i tried to add the user input option its not working any more:
@echo off
set /P path=Enter path:

echo cd wf/721/pages >> temp.txt

echo put %path%\721\pages\channel.json >> temp.txt
echo put %path%\721\pages\main-screen.json >> temp.txt
echo put %path%\721\pages\settings.json >> temp.txt
echo put %path%\721\pages\wifi.json >> temp.txt

echo quit >> temp.txt

ftp -n -s:temp.txt 150.42.40.221

del temp.txt

i dont know what went wrong,
thanks for your help :)

A: Do not use path as a variable name...
...it is a system variable that tells cmd where to look for programs. Change path in this script to something else, such as inputpath.


text:
Q: Dynamic indexes while zooming in Python Bokeh I am fairly new to Bokeh and try to achieve the following:
I have a dataset with rows containing dates in the format dd-mm-yyyy.
The dates are counted and then plotted.
When zoomed in I want Bokeh to show the indiviudal dates (that works already).
When zoomed out I want Bokeh only to show the months (or years when zoomed out even further). Right know the index gets pretty messy due to individual dates getting closer and closer the more you zoom out.
Is there a way to tell Bokeh to change what is shown in the index depending on how far you zoomed in or out?
Here is my code:
import pandas as pd
from bokeh.charts import TimeSeries
from bokeh.io import output_file, show, gridplot

transactionssent = dict(pd.melt(df,value_vars=['datesent']).groupby('value').size())
transactionssent2 = pd.DataFrame.from_dict(transactionssent, orient= 'index')
transactionssent2.columns = ['Amount']
transactionssent2.index.rename('Date sent', inplace= True)

ts = TimeSeries(transactionssent2, x='index', y='Amount')
ts.xaxis.axis_label = 'Date sent'

If someone knows please point me in the right direction.
Thanks and best regards,
Stefan

A: What you've described as what you want already sounds like the standard behavior of the built in datetime axis. So, my guess is that TimeSeries is treating your dates as string/categorical values, which would explain why you are not seeing standard datetime axis scaling.
I should add that bokeh.charts (including TimeSeries) has recently been removed to a separate project and also is known to have problems. I would actually discourage it's use at this point. Fortunately, it's also easy to plot timeseries with the bokeh.plotting API, which is stable, well-tested and documented, and in widespread use.
Here is an example to demonstrate:
import datetime
import numpy as np

from bokeh.io import show, output_file
from bokeh.plotting import figure

# some fake data just for this example, Pandas columns work fine too
start = datetime.datetime(2017, 1, 1)
x = np.array([start + datetime.timedelta(hours=i) for i in range(800)])
y = np.sin(np.linspace(0, 2, len(x))) + 0.05 * np.random.random(len(x))

p = figure(x_axis_type="datetime")
p.line(x, y)

output_file("stocks.html")

show(p)

Whose axis looks like this when first displayed:

But like this when zoomed in:

You can also further customize how the dates are formatter by setting various properties on the p.xaxis[0].formatter. For details about available properties, see the reference guide:
http://docs.bokeh.org/en/latest/docs/reference/models/formatters.html#bokeh.models.formatters.DatetimeTickFormatter


text:
Q: Aging Objects in a Collection I want to be able to age objects in a Collection.
For example I could put strings in a HashSet.

*

*I would like timestamps associated of when the String was put in the HashSet.

*I would like String older than say time X to be dropped from the HashSet.

*I would like to be able to say "touch" a string and update the time to when it was inserted in the Collection.

So I can accomplish this by keeping track of each String and then running a house cleaning Thread and purging String from the Collection if it is older than a certain time quantum.
However I am looking for:

*

*Either a Clever way to do this.

*An existing open-source java component which accomplishes this.

Thanks.

A: Sounds like you need a cache. Either try CacheBuilder (see Caches Explained) from Guava or EhCache.

A: Google Guava caches meet all your requirements and more! See Caches Explained.

A: I would use JCS, really like the Guava idea though @sjr

A: Why not just create your own Collection class (for the house cleaning tasks) that's backed by a HashMap<String, Date> ?


text:
Q: Scrape specific value from a json i'm looking to scrape some stuff from this example, my goal is to scrape just some values and focus on them by matching the title that's inside of the json file (e.g 5.5/6), i would like to let my script pick just values for the section which has as title and option1/2/3 the number 6
({
    "id": 39430269435981,
    "title": "5.5",
    "option1": "5.5",
    "option2": null,
    "option3": null,
    "sku": "195241242248",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 5.5",
    "public_title": "5.5",
    "options": ["5.5"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
},
{
    "id": 39430269468749,
    "title": "6",
    "option1": "6",
    "option2": null,
    "option3": null,
    "sku": "195241242255",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 6",
    "public_title": "6",
    "options": ["6"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
}

How can i do that? How can i scrape just the id of the part where the title is 6?

A: There must be a more specific method in your case, but the generic method is transform this "json" into a list of dicts and iterate through them, example:
import json

jstring = '''
[
{
    "id": 39430269435981,
    "title": "5.5",
    "option1": "5.5",
    "option2": null,
    "option3": null,
    "sku": "195241242248",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 5.5",
    "public_title": "5.5",
    "options": ["5.5"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
},
{
    "id": 39430269468749,
    "title": "6",
    "option1": "6",
    "option2": null,
    "option3": null,
    "sku": "195241242255",
    "requires_shipping": true,
    "taxable": true,
    "featured_image": null,
    "available": false,
    "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 6",
    "public_title": "6",
    "options": ["6"],
    "price": 13108,
    "weight": 1361,
    "compare_at_price": null,
    "inventory_management": "shopify",
    "barcode": null
}
]
'''
jlist = json.loads(jstring)

for jdict in jlist:
    if ( jdict['title'] == "6" ):
        print(jdict['id'])

output
39430269468749


text:
Q: Nodal voltage analysis in a DC circuit I am trying to analyze the circuit given below:

The reference node is in the bottom with 0 V.
At nodes A and B writing down Kirchhoff's first law equation trying to express each current in terms of the voltage across the branch.
My equation for node A looks like this:
$$
 \frac{V_{G_1}-V_A}{R_1} - \frac{V_A-V_{reference}}{R_2} - \frac{V_A-V_{reference}}{R_3} + \frac{V_A-V_B}{R_4} + I_{G_2} = 0
$$
For node B:
$$
-I_{G_3} -  \frac{V_B-V_{reference}}{R_5} - \frac{V_B-V_A}{R_4} + I_{G_2} = 0
$$
As of now I only have two equations and three unknowns. Therefore I am not sure if my solution attempt is correct.

A: You have done a good job drawing arrows to represent your currents.  When you apply Kirchoff's current law you are just saying all current into a node = all current out of a node.
Below I'll write the node A equation and will arbitrarily assign current into the node as positive:
$$
 \frac{V_{G_1}-V_A}{R_1} - \frac{V_A-V_{reference}}{R_2} - \frac{V_A-V_{reference}}{R_3} - \frac{V_A-V_B}{R_4} - I_{G_2} = 0
$$
Equally as valid - i can arbitrarily assign current into the node as negative which would result in the following equation:
$$
 -\frac{V_{G_1}-V_A}{R_1} + \frac{V_A-V_{reference}}{R_2} + \frac{V_A-V_{reference}}{R_3} + \frac{V_A-V_B}{R_4} + I_{G_2} = 0
$$
Clearly, these are both equivalent.
EDIT:  Using your figure and adding an arrow for IG2.  I will arbitrarily decide that current into node B is negative and write a KCL equation:
$$-I_{R_4} - I_{G_2} - I_{R_5} - I_{G_3} = 0$$


text:
Q: How to simulate the delete key on UITextField? I'm creating an application on the iPad. I create a custom keyboard using UITextField's inputView property. To insert text at the cursor position, I use the copy & paste method (http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html), which works fine. Now, I want to create the delete key. The code that I'm using is:
if (textField.text.length > 0) {
    textField.text = [textField.text substringToIndex:textField.text.length-1];
}

However, as you may know, it only deletes the last character no matter where the cursor is. Does anyone know a better solution?
Thank you very much!

A: I've got it!
This is my delegate method implementation for the shouldChangeCharactersInRange method.

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange) range replacementString:(NSString *) string {
    if ([string isEqualToString:@"⌫"]) {
        // NSLog(@"Backspace Pressed");
        NSMutableString *text = [textField.text mutableCopy];
        // NSLog(@"Length: %d Location: %d", range.length, range.location);
        if (range.length > 0) {
            [text deleteCharactersInRange:range];
        }
        if (range.length == 0 && range.location != 0) {
            NSRange backward = NSMakeRange(range.location - 1, 1);
            // NSLog(@"Length: %d Location: %d", backward.length, backward.location);
            [text deleteCharactersInRange:backward];
        }
        // NSLog(@"%@", text);
        textField.text = text;
        return NO;
    } else {return YES;}
}

It works hand in hand with the UIPasteboard method for getting text into a UITextField, which means that you have to link up your delete key to a method that pastes an arbitrary unicode character into your textfield (such as ⌫), and when the delegate method is called, you recognise that the replacement string is that specific character.
From there, you either delete the characters in range from your mutable string of the textField's text if there is an active selection, or you grab the previous character from the range if there is no selection, just a caret.

A: Late to the party (again ;-)... With iOS 5, UITextField conforms to the UITextInput protocol, which extends UITextField with some helpful methods and properties, including the selectedTextRange property, which is the equivalent of selectedRange in UITextView.

A: This is an alternative solution using a undocumented API: selectionRange. I don't know if this will pass Apple's review but as written it won't make the app crash if the method is not available and does not give warnings too :)
This is a category on UITextField:
- (void)deleteBackward{
    @try{
        //check current selected range
        NSRange selectedRange = [[self valueForKey:@"selectionRange"] rangeValue];
        if (selectedRange.location == NSNotFound) selectedRange = NSMakeRange([[self text] length], 0);
        if (selectedRange.location < 1) return;

        //delete one char
        NSRange deleteRange = (selectedRange.length>0)?selectedRange:NSMakeRange(selectedRange.location-1,1);
        self.text = [self.text stringByReplacingCharactersInRange:deleteRange withString:@""];

        //adjust the selected range to reflect the changes
        selectedRange.location = deleteRange.location;
        selectedRange.range.length = 0;
        [self setValue:[NSValue valueWithRange:range] forKey:@"selectionRange"];
     }@catch (NSException *exception) {
          NSLog(@"failed but catched. %@", exception);
     }@finally {}
}

UPDATE: 2011/11/17
in iOS5 UITextField and UITextView conform to UITextInput protocol (which conforms to UIKeyInput) so you can do [textField deleteBackward]; which will do exactly the same as Del key in the keyboard, [textField insertText:@"text"]; which will insert text and update the caret position correctly, etc.
So, for compatibility purposes, probably what you want to do similar to this:
- (void) myDeleteBackward
{
    if ([self conformsToProtocol:@protocol(UITextInput)]) {
        // iOS5 and later
        [textField deleteBackward];
        // Or do below line if you are not deploy-targeting 5.0 or above and want to avoid warnings
        //[textField performSelector:@selector(deleteBackward)];
    } else {
        // iOS4 and older versions
        // Do the trick :)
        @try{
        ...
        }@catch (NSException *exception) {
        ...
        }
    }
}

A: Consider switching to a UITextView, which has a selectedRange property for getting the currently selected range of characters or the cursor location if nothing is selected. Unfortunately, UITextField does not have this method, and I have not found another way to find the cursor location.
The documentation for the selectedRange property can be found here here on Apple's website. It consists of an NSRange in which selectedRange.location is the cursor location and selectedRange.length is the number of selected characters (or zero if nothing is selected.) Your code will have to look something like this:
textView.text = [textView.text stringByReplacingCharactersInRange:textView.selectedRange withString:@""];

A: Just call [textField deleteBackward]. It takes care of cursor position and highlight for you.
Swift:
textField.deleteBackward()

A: A UITextView has a selectedRange property.  Given that you could build a range to use with the following code:
textView.text = [textView.text stringByReplacingCharactersInRange:?? withString:@""];

A UITextField has no such range property.  Obviously it has a _selectionRange member but that is private.
I think your choices are either to switch to a UITextView or prevent having the cursor anywhere but at the end of the text and using your current code.
You can always submit a bug report to Apple requesting that they document selectedRange for UITextField, or ask for special permission to access the field directly.

A: Holy necro, Batman!  Here's a much simpler answer for iOS 3.2 and later.  Do this in your view controller's viewDidLoad or some other method that has access to the delete button:
[self.myDeleteButton addTarget:nil action:@selector(deleteBackward) forControlEvents:UIControlEventTouchDown];

This is the same way the system keyboard's delete key works: it sends the deleteBackward message along the responder chain.

A: To delete the position behind the cursor, you can use textField.deleteBackward()
This is what I use in Swift 5 when I want to get the result without deleting text from the UITextField
extension UITextField {
    /// simulates removing a character from 1 position behind the cursor and returns the result
    func backSpace() -> String {
        guard var text = text, // local text property, matching textField's text
              let selectedRange = selectedTextRange,
              !text.isEmpty
        else { return "" }

        let offset = offset(from: beginningOfDocument, to: selectedRange.start)

        let index = text.index(text.startIndex, offsetBy: offset-1)
        // this doesn't remove text from the textField, just the local text property
        text.remove(at: index)
        return text
    }
}

A: What about this if (UITextField.text.length > 0) { [UITextField deleteBackward]; } :)

A: you can try this:
if (txtTotal.text.length > 0) {
        txtTotal.text = [txtTotal.text substringToIndex:txtTotal.text.length-1];
    }


text:
Q: Elevation of GPS doesn't work I'm developing a website in which I'll use the elevation or the above sea level of the current location where it uses GPS. I'm testing a website where it will give the coordinates as well as the elevation.
The link of the website that I've searched and I'm testing:
MyGeoPosition.com
PROBLEM: The elevation doesn't work on my laptop.
On my friend's laptop

On my laptop

A: If it only works sporadically, the elevation service used in the source code says it rate limits requests.


text:
Q: Unable to create polyline for map in SwiftUI Essentially I would like to create a polyline that connects all coordinates together with a dashed line. How can this be done with the following setup in SwiftUI.
The following is how I am currently drawing the MapMarkers on the map, can a polyline be used to connect them?
@State var myAddresses = [Locations]()

struct Place: Identifiable {
    let id = UUID()
    let name: String
    let latitude: Double
    let longitude: Double
    var coordinate: CLLocationCoordinate2D {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

Map(coordinateRegion: $region, interactionModes: .all, annotationItems: myAddresses) { place in
    MapMarker(coordinate: place.coordinate)
}

.frame(width: UIScreen.main.bounds.width - 20, height: 500)
.cornerRadius(10)


text:
Q: Pure PHP/HTML views VS template engines views I would like to know which approach is faster, using the pure PHP in the HTML files or using a template engines like Smarty,Twig, ...
What I would particularly like to know is next: which is parsed faster, is the Smarty cache for example faster than using pure PHP?
Which of the template engines is the fastest? I'm about to rewrite simple application where speed is on the first place.

A: Simply and purely opinion, I think the only advantage is portability. You can re-use templates or views from a template engine into other backend application. Say you're moving your application from PHP to Java, you don't need to refactor the templates.
Otherwise, you're adding complexity, adding other layer of execution ( more time ), more requirements to maintain the application ( you need people that knows that template engine ), and so on. PHP itself it's the best and more featured template engine you're going to get, probably the fastest, and you can do caching also, with the advantage of controlling cache from the backend application, and not from the view.

A: I will take up this again as things have changed significantly and there are some pieces of evidence missing from the earlier answer.
Without getting deep into why frameworks use template engines over PHP which most do. For some reason there is a constant effort to "fix" PHP with another abstraction layer. Always with claims of simplicity without loss of versatility or performance.
Regardless, the use of PHP is still the fastest and most versatile way of templating. PHP in it's earliest incarnations looked much like a templating language. But let's take a look at the advancements in PHP and place them side by side with the after layers.
Twig and some others claim caching something which was always an addon in earlier versions of PHP. Caching is now a default part of PHP5.5+ (Opcache) and so using PHP as a template language will give more performance enhancements.
Twig and others claim simple syntax for designers. In comparing the syntax of a template engine you'll see that the logic is similar with the only benefit of using a template system like Twig being another layer of security separation between the designer and the underlying system code.
Two very popular CMS Wordpress and Drupal used PHP as their template engines. So the old argument of using a template engine to secure and simplify the use of PHP while designing a website is not really valid in today's web. While Drupal 8 is moving on to Twig it mostly because twig is part of Symfony Framework ( returning to why do frameworks use template engines). Wordpress on the other hand is still using PHP. As Wordpress is growing by leaps and bounds with web designers using PHP to help this happen. Drupals Community has also been split in part by decisions to use Twig and Symfony.
So it would seem that using PHP is the better choice in terms of performance but also the preference for themers and designers going forward. At least all evidence leads to this conclusion.
That being said here's my baseless opinion. I think that using anything other than PHP as template engine in today's web covers some inherent weaknesses in the underlying framework or web application architecture. That weakness being its complexities and complications that cannot be explained easily at the designer or themer level.
If you are writing a lightweight application that has to be small. Keep it small and performing optimally by using PHP and leave the other engines to "enterprise" level groups and projects

A: "Depends" is the answer to all your questions.
What is "faster"? Execution time? Development time? Maintenance? Memory overhead? A mixture of them? A template engine is usually trading in some performance (speed, memory) for better development and maintenance.
If you are talking about purely dynamic templating (meaning: template evaluated on every request) PHP will outrun any template engine. This is a nobrainer, really. If you're taking caching into account, a template engine like Smarty may help. Caching is nothing you couldn't implement yourself in plain PHP, though. With Smarty it's just been done for you (and on a far more sophisticated level than you possibly would).
If you are using a framework, say Symfony, it might be wise to use Twig, as Twig and Symfony are tightly integrated. Sure you can use Smarty or plain PHP. The question here is: is it practicable?
Caching makes sense when building sites from datasources like a database or remote APIs. What you are really saving (in a sense of reducing) here are database calls, intensive calculations, etc. Check if you have any time-intensive functions running to build your site. If so, use caching (if you can).
Knowing development/maintenance/convenience/performance trade-offs, I would (always) recommend using a template engine. Being a Smarty developer, I'll, of course, suggest using Smarty. That is unless you're using Symfony, then you might be better of with Twig. Or some other framework featuring some other template engine.
Please ignore posts like Smarty vs. Twig, as they only compare a very limited view of the engines. Don't trust benchmarks you haven't faked yourself™.
In general, though, Smarty 3.1 is a bit faster than Twig. Twig is doing a lot of stuff at runtime (being the time when a template is executed) that Smarty does on compile time (being the time when a template is prepared for execution). Twig is not really pissing away speed here. Twig needs to do certain stuff at runtime by design. They traded a bit of performance for a bit of "convenience" (Accessing arrays and objects with the same notation, for example).

A: Let's tear the tropes related to this subject apart:

1. Keep logic out of the presentation - Do not put 'code' into your HTML

Anyone who says this and then tells you to go with templating is contradictory:

*

*PHP is an interpreted language - it becomes C code on execution.

*The templating 'syntax' is interpreted into PHP

They must stop lying to themselves. Their 'templating syntax' is a programming language built on top of another, which in turn is built on top yet another language - That's inefficient, redundant, and weird.
Furthermore, I fail to see how the very existence of the variables every templating engine that ever was depends on aren't considered logic - Their existence, content and implementation depend on a logical backend.
And what of those templating systems with if/else statements and for loops? That's the very essence of logic - The very concepts which most programming languages utilize. They require variable data which can only be generated or exist through some form of computation.
You cannot serve dynamic content without mixing presentation with logic. It's impossible.

2.1 It's safer...

So, you don't trust your HTML guy?
Case: You think your HTML/CSS guy is stupid and will accidentally print the database password
If that's so, I've got news for you - Your environment is already not safe if sensitive data can be accessed/modified from anywhere within the program.
Case: You think your HTML guy will print random server constants - it's dangerous to allow him, as an individual, to work with server logic
I see - He's either stupid, or hates his job and wants to be fired and therefore will do something dumb like printing session variables. Fine, but to that I'll say...
...Why the heck is this stuff not peer reviewed? Even if he had no access to direct server logic but rather a fancy templating system, he could still equally spread his his stupidity/hatred merely because he has final say on output. Or, he could even be in cahoots with another programmer (If any) and still access server constants and co.
-

2.2.1 Good templating engines automatically sanitize output, or allow the templating-guy to do it himself - he knows better when data should be sanitized

You dummy.
You don't know when output should be sanitized? You couldn't do that yourself..?
Even so, maybe you're just the code monkey and the HTML guy is a web-security HTML-injection specialist, and he should be the one sanitizing output. In that case, giving him access to PHP also allows him to use the likes of htmlspecialchars() rather than whatever the template gives him to do the same thing.
Regarding automatic escaping, provided you're safely passing along content, you can implement such a simple feature within the code you're doing so.
--

2.2 ...and I can control what data is being worked with

Think about classes, functions, etc - You throw data in, they work with it, then you get a result. Typically they do not deal with outside data unless it is handed to them (Doing otherwise is unclear, dangerous and bad practice - Some constants aside). Through these same methods, you can pass on precisely what you need to your output in an efficient, clear and unlimited manor.
--
All that said, it seems like the reason you think your templating engine is any safer than plain code is because you're lacking in several areas of general safety:

*

*You (Or whoever) do not peer review content - You allow individuals to output content.

*You are not implementing proper or safe programming practices, and seem to not realize that you can control what's passed along from point A to B.

3. PHP syntax is too hard/difficult to teach the style people

The truth is it's no more complicated than the psuedo-syntax created by template systems such as Smarty, so if this is an issue than dynamic content isn't for you.
The following is in PHP 'short syntax' - Is it too difficult?

<?= $username ?>

4. It's too much work to develop my own solution

Though I'd argue it's not, you're free to choose whatever you wish! Choose whatever fits your needs best. They're usually free, not difficult to integrate, and come with loads of features out of the box.

I'm under the impression that most people opt for templating simply because it looks 'neater' within the file - They love thinking that the TPL file is some special thing they created, they like the way the syntax looks; As if by some magic, the variable is 'called' by the little @ or # symbol and hops from your logic into the output.
It seems like a trick - The beautiful enchantress (AKA The templating engine) draws you in with her beauty. Though she's appealing to the eye, she's really a blood sucking demon and extracts your soul (Server resources) in exchange for eye candy nobody else sees (Your users would much rather have a faster website and more features funded by the $$$ you're saving on power/server renting)
<title>{{@title}}</title>
Vs
<title><?= $title ?></title>

I will admit, there's only one case I can think of in which templates have any ground over PHP - Portability to other applications. appartisan's answer addresses that. Even so, it's not hard to replace <?= $var ?> with {{@var}} - That's a job for a templating-esque system.

A: I have a problem with the argument that logic and data display must be separared as much as possible. I found that data validation and display actually requires a lot of logic on forms. Information about data type, number range, relation between different data requires a lot of code. The real question is should we use a template language on the server side or Javascript on the client side. By using Ajax and client side code for data display and validation, I end up having very little template code. The biggest problem with template engines is the intoduction of new code rules and syntax. I see the future with PHP, Jquery and Ajax and template engines loosing its appeal.


text:
Q: How to store column value from mysql to python variable? actually i'm new to learning python and mysql database
i have table named TABEL_NILAI in database like this:
id auto_increment primary key
NILAI_TRUST FLOAT
NAMA_ALAT VARCHAR(10)

--------------------------
|ID|NILAI_TRUST|NAMA_ALAT|
--------------------------
|1 |   0.12    |  ALAT1  |
--------------------------
|2 |   0.34    |  ALAT2  |
--------------------------
|3 |   0.54    |  ALAT3  |
--------------------------

So i want to Retrieve value NILAI_TRUST from TABEL_NILAI and i want to do some math. here's code i was made:
kursor = db.cursor()
kursor.execute("SELECT NILAI_TRUST FROM TABEL_NILAI")
hasil = kursor.fetchall()

def hitung_standardeviasi():
    #input data
    TrustValue= x().split(',')
    for i in range(len(TrustValue)):
        TrustValue[i]= int(TrustValue[i])
    jumlah=0

    #Average
    for i in range(len(TrustValue))
        jumlah += TrustValue[i]
    ratarata = jumlah/len(TrustValue)

    total=0

    #sigma
    for i in range(len(TrustValue))
        hitung = (TrustValue[i]-ratarata)**2
        total += hitung
    sigma = total/(len(TrustValue)-1)

    #standardeviasi
    standardeviasi = math.sqrt(sigma)
    print(standardeviasi)

for x in hasil:
    hitung_standardeviasi()

And giving me error like:
Traceback (most recent call last):
   File "/home/lihat_tabel.py", line 60, in <module>
        hitung_standardeviasi()
   File "/home/lihat_tabel.py", line 24, in hitung_standardiviasi
        Trustvalue = x().split(',')
TypeError: 'tuple' object is not callable

so how to retrieve value into python variable in right ways.
Please help:(

A: The query
kursor.execute("SELECT NILAI_TRUST FROM TABEL_NILAI")

will return a iterable of tuples, for example like this:
[(0.12,), (0.34,), (0.54,)]

So this line
TrustValue= x().split(',')

has two problems:

*

*x is a tuple, so it can't be called like x()

*x is not a string, so it doesn't have a split method

It looks like you want to make TrustValue a list of the int values of each result in the query.  In that case this for loop is unnecessary, because it will only it will make the code operate on a single result at a  time:
#  You don't need this
for x in hasil:
    hitung_standardeviasi()

The hitung_standardeviasi function could begin like this:
def hitung_standardeviasi():
    #input data
    results = list(hasil)
    TrustValue= []
    for i in range(len(results)):
        TrustValue[i]= int(results[i][0])
    jumlah=0

We can make this code a more readable by looping over the results directly instead of using the for i in range(len(collection)): idiom, which is often unnecessary in Python:
def hitung_standardeviasi():
    #input data
    TrustValue= []
    for (result,) in hasil:
        TrustValue.append(int(result))
    jumlah=0

Using a list comprehension is even more Pythonic:
def hitung_standardeviasi():
    #input data
    TrustValue = [int(result) for (result,) in hasil]
    jumlah=0

You might want to look at the sum built-in function and the statistics module too.


text:
Q: is it possible to retrieve the time when the current run started? How do we retrieve the datetime when the logic app started execution?
In our logic apps, we are currently setting a variable just to capture the datetime of when the workflow started executing, like so:

How do get the time when the logic app started execution without having to declare a variable at the beginning to capture utcNow()?

A: An easier option (which to be honest may have been added to Azure Logic Apps) since @George Chen's answer in 2019) is to use the trigger() expression to obtain the JSON object that contains information about what triggered the Logic App run. The desired value is in the startTime property of this object. Below is an example of what the trigger() expression returns as a JSON object for my Logic App, which is triggered by an HTTP call. This should be similar for a message queue trigger:
{
  "name": "manual",
  "inputs": {
    "schema": {
      "properties": {
        "requestGUID": {
          "type": "string"
        }
      },
      "required": [
        "requestGUID"
      ],
      "type": "object"
    }
  },
  "outputs": {
    "headers": {
      "Accept": "*/*",
      "Host": "***.logic.azure.com",
      "User-Agent": "curl/7.79.1",
      "Content-Length": "54",
      "Content-Type": "application/json"
    },
    "body": {
      "requestGUID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    }
  },
  "startTime": "2022-02-22T02:14:47.5168196Z",
  "endTime": "2022-02-22T02:14:47.5168196Z",
  "trackingId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "clientTrackingId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "originHistoryName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "status": "Succeeded"
}

Based on this object and which referencing notation you prefer, you could get the Logic App start date & time (UTC) using the formula @trigger().startTime or @trigger()?['startTime'].

A: For now no directly action or function to get the startTime property, however you could use Rest API in runtime with Correlation ID to get it. This is the api description :Workflow Runs - Get.
The Resource Group name and the workflow name are static and the Correlation ID is dynamic you could use workflow()['run']['name'] to get it. And then use body('HTTP')['properties']['startTime'] to get time from response.
The below is my flow.

And this is the result, cause the timezone so thy are 8 hours apart.

Hope this could help you.


text:
Q: WP_Query с возможностью фильтрации У меня есть страница с фильтром по атрибутам, который работает по методу GET.
То есть, при отправке формы фильтра, в адресной строке появляется
https://apyachts.com/buy/?pa_build-year=2019&pa_builder=absolute

Я сделал WP_Query для вывода товаров
<?php $builder = $_GET['pa_builder'];
$year = $_GET['pa_build-year'];

$related_yachts = new WP_Query( array(
    'post_type'      => 'product',
    'posts_per_page' => 9,
    'tax_query' => array(
        'relation' => 'AND',
        array(

        'taxonomy' => 'product_cat',
                        'field' => 'id',
                        'terms' => 20

        ),

        array(

        'taxonomy' => 'pa_builder',
        'terms' => $builder,
        'field' => 'slug',
        'operator' => 'IN',
        ),

        array(

        'taxonomy' => 'pa_build-year',
        'terms' => $year,
        'field' => 'slug',
        'operator' => 'IN',
        ),

    ),

    )); ?>

Но когда GET-запросов нет и фильтр не отправлял никаких данных, он не выводит товаров.
И если в фильтре указан лишь один атрибут ( pa_builder или pa_build-year), то тоже ничего не выводит, хотя должен выводит с одним параметром.
Как сделать грамотно? Спасибо!


text:
Q: Is it possible to replace member function to a noop function? I write c++ with c++11 and have a question as title.
Ex.
class Hi {
public:
Hi(){};
test() {cout << "test" << endl;};
}

void noop(){
; // noop
};

int main(){
 Hi hi();
 hi.test = noop; // just example, not real case

 return 0;
}

Is that possible to replace test() of class Hi to a noop function in runtime!? Thanks.

A: You can't replace any function at runtime, whether class member or not.
However, you can achieve the desired effect by using a variable.
(This is yet another example of the "add a level of indirection" method of solving problems.)
Example:
class Hi {
public:
    Hi(): test([this]() { do_test(); }) {}
    std::function<void()> test;
    void do_test() { cout << "test" << endl; }
};

void noop(){}

int main(){
 Hi hi;
 hi.test(); // Outputs 'test'
 hi.test = noop;
 hi.test(); // Does nothing
}

A: You have to think object oriented. In this case you have to elevate your function to be an object we can name it MethodClass then your function in the class Hi will be a pointer to that class. Below a simple example
#include <memory>

class BaseMethodClass
{
public:
    virtual void method() = 0;
};

class MethodClass1 : public BaseMethodClass
{
public:
    virtual void method()
    {
        // your implementation here
    }
};

class MethodClass2 : public BaseMethodClass
{
public:
    virtual void method()
    {
        // your implementation here
    }
};

class Hi
{
public:
    Hi() { method = nullptr; };

    void setMethod(BaseMethodClass* m) { method.reset(m); }

    void test() { if (method) method->method(); };

private:
    std::shared_ptr<BaseMethodClass> method;
};

int main()
{
    Hi hi;
    hi.setMethod(new MethodClass1());
    hi.test();
    hi.setMethod(new MethodClass2());
    hi.test();

    return 0;
}

This way you can override your methos as you want not just noop


text:
Q: Android built-in browser and download This is driving me nuts. I want to offer an .apk file for download. All browsers I've tested will download my file without any problem. Except for the built-in browser in android. For some strange reason it will repeat the request for the resource. Using BurpSuite I've discovered that the apk file is transferred flawlessly. I proxy the file, but I send the headers right away, using curl I could confirm the headers are sent and the content starts being transmitted in the following. I've compared my headers with the headers sent by threema.ch which works flawlessly.
These headers are sent by my application:
HTTP/1.1 200 OK
Date: Sat, 16 Aug 2014 16:41:01 GMT
Server: Apache/2.4.7
Content-Disposition: attachment; filename="test.apk"
Content-Type: application/vnd.android.package-archive
Transfer-Encoding: Chunked

These headers are sent by Threema:
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 16 Aug 2014 17:49:10 GMT
Content-Type: application/vnd.android.package-archive
Content-Length: 14146751
Connection: keep-alive
Content-Disposition: attachment; filename="Threema-1.63.apk"
Strict-Transport-Security: max-age=31536000; includeSubdomains

I've first loaded the file through an iframe. Currently I'm redirecting the browser to the download using HTTP redirect. I offer the file from a different subdomain. But I also tried delivering the file from the same domain and using a html link.
These are the headers sent by the client. First:
GET /download/download/NlnMhaeXmcjSosfqRTcG8YdxQgQGSxTWQeE10-GrH4U HTTP/1.1
Host: l.dl.test
Proxy-Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Linux; Android 4.4.4; Nexus 7 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36
Referer: http://l.google/device/deviceid/351cd7c24f637eb5?token=6Xf3nJIIMIa4toKrpTqgDGFjAKzeBBoaeduMmcIMeGY
Accept-Encoding: gzip,deflate
Accept-Language: de-DE,en-US;q=0.8
X-Requested-With: com.android.browser

And then (around 20s later):
GET /download/download/NlnMhaeXmcjSosfqRTcG8YdxQgQGSxTWQeE10-GrH4U HTTP/1.1
User-Agent: Mozilla/5.0 (Linux; Android 4.4.4; Nexus 7 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36
Referer:
cookie:
Accept-Encoding: identity
Host: l.dl.test
Connection: Keep-Alive

I'm generating a download id for one time use. The second Request will fail, because the id becomes invalid after the first request. The download works if I permit the second attempt to download the file.
Might it be that the android browser wants compressed content in the first attempt and if it gets identity content it will make a second attempt using Accept-Encoding identity? I also tried setting Content-Encoding: identity without luck.
Workaround:
The only way I've got this working without sending the .apk twice is using this very stupid (and properly error-prone) workaround:
header("Content-Disposition: attachment; filename=\"test.apk\"");
header('Content-Type: application/vnd.android.package-archive');

// Ugly workaround for bug in built-in android browser.
if (
  isset($_SERVER['HTTP_X_REQUESTED_WITH'])
  && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'com.android.browser')
  && isset($_SERVER['HTTP_ACCEPT_ENCODING'])
  && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'identity') === FALSE)
) {
    // The built-in android browser will make two requests for the apk
    // file, one with Accept-Encoding gzip and deflate and one with
    // Accept-Encoding identity. But it will only serve the second request
    // with Accept encoding identity. So stop the first request.

    // If the first request is shown, the workaround didn't work.
    die ("Oh no! I'm sorry. The built-in android browser has a nasty bug."
    . " It's hard to work around. If you see this the workaround failed."
    . " Please try downloading with a different browser.");
}