Q: Set color of alertdialog I display an alertdialog in my app but the left and right side of the title shows a different color. I have set my own background color in thems.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="ACCAppTheme" parent="android:Theme.Holo">
    <!-- Change default text colour from dark grey to black -->
    <!-- <item name="android:windowBackground">@drawable/ic_logo</item> -->
    <item name="android:background">#140051</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:textColorHint">#c0c0c0</item>
    <item name="android:actionBarStyle">@style/AppTheme.ActionBar</item>
</style>

<!-- <style name="OverFlow" parent="@android:style/Widget.Holo.ActionButton.Overflow">
    <item name="android:textSize">18sp</item>
</style> -->

<style name="AppTheme.ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">#140051</item>
    <item name="android:height">50dp</item>
    <item name="android:titleTextStyle">@style/AppTheme.ActionBar.Text</item>
    <item name="android:textColor">@android:color/white</item>
    <item name="android:showDividers">beginning</item>
</style>

<style name="AppTheme.ActionBar.Text" parent="@android:style/TextAppearance">
    <item name="android:textAllCaps">false</item>
    <item name="android:textColor">@android:color/white</item>
</style>
</resources>

but what appears is like this

here's the code that creates the alert dialog
public class AppMessages {
public static final int MESSAGE_INFO = 1;
public static final int MESSAGE_CRITICAL = 2;

public interface AlertButtonClickListener {

    public abstract void onButtonClicked(boolean value);

}

public static void showMessage(Context context,
                                String message,
                                String title,
                                int messageType,
                                final AlertButtonClickListener target) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message)
            .setTitle(title)
            .setIcon(R.drawable.ic_dialog_information)
            .setCancelable(false)
            .setPositiveButton("Ok", new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (target != null) {
                        target.onButtonClicked(true);
                    }
                }
            });

    switch (messageType) {
    case AppMessages.MESSAGE_CRITICAL:
        builder.setIcon(R.drawable.ic_dialog_exclamation);
        break;
    case AppMessages.MESSAGE_INFO:
        builder.setIcon(R.drawable.ic_dialog_information);
        break;
    }

    builder.show();
}

public static void yesNo(final Context mContext,
                        final String title,
                        final String msg,
                        final String positiveBtnCaption,
                        final String negativeBtnCaption,
                        final boolean isCancelable,
                        final AlertButtonClickListener target) {

        ((Activity) mContext).runOnUiThread(new Runnable() {

        @Override
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

            builder.setTitle(title)
                    .setMessage(msg)
                    .setIcon(R.drawable.ic_dialog_question)
                    .setCancelable(false)
                    .setPositiveButton(positiveBtnCaption,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    target.onButtonClicked(true);
                                }
                            })
                    .setNegativeButton(negativeBtnCaption,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    target.onButtonClicked(false);
                                }
                            });

            AlertDialog alert = builder.create();
            alert.setCancelable(isCancelable);
            alert.show();
            if (isCancelable) {
                alert.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        target.onButtonClicked(false);
                    }
                });
            }
        }
    });

}
}

here's how I call the it
AppMessages.showMessage(thisActivity,
                                    "New update found. Click Ok to download it now.",
                                    "New Update Found",
                                    1,
                                    new AppMessages.AlertButtonClickListener() {
                                        @Override
                                        public void onButtonClicked(boolean value) {
                                            APKDownloader.downloadAPK(thisActivity);
                                        }
                                    });

A: Try this,
Customize AlertDialog Theme
Create a new Android XML resource file under res/values/
You'll want to create a new style that inherits from the default alertdialog theme:
<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog">
    <item name="android:bottomBright">@color/white</item>
    <item name="android:bottomDark">@color/white</item>
    <item name="android:bottomMedium">@color/white</item>
    <item name="android:centerBright">@color/white</item>
    <item name="android:centerDark">@color/white</item>
    <item name="android:centerMedium">@color/white</item>
    <item name="android:fullBright">@color/orange</item>
    <item name="android:fullDark">@color/orange</item>
    <item name="android:topBright">@color/blue</item>
    <item name="android:topDark">@color/blue</item>
</style>

You can specify either colors or drawable for each section of the AlertDialog.
An AlertDialog will build it's display by combining 3 drawables/colors (top, center, bottom) or a single drawable/color (full).
In a theme of your own override the android:alertDialogStyle style (you can do this within the same XML file):

    @style/CustomDialogTheme

Override your application's theme in the AndroidManifest within the application tag:
<application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/MyTheme">

Now that you've defined your application's theme, any attributes overridden in your theme will resonate throughout your app.
For example if you also wanted to change the color of your application's title bar:
You would first define a  new style that inherits from the default attribute

    @color/blue

and just add the new overridden item to your theme:
<style name="MyTheme">
    <item name="android:windowTitleBackgroundStyle">@style/MyBackground</item>
    <item name="android:alertDialogStyle">@style/CustomDialogTheme</item>
</style>


Q: Embedding tab bar to top of screen iphone I want to design a page with tab bar on top of it.In some articles of this site.(i missed urls) i found that this is not a common way and the question gets some down rate.
The question is this: whethere having a design like this may cause that apple not approve the application on his store?

A: Even if it doesn't make Apple reject your app, think of the users not being used to the tab bar being at the top and how that is going to affect how well the app does in the Store.
Every platform has its own design patterns and there is a reason for that. If you stick to them there is a higher chance that the first-time users have an easier time using your app, which results in a higher chance that they keep using it. If they don't know how to use it or find it hard, they will move to another one.
Take a look at the Human Interface Guidelines and apply them. It will do good.


Q: Terraform: aws_lb_listener with multiple ports I am building an ALB on AWS using Terraform. The ALB should forward multiple ports to the instances, but the documentation specifies:

port - (Required) The port on which the load balancer is listening.

Do I have to add a separate ALB listener for each port, or is there a way to specify multiple ports per listener?

A: An ALB listener can only listen on a single port. You must define a listener for each port you want the load balancer to listen on. This isn't a limitation of Terraform, it's the way AWS load balancers are designed.
Additionally, since an ALB can only handle HTTP and HTTPS requests you usually don't setup more than two listeners on an ALB (ports 80 and 443), and the listener configuration would of necessity be different since one would have an SSL certificate configuration and one would not.


Q: Use multiple checkbox selection while parsing JSON I'm trying to select multiple checkboxes in a custom listview while parsing JSON. Now I am able select a single checkbox. How can I select multiple checkbox values?


Q: python - regex putting repeating patterns in a single group I'm trying to parse a string in regex and am 99% there.
my test string is
 1
  1234 1111 5555 88945
    172.255.255.255 from 172.255.255.255 (1.1.1.1)
      Origin IGP, localpref 300, valid, external, best
      rx pathid: 0, tx pathid: 0x0

my current regex pattern is:
(?P<as_path>(\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>\S+,\s{0,4})

im using regex101 to test and have a link to the test here https://regex101.com/r/iGM8ye/1
So currently i have a group2 I don't want this group, could someone tell me why im getting this group and how to remove it?
and the second is, in the attributes I want to match the words, "valid, external, best" currently my pattern only matches "valid," I thought adding the repeat of within the group would of matched all three of those but it hasn't.
How would I achieve matching the repeat of "string, string, string," (string comma space) into one group?
Thanks
EDIT
Desired output
as_path : 1234 1111 5555 88945
peer_addr : 172.255.255.255
peer_rid : 1.1.1.1
local_pref : 300
attribs : valid, external, best

attiribs may also just be valid, external, or just external, or another entry in the format (stringcommaspace)

A: Try Regex: (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>[\S]+,(?: [\S]+,?)*){0,4}
Demo
Regex in the question had a capturing group (Group 2) for (\d{4,10}\s). it is changed to a non capturing group now (?:\d{4,10}\s)

A: See regex in use here.
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}(?:\.\d{0,3}){3}).*\((?P<peer_rid>\d{0,3}(?:\.\d{0,3}){3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2})

*

*You were getting group 2 because your as_path group contained a group. I changed that to a non-capturing group.

*I changed attribs to \S+(?:,\s+\S+){2}

*

*This will match any non-space character one or more times \S+, followed by the following exactly twice:

*

*,\s+\S+ the comma character, followed by the space character one or more times, followed by any non-space character one or more times

*I changed peer_addr and peer_rid to \d{0,3}(?:\.\d{0,3}){3} instead of \d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}. This is a preference, but shortens the expression.

Without that last modification, you can use the following regex (it performs slightly better anyway (as seen here):
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2})

You can also improve the performance by using more specific tokens as the following suggests (notice I also added the x modifier to make it more legible) and as seen here:
(?P<as_path>\d{4,10}(?:\s\d{4,10}){0,19})\s+
(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})[^)]*
\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+
.*localpref\s(?P<local_pref>\d+),\s+
(?P<attribs>\w+(?:,\s+\w+){2})

A: You get that separate group because your are repeating a capturing group were the last iteration will be the capturing group, in this case 88945 You could make it non capturing instead (?:
For the second part you could use an alternation to exactly match one of the options (?:valid|external|best)
Your pattern might look like:
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>(?:valid|external|best)(?:,\s{0,4}(?:valid|external|best))+)

regex101 demo


Q: Why json_encode create new line after password_verify php and create error in android studio I'm new in php, now i want to create json_encode and use it as API to my android apps, but after i try it on android, the log say that

Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

and the postman shows one line after the json response. how to eliminate the new line (line two) which is not contain anything.
This is my response in postman:
1 {"kode":1,"pesan":"Login Berhasil"}
2

picture spoiler :
https://imgur.com/a/fKi0a72
thank you for all your response afterwards
i have tried to change code in php to fetch the password row several time but always produce second line.
 $konek = new Mysqli($HostName, $HostUser, $HostPass, $DatabaseName) or die(Mysqli_errno());

 if($_SERVER['REQUEST_METHOD'] == 'POST')
 {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $role = $_POST['role'];

    $sql = "SELECT * FROM user WHERE email= '$email'";
    $result = $konek->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
                if(password_verify($password, $row['password'])){
                echo json_encode(array('kode' =>1, 'pesan' => 'Login Berhasil'));
                } else {
                    echo json_encode(array('kode' =>2, 'pesan' => 'Login Gagal. Periksa Email atau password'));
                }
        }
     }
 }
else{
    echo json_encode(array('kode' =>101, 'pesan' => 'Login Error '));
}

This is my response in postman:
1 {"kode":1,"pesan":"Login Berhasil"}
2

A: try to see output in json instead of html because in my Postman it is displayed correctly.
you should set Content type of Response of API to json to avoid any issues like this.
If doesn't help please comment with output as json in postman.


Q: Rails ActiveRecord query using multiple joins involving polymorphic association I'm trying to figure out how I can replicate the following SQL query using AR given the model definitions below. The cast is necessary to perform the average. The result set should group foo by bar (which comes from the polymorphic association). Any help is appreciated.
SQL:
SELECT AVG(CAST(r.foo AS decimal)) "Average", s.bar
FROM rotation r INNER JOIN cogs c ON r.cog_id = c.id
           INNER JOIN sprockets s ON s.id = c.crankable_id
           INNER JOIN machinists m ON r.machinist_id = m.id
WHERE c.crankable_type = 'Sprocket' AND
      r.machine_id = 123 AND
      m.shop_id = 1
GROUP BY s.bar

ActiveRecord Models:
class Rotation < ActiveRecord::Base
    belongs_to :cog
    belongs_to :machinist
    belongs_to :machine
end

class Cog < ActiveRecord::Base
    belongs_to :crankable, :polymorphic => true
    has_many :rotation
end

class Sprocket < ActiveRecord::Base
    has_many :cogs, :as => :crankable
end

class Machinist < ActiveRecord::Base
    belongs_to :shop
end

UPDATE
I've figured out a way to make it work, but it feels like cheating. Is there are a better way than this?
Sprocket.joins('INNER JOIN cogs c ON c.crankable_id = sprockets.id',
               'INNER JOIN rotations r ON r.cog_id = c.id',
               'INNER JOIN machinists m ON r.machinist_id = m.id')
    .select('sprockets.bar', 'r.foo')
    .where(:r => {:machine_id => 123}, :m => {:shop_id => 1})
    .group('sprockets.bar')
    .average('CAST(r.foo AS decimal)')

SOLUTION
Albin's answer didn't work as-is, but did lead me to a working solution. First, I had a typo in Cog and had to change the relation from:
has_many :rotation

to the plural form:
has_many :rotations

With that in place, I am able to use the following query
Sprocket.joins(cogs: {rotations: :machinist})
    .where({ machinists: { shop_id: 1 }, rotations: { machine_id: 123}})
    .group(:bar)
    .average('CAST(rotations.foo AS decimal)')

The only real difference is that I had to separate the where clause since a machine does not belong to a machinist. Thanks Albin!

A: I think this code is a little simpler and taking more help from AR
Sprocket
.joins(cogs: {rotations: :machinist})
.where({ machinists: { machine_id: 123, shop_id: 1 } } )
.group(:bar)
.average('CAST(rotations.foo AS decimal)')

The select clause was unnecessary, you don't have to select values since you only need them internally in the query, AR helps you decide what you need afterwards.
I tested this out using a similar structure in one of my own projects but it is not the exact same models so there might be a typo or something in there if it does not run straight up. I ran:
Activity
.joins(locations: {participants: :stuff})
.where({ stuffs: { my_field: 1 } })
.group(:title)
.average('CAST(participants.date_of_birth as decimal)')

producing this query
SELECT AVG(CAST(participants.date_of_birth as decimal)) AS average_cast_participants_date_of_birth_as_decimal, title AS title
FROM `activities`
INNER JOIN `locations` ON `locations`.`activity_id` = `activities`.`id`
INNER JOIN `participants` ON `participants`.`location_id` = `locations`.`id`
INNER JOIN `stuffs` ON `stuffs`.`id` = `participants`.`stuff_id`
WHERE `stuffs`.`my_field` = 1
GROUP BY title

which AR makes in to a hash looking like this:
{"dummy title"=>#<BigDecimal:7fe9fe44d3c0,'0.19652273E4',18(18)>, "stats test"=>nil}


Q: I am unable to get show different devices both audio and video available during stream I was just going through https://github.com/ScaleDrone/webrtc/blob/master/script.js but there is no way i could select from the devices and stream
navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true,
  }).then(stream => {
    // Display your local video in #localVideo element
    localVideo.srcObject = stream;
    // Add your stream to be sent to the conneting peer
    stream.getTracks().forEach(track => pc.addTrack(track, stream));
  }, onError);

how do i get all the device id shown for both video as well as audio source . please helpp me anyone
i just want that all device id should be shown and i can select any one from them.
I actually mean to say that when i use this on my phone it only selects my front camera . but what command should i insert here so that i can move to my rear camera or any other camera device attached and same is the case of audio, there are no audio devices to select from

A: I think you are looking for enumerateMediaDevices it seems to be implemented on all recent browsers (Not IE).


Q: Can you mix string and object outputs in SQL JSON? I'm trying to construct a JSON-serialized list of key/value pair items from my SQL database (compat level 140).  The trick is that the values can be anything: numbers, strings, null, or other JSON objects.
It should be able to look something like this:
[{"key":"key1","value":"A String"},{"key":"key2","value":{"InnerKey":"InnerValue"}}]

However, SQL seems to be forcing me to select either a string or an object.
SELECT
       [key] = kvp.[key],
       [value] = CASE
              WHEN ISJSON(kvp.[value]) = 1 THEN JSON_QUERY(kvp.[value])
              ELSE '"' + kvp.[value] + '"'  -- See note below
              END
FROM (VALUES
        ('key1', 'This value is a string')
       ,('key2', '{"description":"This value is an object"}')
       ,('key3', '["This","value","is","an","array","of","strings"]')
       ,('key4', NULL)

       -- Without these lines, the above 4 work fine; with either of them, even those 4 are broken
       --,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
       --,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH

Am I trying to do something that SQL can't support, or am I just missing the proper syntax for making this work?
*Note that the addition of the double-quotes seems like it shouldn't be necessary.  But without those, SQL fails to wrap the string and generates bad JSON:
[{"key":"key1","value":This value is a string},...

A: If your query is modified to this, it works:
SELECT
   [key] = kvp.[key],
   [value] = ISNULL(
          JSON_QUERY(CASE WHEN ISJSON(kvp.[value]) = 1 THEN kvp.[value] END),
          '"' + STRING_ESCAPE(kvp.[value], 'json') + '"'
   )
FROM (VALUES
   ('key1', 'This value is a "string"')
   ,('key2', '{"description":"This value is an object"}')
   ,('key3', '["This","value","is","an","array","of","strings"]')
   ,('key4', NULL)

   -- These now work
   ,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
   ,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH, INCLUDE_NULL_VALUES

Of course, this wouldn't be sufficient if value was an int. Also, I can't really explain why yours doesn't work.


Q: function that moves capitals to the front of a string and capitalizes lowercase letters? I'm trying to make a function that takes in a string as an input. It then moves the capital letters in the string to the front, and capitalizes lower-case letters. Lower-case letters and spaces should be kept in the same position relative to their location in the original string.
For example:
unravel_message(' neHAw moPPnthY')

should return 'HAPPY NEW MONTH' as the output.
and unravel_message('ALL CAPITALS')
should return 'ALLCAPITALS ' as the output.
(the space remains in the same location; only the capitals are moved back)
My Attempt:
def unravel_message(word):
    return ''.join([i for i in word if i == i.upper()]) + ''.join([i.upper() for i in word if i == i.lower()])

for my function, unravel_message(' neHAw moPPnthY') outputs ' HA PPY NEW MONTH'. Which isn't quite right. I think this may be because of the ''.join(). I would like to revise this function to use a single list comprehension wihtout imports if possible. If the inputs are all lowercase, I would also like to include an assertion statement addressing an error but I'm not sure how to do this.

A: Timsort is stable, which means that you can get what you want with something like
>>> assert not message.islower()
>>> ''.join(sorted(message, key=lambda c: not c.isupper())).upper()
'HAPPY NEW MONTH'

The trick is that booleans are a subclass of integers in python. The key returns False == 0 for elements you want to move to the beginning, and True == 1 for elements that stay. You need to use lambda c: not c.isupper() because spaces and other characters will move back if you use str.islower as the key.
If you want the assertion to be more detailed, like checking if all the letter characters are lowercase, you can do it with something like
>>> assert any(c != c.lower() for c in message)

For more complex unicode code points, use c.casefold() instead of c.lower().

A: Here is a solution that uses a single list comprehension without imports. It is also linear in time with the length of the string unlike sorting solutions with have higher time complexity of O(n log n). It also has an assertion statement flagging strings with no uppercase letters (i.e., all alpha characters are lowercase).
def unravel_message(s):
    assert any('A' <= c <= 'Z' for c in s)
    return (duo := list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s]))))[0] + duo[1]

x = unravel_message(' neHAw moPPnthY')
print(x)
x = unravel_message(' no uppercase letters')

Output:
HAPPY NEW MONTH
Traceback (most recent call last):
  File "C:\python\test.py", line 7, in <module>
    x = unravel_message(' no uppercase letters')
  File "C:\python\test.py", line 2, in unravel_message
    assert any('A' <= c <= 'Z' for c in s)
AssertionError

Note that the solution uses the walrus operator := to make it a one-liner. If you are using Python earlier than version 3.8, you can do this instead:
def unravel_message(s):
    assert any('A' <= c <= 'Z' for c in s)
    duo = list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s])))
    return duo[0] + duo[1]


Q: Which one is better in terms of Speed and memory usage or simply best practice I have a function with a lot of constant variables inside. Would it be better to store these variables in a Hash-map (it would be a complicated one) (it would have hash-maps inside the Hash-map. Or several if, else if clauses. In terms of readability they're about the same. But What I'm worried about is the memory taken and the speed of the app. This is a extremely simplified version of the problem :
function myFunction(data) {
    var a = 0, b = 0, c = 0, d = 0;
    if(data == value1) {
        a += 3;
        if(value1Fetched) {
           b += 6;
           c +=2;
           d +=1;
        }
    } else if (data == value2) {
        a += 1;
        if(value2Fetched) {
           b += 4;
           c +=9;
        }
    }
return a+b+c+d;
}

Obviously there are way more flags and values (and Data is a Hash-map too)
version 2 :
function myFunction(data) {
    var a = 0, b = 0, c = 0, d = 0;
    var myHash = {
        value1: {
            a: 3,
            b: 6,
            c: 2,
            d: 1
        },
        value2: {
            a: 1,
            b: 4,
            c: 9,
            d: 0
        }
    };
    a += myHash[data][a];
    if(isFetched(data)){
        b += myHash[data][b];
        c += myHash[data][c];
        d += myHash[data][d];
    }
return a+b+c+d;
}

Sorry for the messy (pseudo)code, i tried to make it as readable as possible.
This has been haunting me for days and everyone at work has a different opinion.

A: I would say the extensibility of the second question far outweighs any possible (and unlikely) performance issues. You can even change that structure on the fly if needed, or have multiple instances for two environments where the mapping turns out different.
It might be slower for examples as small as the one you posted, but it sounds like the actual might have a great many entries, in which case using a map lookup has O(log(n)) complexity rather than O(n) (hope I have those terms correct! Been a while since college). Large JSON objects (string-maps) are not uncommon in JavaScript, in fact you often work with them for the libraries and browser features in common code.


Q: Apache httpd.conf file: How to add condition to check url is HTTPS or HTTP I want to set "SameSite" and "Secure" as follows in httpd.conf file, only if url is https only.
How can add condition to check if url is https or http
Header always edit Set-Cookie (.*) "$1; SameSite=None; Secure"
Header onsuccess edit Set-Cookie (.*) "$1; SameSite=None; Secure
I have tried following solutions but didn't help:
<If "reqenv('HTTPS') == 'on'">
SetEnvIf HTTPS "on" HAS_HTTPS
SetEnvIfExpr "tolower(req('HTTPS')) =='on'" HAS_HTTPS


Q: Failed to call a dynamic method in a static context? These are created using Android Studio similar to How to modify dummy content in android master/detail activity?. I changed the static method under dummyContent into below:
public void fetchData() {
    // Add some sample items.
    for (int i = 1; i <= COUNT; i++) {
        addItem(createDummyItem(i));
    }

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    DummyContent.UNAME, DummyContent.PASSWORD.toCharArray());
        }
    });

    try {
        DummyContentRegistry registry = new XMLDummyContentParser(DummyContent.url).parse();
        for (DummyContent.DummyItem t: registry.getTeachers()) {
            DummyContent.addItem(t);
        }
    } catch (Exception e) {
        fail("Exception should not have been thrown");
    }
}

while above passed the test:
public class DummyContentRegistryTest {
    @Before
    public void buildRegistry() {}

    @Test
    public void testFetchData() {
        Assert.assertEquals(0,DummyContent.ITEMS.size());
        new DummyContent().fetchData();
        Assert.assertEquals(27,DummyContent.ITEMS.size());// two more items are added through parsing xml on a website
    }

}

However when I call the method under MainActivity.onCreate it failed "Exception should not have been thrown". Why? Here's an example of failing call
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (DummyContent.ITEMS.isEmpty()) {
        new DummyContent().fetchData();
    }
......
}

I don't know if the problem is similar to calling non-static method in static method in Java but I've obviously tried the way most of them agreed.
    [ 07-25 04:04:56.442 23983:24025 D/         ]
                                                                                HostConnection::get() New Host Connection established 0x7f1b57910500, tid 24025
07-25 04:04:56.460 23983-24025/*****private*****.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-25 04:04:56.873 23983-23983/*****private*****.myapplication I/Choreographer: Skipped 32 frames!  The application may be doing too much work on its main thread.
07-25 04:05:07.474 23983-23983/*****private*****.myapplication W/System.err: java.io.IOException: Couldn't open *****private*****
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.dummy.XMLDummyContentParser.parse(XMLDummyContentParser.java:33)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.dummy.DummyContent.fetchData(DummyContent.java:53)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:52)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.Activity.performCreate(Activity.java:6237)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: Caused by: android.os.NetworkOnMainThreadException
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:    ... 18 more
07-25 04:05:07.483 23983-23983/*****private*****.myapplication D/AndroidRuntime: Shutting down VM

07-25 04:05:07.484 23983-23983/*****private*****.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: ******private*******, PID: 23983
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{******private*******.myapplication.MainActivity}: java.lang.IllegalStateException: Already attached
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Caused by: java.lang.IllegalStateException: Already attached
                                                                                at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2126)
                                                                                at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
                                                                                at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:313)
                                                                                at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
                                                                                at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:55)
                                                                                at android.app.Activity.performCreate(Activity.java:6237)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: The Exception e, which you catch may contain useful information on what exactly went wrong. Do e.printStackTrace(); inside your catch-block to print all available information to the standard output.
If that does not help you solve the problem post the stacktrace here.

A: You cannot manipulate UI thread from background thread thats why you are getting this error.
ClassName.this.runOnUiThread(new Runnable() {
                public void run() {
                //Do something on UiThread

                // enclose your UI manipulated code here in these braces.
            }
        });


Q: How can I get the number of pages in a PDF file inside a Google Apps Script? The PDF files are in my Google Drive. I just got that I can get the number of pages of a PDF sending it as a job to Cloud Print, because Cloud Print will return a JSON object with "numberOfPages" attribute.
Is there any faster and easier way? Thanks in advance.

A: Well, I actually did like I said.
I take my file, then send it to CloudPrint via its JSON Api. I need to send it to a dummy printer, a printer I registered in CloudPrint but actually is never connected to Internet. Then, I get the number of pages of the PDF file in the value of response's "numberOfPages" attribute. Save this number in some var. Finally, I send a delete petition to JSON Api for my file in the dummy printer, indeed isn't necessary at all.
Thanks!


Q: Bash script in raspbian runs manually, won't run in cron Trying to turn a small TV into a photo frame so to speak, so I have a Raspberry Pi and I have a bash script at /home/pi/scripts/script.sh:
#!/bin/sh
sudo /usr/bin/gpicview /home/pi/Downloads/test_5_25.png >> /home/pi/Downloads/test.log

My cron tab looks like this:
    # m h  dom mon dow   command
* * * * * sh /home/pi/scripts/script.sh
My syslog shows that its running:
May 27 04:32:01 raspberrypi /USR/SBIN/CRON[2999]: (pi) CMD (sh /home/pi/scripts/script.sh

But gpicview is not opening like when I run the script manually, and in my error log it shows...

option parsing failed: Cannot open display:

I thought maybe permissions or something, but I've double checked those to the best of my ability and cannot figure it out. Any clues would be greatly appreciated!!

A: You probably need to set the display manually, i.e.:
* * * * * export DISPLAY=:0 && sh /home/pi/scripts/script.sh

As outlined in this article.


Q: Out-Of-Browser Service Access problem using Silverlight 4 I have a Silverlight 4 application that access a couple of WCF Data Services.
There are no problems accessing the service through the browser.
I set the program to run out-of-browser with elevated trust.  Then I can see the calls to the WCF Service via fiddler, but nothing ever comes back.
If I debug then I get the following error:
$exception  {System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at System.Windows.Controls.ItemCollection.GetValueInternal(DependencyProperty dp)
   at System.Windows.PresentationFrameworkCollection`1.get_CountImpl()
   at System.Windows.PresentationFrameworkCollection`1.get_Count()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.OnRefresh()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.ClearItems()
   at System.Collections.ObjectModel.Collection`1.Clear()
   at ClientFolderExplorer.ViewModels.DocumentExplorerViewModel.clientCatalog_ClientsLoadingComplete(Object sender, ClientLoadingEventArgs e)
   at ClientFolderExplorer.Catalogs.ClientCatalog.<>c__DisplayClass3.<ExecuteClientQuery>b__2(IAsyncResult a)}  System.Exception {System.UnauthorizedAccessException}

Not sure where to start troubleshooting.  I have crossdomain.xml and clientaccesspolicy.xml files in place in the root of the webserver, but I cannot even see these files being requested (in fiddler).
Any Ideas?

A: Yes - you suppose the problem is related to cross-site access, while in reality it's related to cross-thread access (first line of error indicates this clearly).
I'm assuming you're trying to set some UI element's data bound (or not, doesn't matter) property directly from the callback handling the service call. (edit) Forgot to clarify - where the callback is running on a thread different from the UI thread. Silverlight like most other frameworks disallows modifying UI except from the UI thread.
If so, take a look at how to use Dispatcher in order to switch back to the UI thread.


Q: Laravel much better of using if so most of time i do this
@if(!empty($variable)
  @if($variable == "yes")
      do something here
  @endif
@endif

well as you can see it really not a beautiful way, maybe (i really hope there is) a much simpler way to just detect if the variable is exist and not throwing error when it is not exist beside that...?
it making my code so crowded and if by anychance i forgot to add those will got beautiful error (well i design a eye cathing error page by the way)
@if(!empty($variable))
or
@if(isempty($variable))

A: Combine the two checks into a single if statement:
@if (! empty($variable) && $variable == 'yes')
    do something here
@endif

A: if you are searching for one line condition, it will work as expected,
  {{!empty($variable) ? $variable == 'yes' ? 'do something' : 'do something else' : 'variable is empty'}}


Q: C function macro to take NSString placeholders In my IOS-Project, I have a custom Logger-class (singleton) containing the function
- (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message

which is globally available through the following preprocessor macro:
#define MyLog(domain, level, message) [[MyLogger sharedInstance] log:domain logLevel:level logMessage:message]

Now when I make the call:
MyLog(@"common", LL_ERROR, @"There was an error!");

Everything works fine. But in practice, the logMessage will sometimes contain string placeholders. So the big question is:
How can I make my macro accept calls like
MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]);

With the current solution, Xcode complains: "Too many arguments provided to function-like macro invocation".

A: First, you have to change your log method to take a "variable argument list",
for example like this:
- (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message, ...
{
    va_list argList;
    va_start(argList, message);
    NSString *fullMessage = [[NSString alloc] initWithFormat:message arguments:argList];
    va_end(argList);

    NSLog(@"domain:%@, level:%d: %@", domain, level, fullMessage);
}

Then you have to change your MyLog macro to work with a variable number of arguments.
This is a GNU feature (http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html), that works
with Clang as well:
#define MyLog(domain, level, message, ...) \
   [[MyLogger sharedInstance] log:domain logLevel:level logMessage:message, ##__VA_ARGS__]

Now
MyLog(@"common", LL_ERROR, @"There was an error!");
MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]);

should both work without problems.


Q: Requires API level 21 (current min is 16) I'm new in android development and programming. I'm working on android camera application. I'm new in this so I use the lectures of a youtuber who uses API level 21 and I'm using API level 16 for maximum users but our code is same which causes a problem.

call requires API level 21 (current min is 16):android.hardware.camera2.CameraDevice.StateCallback#StateCallback more...CTRL + f1)
Please help me to fix this. I don't want to change its API level to 21.

A: Use 'android.hardware.camera' instead of 'android.hardware.camera2' API and that allows you to use that API with API level 16.


Q: Best practices on upgrading cassandra I am getting errors from pyspark connecting to cassandra because it appears I am using a too old a cassandra:
[idf@node1 python]$ nodetool -h localhost version
ReleaseVersion: 2.0.17
[idf@node1 python]$

[idf@node1 cassandra]$ java --version
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
[idf@node1 cassandra]$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
[idf@node1 cassandra]$

I want to upgrade to the latest version. However, I have already collected quite a bit of data and I don't want to lose it. I am using CentOS 7.2 with a single cassandra node. My questions are,

*

*where is the cassandra data stored on the local file system

*is it correct to assume that I can compress this directory and move it?

Then once I have the data backed up, what is the correct way to upgrade cassandra? Is it

*

*remove old version completely

*install new version

*copy data back

What is the best practice to do this?

A: I'm guessing you are using OSS version. Default location for data is /var/lib/cassandra and you can backup it if you wan't.
Procedure for upgrade is simple:

*

*run nodetool drain

*stop cassandra

*save your cassandra.yaml

*remove old and install new version

*update new cassandra.yaml with your settings

*start cassandra

*run nodetool ugradesstables

This should leave you with your node running the new version of cassandra with all your schema and data in it.
Be careful if you are upgrading past 2.1 because 2.2 and up require java8. Everything else is the same.


Q: cake php form containing file upload not adding enctype="multipart/form-data" attribute I have a controller Job and controller User
I want to send post data from the view of Job Controller  to User controller
the form contains file upload option too
$this->Form->create('User',array('url'=>array('controller'=>'Users','action'=>'newUser')),array('type' =>'file','enctype'=>'multipart/form-data'))

it will give the out put
<form action="/User/newUser" id="UserViewForm" method="post" accept-charset="utf-8">

but it is not adding attribute of enctype="multipart/form-data"
to form

A: Try this
$this->Form->create('User',
array('type' => 'file', 'class' => 'classname', 'url'=>array('controller'=>'Users','action'=>'newUser') ) );

You don't need to create a separate array for the all options.
Docs: Form Options

A: <?php
echo $this->Form->create('User', array('url' => array('controller' => 'Users','action' =>'newUser'),'class'=>'classname','enctype'=>'multipart/form-data'));
?>


Q: how to schedule a notification using firebase messaging I am trying to push a schedule notification to a group of people using firebase messaging, but the only resources I found were for flutter_local_notifications with the scheduling feature. which, as far as I know, work only for the same device I work with and do not send the notification to other devices.
I tried to customize the local schedule notification to send notifications to other devices but I did not know where to add the tokens for other devices


Q: Create waveform with pyaudio and matplotlib in real time I'm looking for a real time graph of an audio input (microphone) and show this data in a waveform graph using matplotlib. How can I show the data on Y axes and the time (seconds) in X axes ?
I don't know anything for audio processing so I learned a lot with docs and examples but I still don't know how to make the graph react in real time.
from scipy.io import wavfile
from matplotlib import pyplot as plt
import numpy as np

# Load the data and calculate the time of each sample
samplerate, data = wavfile.read('audio.wav')
print(samplerate, data)
times = np.arange(len(data))/float(samplerate)

# Make the plot
# You can tweak the figsize (width, height) in inches
plt.figure(figsize=(30, 4))
print(data[:,0])
plt.fill_between(times, data[:,0], data[:,1], color='k')
plt.xlim(times[0], times[-1])
plt.xlabel('time (s)')
plt.ylabel('amplitude')
# You can set the format by changing the extension
# like .pdf, .svg, .eps
plt.savefig('plot.png', dpi=100)
plt.show()

I expect a waveform looking like that but, using my microphone instead of wav file. I tested other things but it was no so concluding...


Q: RegEx JavaScript: Match consecutive single line comments I am trying to write a RegEx to parse groups of single line comments.
Given this input:
//line 1
//line 2
//line 3

//line 4
//line 5
//line 6

I expect to have two matches: Lines 1-3 and 4-6. With my current RegEx (^\/\/[\S\s]+$) I have one match: Lines 1-6, although there is an empty line in between.
The problem is that \s matches any whitespace character, so the blank line is included. But at the same time, line break are part of the RegEx – but only when the line starts with //, so I am stuck.
How can I prevent the RegEx from matching the blank line?

A: You could try this one:
/(^\/\/[^\n]+$\n)+/gm

see here https://regex101.com/r/CrR9WU/1
This selects first the two / at the beginning of each line then anything that is not a newline and finally (at the end of the line) the newline character itself. There are two matches: rows 1 to 3 and rows 4 to 6. If you also allow "empty comment lines like // then this will do too:
/(^\/\/[^\n]*$\n)+/gm

Edit:
I know, it is a little late now, but Casimir's helpful comment got me on to this modified solution:
/(?:^\/\/.*\n?)+/gm

It solves the problem of the final \n, does not capture groups and is simpler. (And it is pretty similar to Jan's solution ;-) ...)

A: This is what modifiers are for:
(?:^\/{2}.+\n?)+

With MULTILINE mode, see a demo on regex101.com.

Broken apart, this says:

(?:       # a non-capturing group
    ^     # start of the line
    \/{2} # //
    .+    # anything else in that line
    \n?   # a newline, eventually but greedy
 )+       # repeat the group


Q: What is the cosine distance of something and itself? I'm playing with scipy's cosine distance. From what I've gathered, the closer a cosine distance is to 1, the more similar the vectors are. I got some unexpected results in a text mining project, so I decided to investigate the simplest case.
import numpy as np
import scipy.spatial
arr1 = np.array([1,1])
arr2 = np.array([1,1])
print scipy.spatial.distance.cosine(arr1, arr2)

My program prints 0.0.
Shouldn't the result be 1.0? Why or why not?

A: It is the cosine distance, not the cosine similarity.  A basic requirement for a function d(u, v) to be a distance is that d(u, u) = 0.
See the definition of the formula in the docstring of scipy.spatial.distance.cosine, and notice that the formula begins 1 - (...).  Your expectation of the function is probably based on the quantity in (...), but that expression is the cosine similarity.


Q: django: Invalid filter I got an article app and trying to make a custom filter, I have a directory called templatetags in article app, and a tags.py within that directory, here is the directory structure.
-manage.py(f)
-settings.py(f)
-articles(d)
 - templatetags(d)
  - tags.py(f)

On the templates, the articles have its own directory, all article templates extend from a base.html template, here is the template structure.
-base.html(f)
-articles(d)
 -index.html(f)

I load the tags in base.html {% load tags %} and use the custom filter in index.html and got the invalid filter error.
tags.py
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def space2Dash(s):
    return s.replace(' ', '_');

I just can't figure out what I did wrong.
edit:
I changed the filter name to abcfilter.py and I have the article app loaded in my settings.py
articles/index.html
 {% load abcfilter %}
 {{ "foo bar"|space2dash }}

the error:
Request Method: GET
Request URL:    http://localhost:8080/articles/
Django Version: 1.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid filter: 'space2dash'
Exception Location: ***/lib/python2.7/django/template/__init__.py in find_filter, line 363
Python Executable:  /usr/local/bin/python
Python Version: 2.7.1
Server time:    Sun, 10 Apr 2011 07:55:54 -0500

A: Just for reference, I solved the problem by moving
{% load ... %}

from the base template to the concrete template.
See also this post https://stackoverflow.com/a/10427321/3198502

A: To avoid loading the module in each template using {% load MODULE_NAME %}, you can add it as a 'builtin' in settings.py:
TEMPLATES = [
    {
        'OPTIONS': {
            ...
            ,
            'builtins': [
                ...
                'APP_NAME.templatetags.MODULE_NAME',
                ]
        },
    },
]

A: First off remove the semicolon after your replace.
Do you have a file called __init__.py (this is suppose to have 2 underscores before and after init, hard to format in editor.) under the templatetags directory?
Here is a good page with lots of info if you haven't looked yet.
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

A: I was nearly going nuts with this problem and none of the above answers helped.
If you have several apps, make sure that the file names containing your custom tags/filters are unique, prefereablyapp_name_filters.py. Otherwise Django will only load the custom filters from the app it finds matching first!


Q: LZ4 compression library in android app How do I use LZ4 compression library in my android application...
The main issue I'm facing is when i try to export a signed application package, the error which comes is
Warning: net.jpountz.util.UnsafeUtils: can't find referenced class sun.misc.Unsafe
When I directly run the application in my device, there is no issue, this error comes only when I try to export the application.


Q: Custom XPath rule raises violation in pmd but not in sonar I have a quite strange behavior.
I create a XPath rule for PMD 4.2.6 in a file named pmd-extensions.xml :
...
<rule name="AvoidPrintStackTrace-XPath"
  message="Avoid to use printStackTrace - XPath"
  class="net.sourceforge.pmd.rules.XPathRule">
  <description>Avoid to use printStackTrace - XPath</description>
  <properties>
    <property name="xpath">
     <value>
<![CDATA[
//Name[contains (@Image, "printStackTrace")]
]]>
     </value>
    </property>
  </properties>
  <example>
  <![CDATA[
    // don't do this!
    myException.printStackTrace()
   ]]>
   </example>
</rule>
...

I have an unit test validating this rule and working fine:
 ...
 @Before
 public void setUp() {
     addRule("rulesets/pmd-extensions.xml", "AvoidPrintStackTrace-XPath");
 }
 ...

But when I embed this rule in Sonar, the rule doesn't fire any violation while I expected one:
 ...
 <rule key="AvoidPrintStackStrace-XPath" >
  <name>AvoidPrintStackStrace-XPath</name>
  <configKey>rulesets/pmd-extensions.xml/AvoidPrintStackTrace-XPath</configKey>
  <category name="Usability"/>
  <description>Avoid to use printStackTrace - XPath</description>
 </rule>
 ...

And if I declare this rule directly in Sonar (with same XPath expression), the rule fire a violation as expected:
...
<rule key="AvoidPrintStackStrace-XPath-Sonar" priority="MAJOR">
 <name><![CDATA[AvoidPrintStackStrace-XPath-Sonar]]></name>
 <configKey><![CDATA[net.sourceforge.pmd.rules.XPathRule]]></configKey>
 <category name="Maintainability"/>
 <description>Avoid to use printStackTrace - XPath-Sonar</description>
 <param key="xpath" type="s">
  <description><![CDATA[XPath expressions.]]></description>
  <defaultValue>//Name[contains (@Image, "printStackTrace")]</defaultValue>
 </param>
 <param key="message" type="s">
  <description><![CDATA[Message to display when a violation occurs.]]></description>
  <defaultValue>Prevent use of printStackTrace</defaultValue>
 </param>
</rule>
...

What's wrong ?
Thanks.

A: You probably haven't added this new rule to the profile that you are using for your project.
The fact that you provided a "pmd-extensions.xml" file just means that you added this rule to the rule repository. But if you do not activate this rule on a single profile, it will remain inactive and will never get executed.


Q: XSLT, getting values not in order I have an XML like this
    <row>
        <col>1</col>
        <col>name1</col>
        <col>link1</col>
        <col>junk1</col>
        <col>value1</col>
    </row>
    <row>
       <col>2</col>
       <col>name2</col>
       <col>link2</col>
       <col>junk2</col>
       <col>value2</col>
    </row>

how do I write the XSLT to get this output? the third column in each row contains the link and the fourth value does not need to be printed in output

        1
        name1
        value1

        2
        name2
        value

A: Seeing your XSLT would help understand why you get unsorted output. But in any case, try <xsl:sort select="col/text()"/>.

A: The following XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" indent="yes"/>

   <xsl:template match="/table">
      <xsl:copy>
         <xsl:apply-templates select="row">
            <xsl:sort select="col[1]"/>
         </xsl:apply-templates>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="row">

            <xsl:value-of select="col[1]"/>

               <xsl:value-of select="col[2]"/>

            <xsl:value-of select="col[5]"/>

   </xsl:template>
</xsl:stylesheet>

When applied to the following input XML

    <row>
        <col>1</col>
        <col>name1</col>
        <col>link1</col>
        <col>junk1</col>
        <col>value1</col>
    </row>
    <row>
       <col>2</col>
       <col>name2</col>
       <col>link2</col>
       <col>junk2</col>
       <col>value2</col>
    </row>

will produce the following output

      1

         name1

      value1

      2

         name2

      value2

Do note the use of Attribute Value Templates (AVT) to set the href attribute for the a tag:

You can also do away with the xsl:sort should you just wish the order of the rows in the output to be the same as the order in input XML.


Q: STM32 DMA: bytes remaining in buffer, encoded? For quite a while now I've been struggling with DMA communication with two STM32 boards in some form or another. My current issue is as follows.
I have a host (a Raspberry Pi) running the following code, waiting for the board to initialise communication:
#include <fcntl.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    unsigned int usbdev;
    unsigned char c;
    system("stty -F /dev/ttyUSB0 921600 icanon raw");
    usbdev = open("/dev/ttyUSB0", O_RDWR);
    setbuf(stdout, NULL);
    fprintf(stderr, "Waiting for signal..\n");
    while (!read(usbdev, &c, 1));
    unsigned char buf[] = "Defend at noon\r\n";
    write(usbdev, buf, 16);
    fprintf(stderr, "Written 16 bytes\r\n");
    while (1) {
        while (!read(usbdev, &c, 1));
        printf("%c", c);
    }
    return 0;
}

Basically it waits for a single byte of data before it'll send "Defend at noon" to the board, after which it prints everything that is sent back.
The boards first send out a single byte, and then wait for all incoming data, replace a few bytes and send it back. See the code at the end of this post. The board can be either an STM32L100C or an STM32F407 (in practice, the discovery boards); I'm experiencing the same behaviour with both at this point.
The output I'm seeing (on a good day - on a bad day it hangs on Written 16 bytes) is the following:
Waiting for signal..
Written 16 bytes
^JDefend adawnon

As you can see, the data is sent and four bytes are replaced as expected, but there's an extra two characters in front (^J, or 0x5E and 0x4A). These turn out to be a direct consequence of the signal_host function. When I replace the character with something arbitrary (e.g. x), that is what's being output at that position. It is interesting to note that \n actually gets converted to its caret notation ^J somewhere along the road. It appears that this occurs in the communication to the board, because when I simply hardcode a string in the buffer and use dma_transmit to send that to an non-interactive host program, it gets printed just fine.
It looks like I've somehow miss-configured DMA in the sense that there's some buffer that is not being cleared properly. Additionally, I do not really trust the way the host-side program is using stty.. However, I've actually had communication working flawlessly in the past, using this exact code. I compared it to the code stored in my git history across several months, and I cannot find the difference/flaw.
Note that the code below uses libopencm3 and is based on examples from libopencm3-examples.
STM32L1 code:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/dma.h>

void clock_setup(void)
{
    rcc_clock_setup_pll(&clock_config[CLOCK_VRANGE1_HSI_PLL_32MHZ]);
    rcc_periph_clock_enable(RCC_GPIOA);
    rcc_periph_clock_enable(RCC_USART2);
    rcc_periph_clock_enable(RCC_DMA1);
}

void gpio_setup(void)
{
    gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
    gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}

void usart_setup(int baud)
{
    usart_set_baudrate(USART2, baud);
    usart_set_databits(USART2, 8);
    usart_set_stopbits(USART2, USART_STOPBITS_1);
    usart_set_mode(USART2, USART_MODE_TX_RX);
    usart_set_parity(USART2, USART_PARITY_NONE);
    usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);

    usart_enable(USART2);
}

void dma_request_setup(void)
{
    dma_channel_reset(DMA1, DMA_CHANNEL6);

    nvic_enable_irq(NVIC_DMA1_CHANNEL6_IRQ);

    dma_set_peripheral_address(DMA1, DMA_CHANNEL6, (uint32_t) &USART2_DR);
    dma_set_read_from_peripheral(DMA1, DMA_CHANNEL6);

    dma_set_peripheral_size(DMA1, DMA_CHANNEL6, DMA_CCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_CHANNEL6, DMA_CCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_CHANNEL6, DMA_CCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL6);
    dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL6);

    dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL6);
    dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL6);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL6);
}

void dma_transmit_setup(void)
{
    dma_channel_reset(DMA1, DMA_CHANNEL7);

    nvic_enable_irq(NVIC_DMA1_CHANNEL7_IRQ);

    dma_set_peripheral_address(DMA1, DMA_CHANNEL7, (uint32_t) &USART2_DR);
    dma_set_read_from_memory(DMA1, DMA_CHANNEL7);

    dma_set_peripheral_size(DMA1, DMA_CHANNEL7, DMA_CCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_CHANNEL7, DMA_CCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_CHANNEL7, DMA_CCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL7);
    dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL7);

    dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL7);
    dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL7);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL7);
}

void dma_request(void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_CHANNEL6, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_CHANNEL6, datasize);

    dma_enable_channel(DMA1, DMA_CHANNEL6);
    signal_host();
    usart_enable_rx_dma(USART2);
}

void dma_transmit(const void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_CHANNEL7, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_CHANNEL7, datasize);

    dma_enable_channel(DMA1, DMA_CHANNEL7);
    usart_enable_tx_dma(USART2);
}

int dma_done(void)
{
    return !((DMA1_CCR6 | DMA1_CCR7) & 1);
}

void dma1_channel6_isr(void) {
    usart_disable_rx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_CHANNEL6, DMA_TCIF);
    dma_disable_channel(DMA1, DMA_CHANNEL6);
}

void dma1_channel7_isr(void) {
    usart_disable_tx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_CHANNEL7, DMA_TCIF);
    dma_disable_channel(DMA1, DMA_CHANNEL7);
}

void signal_host(void) {
    usart_send_blocking(USART2, '\n');
}

int main(void)
{
    clock_setup();
    gpio_setup();
    usart_setup(921600);
    dma_transmit_setup();
    dma_request_setup();

    unsigned char buf[16];

    dma_request(buf, 16); while (!dma_done());

    buf[10] = 'd';
    buf[11] = 'a';
    buf[12] = 'w';
    buf[13] = 'n';

    dma_transmit(buf, 16); while (!dma_done());

    while(1);

    return 0;
}

STM32F4 code:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/dma.h>

void clock_setup(void)
{
    rcc_clock_setup_hse_3v3(&hse_8mhz_3v3[CLOCK_3V3_168MHZ]);
    rcc_periph_clock_enable(RCC_GPIOA);
    rcc_periph_clock_enable(RCC_USART2);
    rcc_periph_clock_enable(RCC_DMA1);
}

void gpio_setup(void)
{
    gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
    gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}

void usart_setup(int baud)
{
    usart_set_baudrate(USART2, baud);
    usart_set_databits(USART2, 8);
    usart_set_stopbits(USART2, USART_STOPBITS_1);
    usart_set_mode(USART2, USART_MODE_TX_RX);
    usart_set_parity(USART2, USART_PARITY_NONE);
    usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);

    usart_enable(USART2);
}

void dma_request_setup(void)
{
    dma_stream_reset(DMA1, DMA_STREAM5);

    nvic_enable_irq(NVIC_DMA1_STREAM5_IRQ);

    dma_set_peripheral_address(DMA1, DMA_STREAM5, (uint32_t) &USART2_DR);
    dma_set_transfer_mode(DMA1, DMA_STREAM5, DMA_SxCR_DIR_PERIPHERAL_TO_MEM);

    dma_set_peripheral_size(DMA1, DMA_STREAM5, DMA_SxCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_STREAM5, DMA_SxCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_STREAM5, DMA_SxCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4);
    dma_enable_memory_increment_mode(DMA1, DMA_STREAM5);

    dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM5);
    dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM5);
    dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM5);
    dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM5);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM5);
}

void dma_transmit_setup(void)
{
    dma_stream_reset(DMA1, DMA_STREAM6);

    nvic_enable_irq(NVIC_DMA1_STREAM6_IRQ);

    dma_set_peripheral_address(DMA1, DMA_STREAM6, (uint32_t) &USART2_DR);
    dma_set_transfer_mode(DMA1, DMA_STREAM6, DMA_SxCR_DIR_MEM_TO_PERIPHERAL);

    dma_set_peripheral_size(DMA1, DMA_STREAM6, DMA_SxCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_STREAM6, DMA_SxCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_STREAM6, DMA_SxCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4);
    dma_enable_memory_increment_mode(DMA1, DMA_STREAM6);

    dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM6);
    dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM6);
    dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM6);
    dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM6);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM6);
}

void dma_request(void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_STREAM5, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_STREAM5, datasize);

    dma_channel_select(DMA1, DMA_STREAM5, DMA_SxCR_CHSEL_4);
    dma_enable_stream(DMA1, DMA_STREAM5);
    signal_host();
    usart_enable_rx_dma(USART2);
}

void dma_transmit(const void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_STREAM6, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_STREAM6, datasize);

    dma_channel_select(DMA1, DMA_STREAM6, DMA_SxCR_CHSEL_4);
    dma_enable_stream(DMA1, DMA_STREAM6);
    usart_enable_tx_dma(USART2);
}

int dma_done(void)
{
    return !((DMA1_S5CR | DMA1_S6CR) & 1);
}

void dma1_stream5_isr(void) {
    usart_disable_rx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_STREAM5, DMA_TCIF);
    dma_disable_stream(DMA1, DMA_STREAM5);
}

void dma1_stream6_isr(void) {
    usart_disable_tx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_STREAM6, DMA_TCIF);
    dma_disable_stream(DMA1, DMA_STREAM6);
}

void signal_host(void) {
    usart_send_blocking(USART2, '\n');
}

int main(void)
{
    clock_setup();
    gpio_setup();
    usart_setup(921600);
    dma_transmit_setup();
    dma_request_setup();

    unsigned char buf[16];

    dma_request(buf, 16); while (!dma_done());

    buf[10] = 'd';
    buf[11] = 'a';
    buf[12] = 'w';
    buf[13] = 'n';

    dma_transmit(buf, 16); while (!dma_done());

    while(1);

    return 0;
}

A: Well, I can be brief about this one.
I recommend against using stty for this sort of thing. I realise I have probably not configured stty properly, and with some option-tweaking it is probably possible to get it right, but it's completely unclear. I ended up throwing it out the window and using pyserial instead. I should've done that weeks ago. The above STM32 code works fine and the required Python code is completely trivial.
#!/usr/bin/env python3
import serial

dev = serial.Serial("/dev/ttyUSB0", 921600)

dev.read(1)  # wait for the signal
dev.write("Defend at noon\r\n".encode('utf-8'))

while True:
    x = dev.read()
    print(x.decode('utf-8'), end='', flush=True)


Q: Dijit TabContainer tabs missing, serif fonts, all containers visible I have a small project I am doing, and am using Dojo for it.  At the moment I can't get everything to load properly.  I am trying to use the Tundra theme.
Essentially, the issue is that the TabContainer is missing tabs, has serif fonts instead of sans-serif, and shows all ContentPanes inside it instead of hiding ones in non-active tabs.  The serif issue also applies to all other Dijit elements I try to create, however Dijit form elements seem to work a bit better (apart from font being incorrect, it has correct styling, and validation and other fancy stuff works fine).
The same issue appears when using the other Dijit themes, however the TabContainer border colour changes with each different theme which leads me to believe the Dijit theme may be loading correctly.  Dojo seems to be correctly creating the Dijit elements though, looking at the Firebug output further below.
Complete copies of Dojo 1.3.2 dojo, dijit and dojox directories exist in js/dojo.  All linked stylesheets and scripts are initially loading and the paths to them are correct (I've tested to confirm that with alert boxes in js and body colour changing in css).
index.html
<!DOCTYPE HTML>

<link href="js/dojo/dijit/themes/tundra/tundra.css" rel="stylesheet">

js/script.js
function xmlEnableDiv(div) {
    dojo.require("dijit.layout.TabContainer");
    dojo.require("dijit.layout.ContentPane");

    var tc = new dijit.layout.TabContainer({
    }, div);

    var cp1 = new dijit.layout.ContentPane({
        id: "xmleditor",
        title: "Editor",
        content: "This is where the editor will actually go"
    });
    tc.addChild(cp1);

    var cp2 = new dijit.layout.ContentPane({
        id: "xmltext",
        title: "Source",
        content: "This is where the source will actually go"
    });
    tc.addChild(cp2);
}

Checking Firebug, I see the following (which to my eyes looks like it should):

This is where the editor will actually go

This is where the source will actually go

The actual output (in Firefox and Chrome) is a box (the TabContainer) with a themed border.  There are no tabs on the TabContainer, and both of the ContentPanes are visible at the same time (both with serif fonts).
The things I've tried without avail:

*

*Doing a dojo.parser.parse() at the end of my init function

*Trying other Dijits.  They act similarly in that they seem to partially load.  Every Dijit has serif fonts instead of sans-serif, but form elements and dialog are both showing correctly apart from the incorrect font

Thanks in advance, this is driving me nuts.

A: The solution was to add startup after creating the TabContainer.
Thanks to this post: http://www.dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/tabcontainer-labels-not-rendering-when-created-programatically
tabContainer = new dijit.layout.TabContainer({
}, div);
tabContainer.startup();

A: Another possibility is that adding TabContainer to a hidden element can have missing tabs, as described above, even after calling startup.  The solution to this is to ensure that the TabContainer receives the resize event.  You can try this yourself by finding the ID of the tab container, and then executing this in the console:
dijit.byId('dijit_layout_TabContainer_0').resize();
If your tabs appear, then you have a resize problem.  Ensure that the parent container handles/passes the resize event to the tab container child.  For example:
    resize: function() {
        this.tabContainer.resize();
    }


Q: Can not access contextVariables in decorator I have python decorator and  I need pass contextVariable inside my decorator or as argument  request_id in function
Step 1: Declare contextVariables and methods
_correlation_id_ctx_var: ContextVar[str] = ContextVar(CORRELATION_ID_CTX_KEY, default=None)
_request_id_ctx_var: ContextVar[str] = ContextVar(REQUEST_ID_CTX_KEY, default=None)

def get_correlation_id() -> str:
    return _correlation_id_ctx_var.get()

def get_request_id() -> str:
    return _request_id_ctx_var.get()

Step 2: The context Variable I declare inside middleware (use FastApi)
@app.middleware("http")
async def log_request(request: Request, call_next):
    correlation_id = _correlation_id_ctx_var.set(request.headers.get('X-Correlation-ID', str(uuid4())))
    request_id = _request_id_ctx_var.set(str(uuid4()))

Step3: I try to pass contextVariable to decorator - it always None
Try to pass as argument in function itself - it always None
What it the problem?
Why contextVars accessible in function body only and not in decorator or argument function?
Is there any solutions to have access to contextVar before function body?
@app.get('/test')
@decorator(request_id=get_request_id())
def test_purpose(request_id=get_request_id()):
    print('get_correlation_id() start', get_request_id())
    return 'ok'

Decorator:
def decorator(request_id=None, *args, **kwargs):
    def logger(func, request_id=None, *args, **kwargs):
        @wraps(func, *args, **kwargs)
        def wrapper(*args, **kwargs):
            try:
                res = func()
                print()
                return res
            except Exception:
              pass
        return wrapper
    return logger

A: @decorator(request_id=get_request_id()) <- this line is executed when your module is imported. Which means your getter function is called only once, when the module is imported, not each time your decorated function is called.
To fix it, just pass the getter function, not its result, to the decorator, and make the call inside the wrapper function, inside the decorator. (For that, just leave the parentheses out):

def decorator(request_id_getter=None, *d_args, **d_kw):
    def logger(func):  # other arguments than the first positional arg here are not used at all.
        @wraps(func, *d_args, **d_kw)
        def wrapper(*args, **kwargs):
            request_id = request_id_getter()  # and here the value is retrieved when the function is actually called
            try:
                res = func()
                print()
                return res
            except Exception:
              pass
        return wrapper
    return logger

@app.get('/test')
@decorator(request_id=get_request_id)  # <- here is the change - do not _call_ the function!
def test_purpose(request_id=get_request_id()):
    print('get_correlation_id() start', get_request_id())
    return 'ok'


Q: Sort simplexml object - without casting to array Is it possible to sort a simplexml object but keep the object as a simplexml object instead of casting to an array.
There doesnt appear to be a way to do this - and if casted to an array it seems very messy to transform the array(s) back to a simplexml object.
So -
Is it possible to sort a simplexml object by an attribute etc.
For example (sort by the position attribute node):
<test_nodes>
  <node position="1"></node>
  <node position="2"></node>
  <node position="3"></node>
</test_nodes>

If not then what is the most painless and efficient way to cast an array to a simple xml object


Q: redirect page with header with string My page cannot redirect to another page using header and below is the code
$v1 = "http://www.google.com";

header('Location: $v1');

instead it redirected to http://localhost/$v1
How can i achieve this type of syntax to redirect

A: Change single quote to double quotes. Note that variables inside the single quotes would not be parsed.
header("Location: $v1");

A: Wrong syntax. Try:
$url = "http://www.google.com/";
header("Location: $url");
//     ^              ^
// You should use double quotes to expand variables.

A: This worked for me:

$v1 = "http://www.google.com";
header('Location:'. $v1);


Q: How to add Lodash debounce to react input? I have a simpel form:
https://codesandbox.io/s/distracted-poincare-2blfq?file=/src/App.js:357-552
      <form>
        <TextField
          onChange={handleChange}
          onBlur={clearInput}
          value={inputValue}
          placeholder="Do an api request"
        />
      </form>

On the onChange I want to do an api request with the value of the input but I would like to add a debounce or throttle. Important is that when the input is blurred the text in the input should be removed and the placeholder should be visible.

A: Method 1.
Use React debounce input, simple method
https://www.npmjs.com/package/react-debounce-input
Method 2
Create timer and call API based on that, no external library needed. and i always suggest this
 let timer = null
 const handleChange = (e) => {
    setInputValue(e.target.value)
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(()=>yourApiCall(e.target.value), 700)
 }
 const yourApiCall = (val) => {
   //call API here
 }

  <form>
    <TextField
      onChange={handleChange}
      onBlur={clearInput}
      value={inputValue}
      placeholder="Do an api request"
    />
  </form>

a working example
https://codesandbox.io/s/beautiful-goldberg-vyo2u?file=/src/App.js
Method 3
Use loadash debounce
check the answers from this link
Lodash debounce with React Input


Q: php variable in a echo string I'm customizing a wordpress for the first time so I'm pretty new with PHP langage and something is driving me crazy.
I wrote that function to transform my HTML5/CSS3/JQUERY layout into a CMS:
<?php $property = simple_fields_values("pillow_front");
  foreach ($property as $value) {
    echo "
";
      echo "
";
        echo "

";
      echo "
";
    echo "
";
  }
?>

But in the front-end it doesn't work and when I look at the code it appears that the img tag is not closed properly:

I didn't really well understoud if the . in PHP was the exact equivalent of the + in javascript but I tried a lots of thing and I can get that tag to be properly closed !
Thank you

A: You can print in another system, something like this:
<?php
$property = simple_fields_values("pillow_front");
 foreach ($property as $value) {
 ?>

<img src="<?php print wp_get_attachment_url($value);?>"/>

 <?php
 }
 ?>

Please note that i put the echo of the function only because i do not know how it works, it can be not necessary, use php only when needed.

A: Or just a bit more MVC-Pattern or in that case just MV? ;) Try this one without Wordpress.
<?php

    //Init
    $property = simple_fields_values("pillow_front");
    $template = '

';

    foreach ($property as $value) {
        echo str_replace(array('{MARKER:FRONT}'), array($value), $template);
    }
?>

And as i know wordpress view, your code style is not confirm to WP-Styleguide. WP is using HTML/PHP Templating. In WP you view need to look like this.
<?php foreach(simple_fields_values("pillow_front") as $value): ?>

<img src="<?php echo htmlentities(value): ?>"/>

<?php endforeach; ?>


Q: FTP username with | (pipe) in Windows batch file I'm trying to FTP files to a remote location. But here is the issue I'm facing.
When I use the below script, I'm able to login to the remote server but I'm not able to place any files over there, 550 access denied log prompt.
echo user domain/username> ftp.txt
echo password>> ftp.txt
echo cd remotepath>> ftp.txt
echo put FTPTest.txt>>ftp.txt
echo quit>> ftp.txt

ftp -n -s ftp.txt Servername>ftp_logs.txt

del ftp.txt

I tried to login via command prompt. I successfully Ftp'd, if the username is like Servername|domain/username.
I modified the script as below, script is not even executing.
echo user Servername|domain/username> ftp.txt
echo password>> ftp.txt
echo cd remotepath>> ftp.txt
echo put FTPTest.txt>>ftp.txt
echo quit>> ftp.txt

ftp -n -s ftp.txt Servername>ftp_logs.txt

del ftp.txt

Searching for clues...

A: You have to escape the |, as that has a special meaning in Windows:
echo user Servername^|domain/username> ftp.txt

The above will get you
user Servername|domain/username

in the ftp.exe.


Q: Binding a field to a reactive form does not show value If I hardcode the value to something like 'xxx' it is fine. But when I call a service and then try to bind the value nothing happens. I thought it was data bound so when the field is set it would show on the UI ?
      <form [formGroup]="saveFileForm" (ngSubmit)="onExpSubmit()">

                Notes:

                <input type="text" formControlName="Notes">

fileData: AttachmentVm = new AttachmentVm();

  constructor(private service: AttachService,
    private formBuilder: FormBuilder,
    private router: Router,
    public dialogRefSpinner: MatDialogRef<DialogRedirectToLandingSpinnerModule>,
    public snackBar: MatSnackBar,
    public dialog: MatDialog,
  ) { }

  ngOnInit(): void {
    this.saveFileForm = this.formBuilder.group({
      PaymentDate: [''],
      IsPaid: [false],
      Notes: [this.fileData.GlobalNotes],
      //Notes: ['xxx'],
      FileDescription: ['']
    });

    if (this.formIdFromParent) {
      this.service.getFiles(this.formIdFromParent).subscribe(result => {
        this.fileData = result;
      })
    }
  }

A: You need to update the form control value:
if (this.formIdFromParent) {
  this.service.getFiles(this.formIdFromParent).subscribe(result => {
     this.fileData = result;
     this.formIdFromParent.controls['Notes'].setValue(this.fileData. GlobalNotes);
  })
}


Q: REDIS LIST MOVE recovery/rollback strategy I have the following scenario:

*

*Redis SENTINEL with one main REDIs and two replicas

*Redis Connection timeout configured to 30 seconds

*Lettuce's Java REDIS client

*Spring Data on top of Lettuce's REDIS client

I have a REDIS LIST which I am using as a QUEUE. As expected, each element on the queue must be processed by one and only one element processor. However, in some weird corner cases, I sometimes experience THIS:
-> BLMOVE A B 8
     (*) I get a timeout here after 30 seconds

(this is, move from list A to list B and block for 8 seconds
The problem I have is that the ELEMENT actually moves from list A to list B and I still get the timeout, so after this exception the element gets lost in queue B and never gets processed. I understand that this might be a network issue with the REDIS CONNECTION.
My question is: What's the best way to handle cases like this? Is there a way to "recover" the unprocessed element and try again?

A: There are a few ways to solve this issue:

*

*Use a REDIS SENTINEL with failover capabilities. This way, if the primary REDIS instance goes down, the sentinel will automatically failover to the replica instance and your elements will not be lost.

*Use a REDIS CLUSTER. This will provide you with high availability and will ensure that your elements are not lost in the event of a failure.

*Use a REDIS Replication setup. This will provide you with a hot standby REDIS instance that can take over if the primary instance goes down.

*Use a REDIS Persistence setup. This will ensure that your elements are not lost in the event of a failure.

*Use a REDIS Backup setup. This will ensure that your elements are not lost in the event of a failure.


Q: My own mini-framework is not compatible with some projects I failed to create a mini-library with some useful functions that I have found over the Internet, and I want to use them easily by just including a file to the HTML (like jQuery).
The problem is that some vars and functions share the same name and they are causing problems.
Is there a better solution to this instead of giving crazy names to the vars/funcs like "bbbb123" so the odds that someone is working with a "bbbb123" var is really low?

A: I would put all of your functions and variables into a single object for your library.
var MyLibrary = {
  myFunc: function() {
    //do stuff
  },

  myVar: "Foo"
}

There are a few different ways of defining 'classes' in JavaScript. Here is a nice page with 3 of them.

A: You should take one variable name in the global namespace that there are low odds of being used, and put everything else underneath it (in its own namespace).
For example, if I wanted to call my library AzureLib:
AzureLib = {
    SortSomething: function(arr) {
        // do some sorting
    },
    DoSomethingCool: function(item) {
        // do something cool
    }
};

// usage (in another JavaScript file or in an HTML <script> tag):
AzureLib.SortSomething(myArray);

A: You could put all of your library's functions inside of a single object.  That way, as long as that object's name doesn't conflict, you will be good.  Something like:
var yourLib = {};

yourLib.usefulFunction1 = function(){
    ..
};

yourLib.usefulFunction2 = function(){
    ..
};

A: Yes, you can create an object as a namespace. There are several ways to do this, syntax-wise, but the end result is approximately the same. Your object name should be the thing that no one else will have used.
var MyLibrary = {

    myFunc: function() { /* stuff */ }

};

Just remember, it's object literal syntax, so you use label : value to put things inside it, and not var label = value;.
If you need to declare things first, use a wrapping function to enclose the environment and protect you from the global scope:
var MyLibrary = (function() {

    var foo = 'bar';

    return {
        myFunc: function() { /* stuff */ }
    };

})(); // execute this function right away to return your library object


Q: Cordova: command not found after installing globally I try to install Cordova in macOS Mojave. I run the following command to install globally. It is installed successfully npm i -g cordova
but when I check the version using cordova --version , It gives me the error "cordova: command not found".
and also when I try to get the location using which cordova, It returns nothing.

A: Refer this great write up: http://blog.webbb.be/command-not-found-node-npm/
This can happen when npm is installing to a location that is not the standard and is not in your path.

To check where npm is installing, run: npm root -g

It SHOULD say /usr/local/lib/node_modules, If it doesn't then follow this:
Set it to the correct PATH:

*

*run: npm config set prefix /usr/local

*Then reinstall your npm package(s) with -g:
npm install -g cordova etc
If this doesn't work then try adding the global path of cordova(where it got installed) to your $PATH variable.


Q: Regex to split the string into identical blocks I wanted to fetch the data an put it in the list from the below XML using regex in python as below
[['ip-address','1.1.1.1/16','protocol','ospf','ll',4],['ip-address','3.3.3.3/32','ip-addr','2.2.2.2','ip-addr','8.8.8.8','type',route]]
a=''' <att>
       <rt>
        <rts>
         <ip-address>1.1.1.1/16</ip-address>
         <bb>
          <cc>
           <protocol>ospf</protocol>
          </cc>
         </bb>
         <ee>
          <ff>
           <ll>4</ll>
          </ff>
         </ee>
        </rts>
        <rts>
         <ip-address>3.3.3.3/32</ip-address>
         <bb>
          <cc>
           <ip-addr>2.2.2.2</ip-addr>
           <ip-addr>8.8.8.8</ip-addr>
          </cc>
         </bb>
         <ee>
          <ff>
           <type>route</type>
          </ff>
         </ee>
        </rts>
       <rt>
      </att>'''

My approach was to divide the above single string into multiple string and then search, example
  b=  '''<rts>
         <ip-address>1.1.1.1/16</ip-address>
         <bb>
          <cc>
           <protocol>ospf</protocol>
          </cc>
         </bb>
         <ee>
          <ff>
           <ll>4</ll>
          </ff>
         </ee>
        </rts>'''

 c= '''<rts>
         <ip-address>3.3.3.3/32</ip-address>
         <bb>
          <cc>
           <ip-addr>2.2.2.2</ip-addr>
           <ip-addr>8.8.8.8</ip-addr>
          </cc>
         </bb>
         <ee>
          <ff>
           <type>route</type>
          </ff>
         </ee>
        </rts>'''

I used the following regex to create multiple string
regex = re.findall(r"<(rts)>.*<\ /rts)", a, re.S)

But it fetches all untill the end of string as below,
        <rts>
     <ip-address>1.1.1.1/16</ip-address>
     <bb>
      <cc>
       <protocol>ospf</protocol>
      </cc>
     </bb>
     <ee>
      <ff>
       <ll>4</ll>
      </ff>
     </ee>
    </rts>
    <rts>
     <ip-address>3.3.3.3/32</ip-address>
     <bb>
      <cc>
       <ip-addr>2.2.2.2</ip-addr>
       <ip-addr>8.8.8.8</ip-addr>
      </cc>
     </bb>
     <ee>
      <ff>
       <type>route</type>
      </ff>
     </ee>
    </rts>

Is there a way I could be able to divide the string as "b" and "c" shown above?

A: With lxml and xpath you can parse xml much more easily than by rolling your own regex parser.
Here's an example:
import lxml
import StringIO

a =''' <att>
       <rt>
        <rts>
         <ip-address>1.1.1.1/16</ip-address>
         <bb>
          <cc>
           <protocol>ospf</protocol>
          </cc>
         </bb>
         <ee>
          <ff>
           <ll>4</ll>
          </ff>
         </ee>
        </rts>
        <rts>
         <ip-address>3.3.3.3/32</ip-address>
         <bb>
          <cc>
           <ip-addr>2.2.2.2</ip-addr>
           <ip-addr>8.8.8.8</ip-addr>
          </cc>
         </bb>
         <ee>
          <ff>
           <type>route</type>
          </ff>
         </ee>
        </rts>
       </rt>
      </att>'''

f = StringIO.StringIO(a)
tree = lxml.etree.parse(f)

rts = tree.xpath('//rts')

ipa = rts[0].xpath(".//ip-address")[0]

print ipa.text

This prints the first ip-address of the first rts tag, i.e. 1.1.1.1/16.
Note:
I needed to fix your xml, there was a / missing on the last rt tag.


Q: different screen.colorDepth value for firefox and opera/chrome I m testing a javascript in which i wrote this
document.write("\n\n\n\n"+screen.colorDepth);
switch(screen.colorDepth)
{
case 24: document.bgColor = "skyblue" ;
         break;
case 32: document.bgColor = "yellow";
        break;
default: document.bgColor = "white";
        break;
}

but unfortunately Firefox 21.0 and IE9 is showing value 24 and thus background color is going skyblue
and opera( v12.01 Build 1532) and chrome(Version 27.0.1453.94 m) is showing 32 and thus the background is going yellow . I m using win 7 ultimate 32bit and my original color depth of screen is 32 bit. Can anyone plz explain why this is happening ?

A: I guess they are using different approaches interpreting the color precision. A 32-bit screen is in fact only 24-bit color (the 8 last bits is not part of the color space).
Mozilla defines it as:

Returns the color depth of the screen.

Chrome seem to read it directly from the system as-is, while FF and IE9 seem to correctly (based on that definition) identify the color precision (color depth) of the screen.
Please note that screen.colorDepth is not part of any standard and it's up to the implementers how it actually works.
The more correct way of checking color-precision in regards to color depth would therefor be:
case 16: document.bgColor = "..." ;
         break;
case 24:
case 32: document.bgColor = "..."; //32 = 24 bit color depth + 8 bits alpha
         break;