text:
Q: To add start index to a list I have a numpy array
a = [1 2 3]

I want to add 0 as first index to the list. How can I do that?
output :
a = [0 1 2 3]

A: Using list.insert:
>>> a = [1, 2, 3]
>>> a.insert(0, 0)
>>> a
[0, 1, 2, 3]

Using slice assignment:
>>> a = [1, 2, 3]
>>> a[:0] = [0]
>>> a
[0, 1, 2, 3]

UPDATE according to tag change.
Use numpy.insert:
>>> a = np.array([1, 2, 3])
>>> np.insert(a, 0, 0)
array([0, 1, 2, 3])

or numpy.hstack:
>>> np.hstack([[0], a])
array([0, 1, 2, 3])

A: You can use list.insert (reference: http://docs.python.org/2/tutorial/datastructures.html)
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
a.insert(0,0)


text:
Q: Optimizing my KnockOutJS function - From Ugly Code to Clean, How? Function Description
This function is supposed to simply replace an item in my observable array.
I am accepting 3 parameters:

*

*findBy = Whether to locate the source index by "id" or "name" property.

*cmpVal = The value we are searching the array for

*objNewItem = The new item. This case ex, { id: "12" , name: "NewName" }

Then I am deleting that index from the array, and finally pushing the new object into the array.
I had no luck using the replace function from Knockout, so I had to write my own.
I realize this may be the ugliest code on the internet. That's why I am deferring to you professionals here. :)
/* Update A Station
  *
  *  @param   findBy      string    Property to find ( "id" or "name")
  *  @param   cmpVal      string    Value to compare against
  *  @param   objNewItem  object    The new object replacing old
  * */
  self.modifyStation = function(findBy, cmpVal, objNewItem){

    var sourceIndex;
    var oldId;

    /* Find Index Of Old Station */
    var c = -1;
    ko.utils.arrayForEach(this.station(), function(item) {
      c++;
      switch (findBy) {

        case "id":
          var value = item.id();
          if(value == cmpVal){
            sourceIndex = c;
            oldId = item.id();
          }
          break;

        case "name":
          var value = item.name();
          if(value == cmpVal){
            sourceIndex = c;
            oldId = item.id();
          }
          break;
      }

    });

    /* Remove Old */
    self.station().splice(sourceIndex,1);

    /* Insert New Station
    *  [For Now] not allowing updating of ID. Only
    *  can update the other properties (yes, I realize that
    *  only leaves "name", but more will be added )
    */
    objNewItem.id = oldId;  // Put old ID back in
    self.station.push(objNewItem);

  }

Note: I am not allowing them to edit the ID for now.
Can anyone help me clean this up? I am smart enough to know its not efficient, but I don't know how else to optimize it.
Any advice would be appreciated. Thank you!
John

A: Ok so...
First of we will create a function that will contain all the logic, from this example on you can do anything with it. The most proper way would be to extend your 'observableArray' directly on knockout, but i am not going to get this one this far now :P
function ReplaceInObservableArray(obsArray, prop, cmpVal, newItem){
    // use the fact that you can get the value of the property by treating the object as the dictionary that it is
  // so you do not need to program for specific properties for different array model types
    var foundItems = obsArray().filter(function(i){

        return ko.utils.unwrapObservable(i[prop]) == cmpVal;
    });

    if(foundItems.length > 1)
    {
      // handle what happens when the property you are comparing is not unique on your list. More than one items exists with this comparison run
      // you should throw or improve this sample further with this case implementation.
    } else if(foundItems.length == 0)
    {
        // handle what happens when there is nothing found with what you are searching with.
    } else {
        // replace at the same index rather than pushing, so you dont move any other items on the array
        // use the frameworks built in method to make the replacement
        obsArray.replace(foundItems[0], newItem);
    }
}

var demoArray = ko.observableArray([{ id : 1, name : 'test1' },{id : 2, name : 'test2' },{ id : 3, name : 'test3'},{id : 4, name : 'test4'}]);
ReplaceInObservableArray(demoArray,'id', 1, {id : 1, name : 'test111'});
ReplaceInObservableArray(demoArray,'name', 'test3', {id : 3, name : 'test3333'});
console.log(demoArray());

redpajama_set_name: RedPajamaStackExchange


text:
Q: SwiftUI: How to disable the "smart quotes" in TextEditor I'm developing a Python-based graphic calculator for MacOS using SwiftUI.
https://github.com/snakajima/macplot
I am using SwiftUI's TextEditor as the editor for Python code, but I am not able to figure out how to disable the smart quote (UITextInputTraits, smartQuotesType: UITextSmartQuotesType).
        VStack {
            TextEditor(text: $pythonScript.script)
            HStack {
                Button(action: {
                    pythonScript.run(clear: settings.shouldClear)
                }, label: {
                    Text("Plot")
                })
                Toggle("Clear", isOn: $settings.shouldClear)
            }
            if let errorMsg = pythonScript.errorMsg {
                Text(errorMsg)
                    .foregroundColor(.pink)
            }
        }

A: After several trials, I came up with the following work-around. It relies on the fact that TextEditor is implemented on top of NSTextView, and changes its behavior across the entire application. It is ugly, but works.
// HACK to work-around the smart quote issue
extension NSTextView {
    open override var frame: CGRect {
        didSet {
            self.isAutomaticQuoteSubstitutionEnabled = false
        }
    }
}

A: For those who are looking for an answer for UIKit (iOS, iPadOS) instead of AppKit (macOS), this works for me using a similar approach. Thanks Satoshi!
extension UITextView {
    open override var frame: CGRect {
        didSet {
            self.smartQuotesType = UITextSmartQuotesType.no
        }
    }
}

This has the same drawbacks, which is that all text fields in your application will lose auto-smart-quotes, but at least you can control this if you need it.

A: Another solution would be to write an NSTextView wrapper:
struct TextView: NSViewRepresentable {
    @Binding var text: String
    private var customizations = [(NSTextView) -> Void]()

    init(text: Binding<String>) {
        _text = text
    }

    func makeNSView(context: Context) -> NSView {
        NSTextView()
    }

    func updateNSView(_ nsView: NSView, context: Context) {
        let textView = nsView as! NSTextView
        textView.string = text
        customizations.forEach { $0(textView) }
    }

    func automaticDashSubstitutionEnabled(_ enabled: Bool) -> Self {
        customized { $0.isAutomaticDashSubstitutionEnabled = enabled }
    }

    func automaticQuoteSubstitutionEnabled(_ enabled: Bool) -> Self {
        customized { $0.isAutomaticQuoteSubstitutionEnabled = enabled }
    }

    func automaticSpellingCorrectionEnabled(_ enabled: Bool) -> Self {
        customized { $0.isAutomaticSpellingCorrectionEnabled = enabled }
    }
}

private extension TextView {
    func customized(_ customization: @escaping (NSTextView) -> Void) -> Self {
        var copy = self
        copy.customizations.append(customization)
        return copy
    }
}

, which can be used like this:
TextView(text: $myText)
    .automaticDashSubstitutionEnabled(false)
    .automaticQuoteSubstitutionEnabled(false)
    .automaticSpellingCorrectionEnabled(false)


text:
Q: Java order of class fields and methods in singleton I have a surprising problem that any amount of Googling is not helping. I was hoping I can clarify here.
I declared a Java singleton for connection pooling my JDBC/MySQL DB using eager initialization like so:
public class SomeConnectionPool
{
   private static final Logger log = Logger.getLogger (SomeConnectionPool.class.getName());
   private static SomeDataSource sDS = null;
   private static SomeConnectionPool sCP = new SomeConnectionPool ();

   private SomeConnectionPool ()
   {
     // Configure DataSource, connect to DB
      sDS = new SomeDataSource (config);
   }

   public static SomeConnectionPool getInstance ()
   {
      return sCP;
   }

   public static SomeDataSource getDataSource ()
   {
      return sDS;
   }
}

In my application, I use the singleton like so:
SomeDataSource sds = SomeConnectionPool.getInstance ().getDataSource ();
Connection connection = sds.getConnection ();

this works as expected.
However, if I change the order of the members in SomeConnectionPool class like so:
public class SomeConnectionPool
{
   private static final Logger log = Logger.getLogger (SomeConnectionPool.class.getName());
   private static SomeConnectionPool sCP = new SomeConnectionPool ();
   private static SomeDataSource sDS = null;

   ... // the rest is the same code as before
}

I get a null pointer exception on the line that requests a getConnection(). I can see that the connection objects are being allocated on the MySQL DB (show processlist lists them).
Does the order of the members really matter? This goes against my previous experience. What am I missing?

A: In the first ordering :
   private static SomeDataSource sDS = null;
   private static SomeConnectionPool sCP = new SomeConnectionPool ();

You first initialize sDS to null and then give it a non null value in the constructor of SomeConnectionPool. Therefore it's not null.
In the second ordering :
   private static SomeConnectionPool sCP = new SomeConnectionPool ();
   private static SomeDataSource sDS = null;

SomeConnectionPool sCP = new SomeConnectionPool (); initializes sDS in its constructor, and later SomeDataSource sDS = null; resets it to null. That's why you get the null pointer exception (SomeConnectionPool.getInstance ().getDataSource (); returns null).

A: Yes. The change makes sense.
static initializers and such are run in line order. So before, you had:

*

*Set sDS to null // sDS is null

*sCP = new SomeConnectionPool();

*Go into constructor

*Set sDS to new SomeDataSource(config); // sDS is not null

*Exit constructor

*continue

So your final result is sDS is not null. But after, you had

*

*sCP = new SomeConnectionPool();

*Go into constructor

*Set sDS to new SomeDataSource(config); // sDS is not null

*Exit constructor

*Set sDS to null // Now sDS is null

*continue

And now sDS is null.

A: You have to understand what is going on when a class is being created. When a class is created, its static members are also created, line by line.
I think the real issue is that you declared SomeDataSource as static, when it should not be. However, to explain what is causing the issue, lets keep looking at it.
In your first example
private static SomeDataSource sDS = null;
private static SomeConnectionPool sCP = new SomeConnectionPool ();

sDs = null. sCP gets constructed and sDs gets constructed as a result.
When you flip the order, sCP gets constructed, as does sDs. Than the next line sets sDs back to null. You should actually try to avoid initializing statics in constructors for this very reason.
Instead you should have:
public class SomeConnectionPool
{
   private static final Logger log = Logger.getLogger (SomeConnectionPool.class.getName());
   private static SomeDataSource sDS = new SomeDataSource (config);
   private static SomeConnectionPool sCP = new SomeConnectionPool ();

   private SomeConnectionPool ()
   {
     // Configure DataSource, connect to DB
   }

However, a typical singleton pattern doesn't have anything static except for the instance. The purpose is to have instance specific logic, but enforce that there is only ever one version of the instance. For example, a more appropriate singleton would be:
public class SomeConnectionPool
{
   private static final Logger log = Logger.getLogger (SomeConnectionPool.class.getName());
   private static SomeConnectionPool instance = new SomeConnectionPool ();
   private SomeDataSource sDS = null;

   private SomeConnectionPool ()
   {
     // Configure DataSource, connect to DB
      this.sDs = new SomeDataSource (config);
   }
   public static SomeConnectionPool getInstance ()
   {
     return instance;
   }
   public SomeDataSource getDataSource ()
   {
      return this.sDs;
   }

Note the removal of static in certain places.


text:
Q: Can I add multiple models from different apps to one admin site? Can I add multiple models from different apps to one admin site? I would like see e.g both apps (polls, news) models under one roof of admin panel.
For now in my Django admin site NONE of the models is displayed.
I try in admin.py file
from tutorial.polls.models import Poll, Choice
from tutorial.news.models import Article, Reporter
from django.contrib import admin

admin.site.register(Poll)
admin.site.register(Choice)
admin.site.register(Article)
admin.site.register(Reporter)

My catalogs structure:
(example)andi@MacBook-Pro-Andrzej:~/example/tutorial$ ls -lR
total 8
-rw-r--r--   1 andi  staff   251B 28 paź 11:53 manage.py
drwxr-xr-x  12 andi  staff   408B 31 paź 02:46 news/
drwxr-xr-x   9 andi  staff   306B 31 paź 02:46 polls/
drwxr-xr-x  12 andi  staff   408B 31 paź 03:06 tutorial/

    ./news:
    total 64
    -rw-r--r--  1 andi  staff     0B 31 paź 00:18 __init__.py
    -rw-r--r--  1 andi  staff   210B 31 paź 02:09 base.html
    -rw-r--r--  1 andi  staff   466B 31 paź 01:26 models.py
    -rw-r--r--  1 andi  staff   383B 31 paź 00:18 tests.py
    -rw-r--r--  1 andi  staff   277B 31 paź 02:08 views.py
    -rw-r--r--  1 andi  staff   329B 31 paź 01:53 year_archive.html

    ./polls:
    total 40
    -rw-r--r--  1 andi  staff     0B 31 paź 02:32 __init__.py
    -rw-r--r--  1 andi  staff   612B 31 paź 02:33 models.py
    -rw-r--r--  1 andi  staff   383B 31 paź 02:32 tests.py
    -rw-r--r--  1 andi  staff    26B 31 paź 02:32 views.py

    ./tutorial:
    total 72
    -rw-r--r--  1 andi  staff     0B 28 paź 11:53 __init__.py
    -rw-r--r--  1 andi  staff   244B 31 paź 03:06 admin.py
    -rw-r--r--  1 andi  staff   5,4K 31 paź 02:34 settings.py
    -rw-r--r--  1 andi  staff   752B 31 paź 02:36 urls.py
    -rw-r--r--  1 andi  staff   1,4K 28 paź 11:53 wsgi.py

A: Welcome to Django programming!
Easy! Create an admin.py in polls/ and news/, and only include the models you need for that app.
For example, polls/admin.py might contain:
from models import Poll, Choice
from django.contrib import admin

admin.site.register(Poll)
admin.site.register(Choice)

That ought to work just fine.
(I believe your current approach isn't working because polls and news aren't reachable from within tutorial/admin.py, and tutorial.polls.models can't find them -- polls/ and models/ would need to be subdirectories of tutorial/ for that to work. Otherwise you're on the right track -- keep going! :) )


text: Q: JavaScript full calendar resource timeline two days issue In JavaScript full calendar resourcetimeline2days view is showing days excluding the present day and showing the other two days how can I show today?


text:
Q: Kotlin MockK: io.mockk.MockKException: no answer found for This is my code snippet:
@Test
fun `request should return anon id if query param present`(@MockK(relaxed = true) req: ServerRequest)

I'm using JUnit5(Jupiter).
The exception I've got is:
io.mockk.MockKException: no answer found for: ServerRequest(#1).cookies()
This is weird because if I understood relaxed correctly, my instance of ServerRequest should always have some value.
Why doesn't it in my case?

A: I figured out while I was writing the question that there is another alternative to specify relaxed, via @RelaxedMockK. And imagine my surprise, it works:
@Test
fun `request should return anon id if query param present`(@RelaxedMockK req: ServerRequest) {


text:
Q: how to keep the time up-to-date in a localtime() variable I'm trying to update localtime() variable I made.
import time
time = time.localtime()

print(time)

the output is
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=6, tm_hour=15, tm_min=34, tm_sec=48, tm_wday=0, tm_yday=126, tm_isdst=1)
I expect it to be the current time.

A:
I expect it to be the current time.

It is (or was) the current time -- at the moment when you called localtime().  But that moment is now in the past.
If you want to have the current time as of right now, call localtime() again.

A: This is what you want.  Avoid using 'time' as variable because it is also a function name.  Visit this link for more formatting codes: https://docs.python.org/3/library/time.html#time.strftime
import time
time_str = time.localtime()

print(time.strftime("%m/%d/%Y %H:%M:%S AM", time_str))

Result:
05/06/2019 16:51:19


text:
Q: Google Maps show hide markers by active icons Hello I'm using google maps API. I have some buttons and I want to show the active markers. If i will click on the image with restaurants then to show me all the markers with the restaurants and hide the others.. I have here the code i tried
  var customIcons = {
            restaurant: {
                icon: 'img/homepage/screen_3/map_pins/restaurante.png'
            },

            shopping: {
                icon: 'img/homepage/screen_3/map_pins/shopping.png'
            },

            spa: {
                icon: 'img/homepage/screen_3/map_pins//spa-&-aquapark.png'
            }

        };

        var markerGroups = {
            "restaurant": [],

            "shopping": [],

            "spa": []
        };

        function load() {
            var map = new google.maps.Map(document.getElementById("map"), {
                center: new google.maps.LatLng(47.059516, 21.947613),
                zoom: 13,
                scrollwheel: false,
                mapTypeId: 'roadmap'
            });
            var infoWindow = new google.maps.InfoWindow();
            // Change this depending on the name of your PHP file

            var bounds = new google.maps.LatLngBounds();
            downloadUrl("googlemaps/phpsqlajax_genxml2.php", function (data) {
                var xml = data.responseXML;
                var markers = xml.documentElement.getElementsByTagName("marker");
                for (var i = 0; i < markers.length; i++) {
                    var id_marker = markers[i].getAttribute("id_marker");
                    var name = markers[i].getAttribute("name");
                    var category = markers[i].getAttribute("category");
                    var address = markers[i].getAttribute("address");
                    var img = markers[i].getAttribute("img");
                    var phone = markers[i].getAttribute("phone");
                    var schedule = markers[i].getAttribute("schedule");
                    var link = markers[i].getAttribute("link");
                    document.getElementById('categorii').src = img;
                    var type = markers[i].getAttribute("type");

                    var point = new google.maps.LatLng(
                            parseFloat(markers[i].getAttribute("lat")),
                            parseFloat(markers[i].getAttribute("lng")));
                    bounds.extend(point);
                    var html = "" + name + "
" + category + "
" + address + "
" + phone + "
" + "
" + schedule + "
" + link;
                    var icon = customIcons[type] || {};
                    var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        icon: icon.icon,
                        id_marker: id_marker,
                        image: img,
                        type: type

                    });

                    if (!markerGroups[type])
                        markerGroups[type] = [];
                    markerGroups[type].push(marker);
                    marker.setVisible(false);
                    bindInfoWindow(marker, map, infoWindow, html);

                }
                map.fitBounds(bounds);
                toggleGroup("spa");

            });

        }

        function toggleGroup(type) {
            for (var i = 0; i < markerGroups[type].length; i++) {
                var marker = markerGroups[type][i];
                if (!marker.getVisible()) {

                    marker.setVisible(true);

                } else {

                    marker.setVisible(false);

                }

            }
        }

        function bindInfoWindow(marker, map, infoWindow, html) {
            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.setContent(html);
                infoWindow.open(map, marker);

                document.getElementById('categorii').src = marker.image;

            });
        }

        function downloadUrl(url, callback) {
            var request = window.ActiveXObject ?
                    new ActiveXObject('Microsoft.XMLHTTP') :
                    new XMLHttpRequest;

            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    request.onreadystatechange = doNothing;
                    callback(request, request.status);
                }
            };

            request.open('GET', url, true);
            request.send(null);
        }

        function doNothing() {
        }

        //]]>

    </script>

And here is the HTML code


text:
Q: $_POST arrays building new array from foreach loop I have a some values in my $_POST that are in there own arrays similar to this,
array(
   ['conviction_date'] = array(
      [0] => 12/01/2011
      [1] => 22/12/2011
   )
   ['conviction_description'] = array(
      [0] => This some text to show what the conviction was for etc.
      [1] => This is some more text to show what the second convication was for
   )
)

What I want to know is how do I loop through said arrays so that I can value from one to the match the value of the other via there keys?
Is it as simple as this,
foreach ($_POST['conviction_date'] as $k => $v) {
    $newArray[] = array(
       'conviction_date' => $v,
       'conviction_details' => $_POST['conviction_details'][$k]
    )
}

Will this then output something to the following?
array(
    [0] => array(
      'conviction_date' => 12/01/2011
      'conviction_details' => This is some to show what the conviction was for etc.
    ),
    [1] => array()
      'conviction_date' => 22/11/2011
      'conviction_details' => This is some more text to show what the second convication was for
    )

Is there away to build a simpler array?

A: Edit the form to the following might be simpler:
<form method="post" action="">
<input type="text" name="conviction_date[]">
<input type="text" name="conviction_details[]">
</form>

if (isset($_POST) { var_dump($_POST); }

A: Might be simpler to give the parameters names so that php will create an array like
array( 'conviction'=>array(
  0=>array('date'=..., 'details'=>...),
  1=>array('date'=..., 'details'=>...),
  ...
);

Then you can do something like
foreach( $_POST['conviction'] as $c ) {
    echo $c['date'], ' ', $c['details'], "\n";
}

A simple demo form:
<form method="post" action="...">
    <fieldset><legend>0</legend>
        <input type="text" name="conviction[0][date]">
        <input type="text" name="conviction[0][details]">
    </fieldset>
    <fieldset><legend>1</legend>
        <input type="text" name="conviction[1][date]">
        <input type="text" name="conviction[1][details]">
    </fieldset>
    ...
</form>

A: Your code sample has a few errors, e.g. conviction date: 12/01/2011 should probably be '12/01/2011'.
That aside, your proposed solution seems appropriate. Alternatively, if each date for a set of convictions is unique(!) you could also use the date as key (e.g. as UNIX-timestamp, or in YYYYMMDD-format). Retrieving the data would then be as simple as:
foreach ($convictions as $date => $description) { ... }


text:
Q: Running AppImage on WSL: How to resolve error requiring FUSE? I downloaded WSL (Windows Subsystem for Linux) and tried to run an AppImage, but received an error message that said
AppImage needs FUSE to run

When I tried the --appimage-extract and --appimage-extract-and-run options, neither of them worked. It seems that FUSE is not supported in WSL.
How can I run an AppImage on WSL if it requires FUSE and FUSE is not supported in WSL?

A: You don't mention which Ubuntu version you are using, but I'm guessing Ubuntu 22.04 since that release doesn't include FUSE by default.  See this answer on Ask Ubuntu.  I tested with the KeePassXC AppImage on WSL on both Ubuntu 20.04 and 22.04.  It works fine on 20.04, but I get the same error as you on 22.04.  To quote the entire error for searchability:
dlopen(): error loading libfuse.so.2

AppImages require FUSE to run.
You might still be able to extract the contents of this AppImage
if you run it with the --appimage-extract option.
See https://github.com/AppImage/AppImageKit/wiki/FUSE
for more information

Again, this isn't a WSL issue -- You'd see the same thing on any installation of Ubuntu 22.04.
The solution is straightforward:
sudo apt install libfuse2

However, on WSL you may find that you need additional dependencies for graphical apps, since the WSL Ubuntu distribution is based on Ubuntu Server and doesn't include graphical libraries by default.
For instance, for KeePassXC, there are a number of graphical dependencies in the AppImage that just aren't available with Ubuntu Server.
I'm honestly not even sure what all of the dependencies are, since I tried to install them piecemeal without success.  However, if you:
sudo apt install xterm

... then it will also come with all of the needed graphical libraries for (at least) KeePassXC (and probably others).
However, there are almost certainly AppImages that have other dependencies, such as a desktop environment (e.g. Gnome or KDE).


text:
Q: convert comment in input string into uppercase how can i identify commented string input by user. suppose user has typed
> I am /*not working*/ right now.

So i want to convert the commented sub string > /* not working*/ into uppercase. how can i do that in c#. converting is not a problem. the problem is how to identify comments? what to do in the if block??
   static void comment(string exp_string)
    {
        for (int i = 0; i < exp_string.Length; i++)
        {
            if (exp_string[i] == 47 && exp_string[i + 1] == 42)

        }

    }

A: If you're restricted from using something as clean as Regular Expressions, look into using String.SubString(), and String.ToUpper().
I think it's silly that you're being restricted, but sometimes there's no other choice. Best of luck to you.
EDIT: Another thing to consider is using IndexOf(). I leave that up to you, however, to find in MSDN

A: You could use this method:
public static string CommentToUpper(string input)
{
    int index = input.IndexOf("/*");
    if (index >= 0)
    {
        int endIndex = input.LastIndexOf("*/");
        if (endIndex > index)
            return string.Format("{0}/*{1}*/{2}",
                input.Substring(0, index),
                input.Substring(index + 2, endIndex - index - 2).ToUpper(),
                input.Substring(endIndex + 2));
        else
            return string.Format("{0}/*{1}",
                input.Substring(0, index),
                input.Substring(index + 2).ToUpper());
    }
    return input;
}

Use it in this way:
string output =  CommentToUpper("> I am /*not working*/ right now.");
Console.Write(output);

Demo


text:
Q: single quotes appear arround value after running copy in postgres 9.2 I am new to postgres and I play around with data loading.
Here is the table definition from postgres 9.2 spec:
CREATE TABLE weather (
    city varchar(80),
    temp_lo int, -- low temperature
    temp_hi int, -- high temperature
    prcp real, -- precipitation
    date date
 );

I prepared the following data file (weather.txt):
San Francisco   43  57  0.0 '1994-11-29'
Hayward 54  37  0.0 '1994-11-29'

and ran the COPY command:
COPY weather FROM '~aviad/postsgres/playground/weather.txt';

now, when I run select * from weather; I see that single quotes appears around the city values.
This does not happen when I run simple INSERT e.g:
INSERT INTO weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');

I wonder:

*

*what is the reason for wrapping text values by single quotes?

*What is the correct way to put the text data in the file used by
COPY to avoid single quote wrapping?

A: What you describe in your question is obviously not what's really happening. COPY would fail trying to import string literals with redundant single quotes into a date column.
To get rid of redundant quotes, import to a temporary table with text column, then INSERT INTO the target table trimming the quotes:
CREATE TEMP TABLE wtmp (
   city text
 , temp_lo int
 , temp_hi int
 , prcp real
 , date text  -- note how I use text here.
);

COPY wtmp FROM '~aviad/postsgres/playground/weather.txt';

INSERT INTO weather (city, temp_lo, temp_hi, prcp, date)
SELECT city, temp_lo, temp_hi, prcp, trim(date, '''')::date
FROM   wtmp
-- ORDER BY ?
;

The temp table is dropped automatically at the end of your session.
Reserved words as identifiers
I see you copied the example from the manual. Here is the deep link to the current manual.
While being correct, that example in the manual is unfortunate. I'd advise not to use reserved words like date as column names. As you can see here date is a reserved word in every SQL standard. It's allowed to use in Postgres and I can see how it's tempting for a simple example. But that doesn't make it a good idea. Generally, you should be in the habit of avoiding reserved words as identifiers. It leads to confusing error messages and needlessly incompatible SQL code.

A: 1 - The practice of wrapping text in quoted identifiers is done in the event that the demiliter used within the file (comma in your case) also appears within the text string
2 - I do not know must about postgres, but if you specifiy the quoted identifier in your COPY command, it should remove it during the import:
COPY weather FROM '~aviad/postsgres/playground/weather.txt' (QUOTE '?');

something along those lines. Simply try replacing the ? with the quoted identifier - in your case, I would try this first:
COPY weather FROM '~aviad/postsgres/playground/weather.txt' (QUOTE '''');

You also might want to check out: http://www.postgresql.org/docs/9.2/static/sql-copy.html as there are many different switches you can use in the COPY command


text:
Q: Как из api забрать данные и записать в базу данных postgresql с помощью python?
import requests
import psycopg2
URL = 'url'
payload = {
    "secret_key": "",
    "company_id": '',
    "type":''
}

response = requests.get(
    URL,
    params=payload
)
json_in=response.json()

connection = psycopg2.connect(database="", user="", password="", host="", port=)
cursor = connection.cursor()

record = cursor.fetchall()
print("Data from Database:- ", record)
print(response.status_code)
print(json_in)

Я смогла вывести json, но вот как его дальше записать в таблицу не разобралась. Подскажите плиз как записать данные из api в postgresql базу? зы) гугл не помог((

A: Для того, чтоб записать json в базу данных необходимо выполнить следующее
import psycopg2

try:
    connection = psycopg2.connect(database="", user="", password="", host="", port="")
    cursor = connection.cursor()
    cursor.execute("INSERT INTO yami(js1) VALUES ('{}')".format(json.dumps(json_in)))

    connection.commit()
    count = cursor.rowcount
    print(count, "Record inserted successfully into mobile table")

except (Exception, psycopg2.Error) as error:
    print("Failed to insert record into mobile table", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")


text:
Q: How do I debug MSpec tests in MonoDevelop/Xamarin Studio? Using MonoDevelop 5.x on OSX, I have some failing unit tests using Machine.Specifications that I would like to debug through to find the specific issue that's causing the failure. Is there a way to debug MSpec tests through MonoDevelop?

A: You can run MSpec code through custom commands allowing you to debug through your tests directly through MonoDevelop:

*

*Go to your project options

*Select Run > Custom Commands

*Select Execute under the dropdown menu

*For the command, browse and select your mspec runner

*Select Target File

*For the working directory, select Project Directory

You should now have a command that looks like ../path/to/mspec-clr.exe ${TargetFile}
You should now be able to place breakpoints in your test code, and start your tests with Start Debugging Item or running in debug mode.


text:
Q: Error while solving State space equations using ode45 My code should output me a column vector of X at the end of the program.I'm getting a lot of errors.
Please help!
    clc;
    clear;
    t0=0;
    tend=.001;
    T=[t0 .00005];
    T1=[.00005 tend];
    temp=1;
    X(:,1) = [0;0;0;0];

    for k=1:2
    for i= temp:50*(k)
            [T,X]=ode45(@(T,X)sys(T,X,A1,B1),T,X(:,1));
        else
            [T1,X1]=ode45(@(T1,X1)sys1(T1,X1,A0,B0),T1,X(:,end));
        end
    end
    temp=50;
    end

    function Xdot = sys(T,X,A1,B1,U)
    Xdot= A1*X + B1*U;
    end
    function Xdot = sys1(T1,X,A0,B0,U)
    Xdot= A0*X + B0*U;
    end

The errors are as follows:
Not enough input arguments.
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:});   % ODE15I sets args{1} to yp0.
 Error in ode45 (line 115)
    odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options,
    varargin);

A: It looks like you are not setting the argument U to the functions sys and sys1.
I have highlighted the corresponding places below with <U missing>:
if sw(i)==0 && X(2,i)> vdon || sw(i)==1 && X(1,i)>0
    sw(i+1)=1;
    [T,X] = ode45( @(T,X) sys(T,X,A1,B1, <U missing> ), T, X(:,1) );
else
    sw(i+1)=0;
    [T1,X1] = ode45( @(T1,X1) sys1(T1,X1,A0,B0, <U missing> ), T1, X(:,end) );
end


text:
Q: Using 'If' and 'ElseIf' function to identify if a cell holds a specific string, then deleting the row I'm currently trying to create a code in VBA that identifies the string in Cell ("C" & (Int)), following which, if it has the value of "CHK," for example, it deletes the entire row. The following is the code I've put together which is not currently functioning as intended, in that no cells with the values specified are getting removed.
'''
    For i = 1 To Count Step 1

            If ws1.Range("C" & d).Value = "CHK" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "SOR" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "CAN" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "FBE" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "CHP" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "FER" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "FPE" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "SUN" Then

                 ws1.Range("C" & d).EntireRow.Delete

            ElseIf ws1.Range("C" & d).Value = "MAZ" Then

                 ws1.Range("C" & d).EntireRow.Delete

            End If

            d = d + 1
    Next

'''
I've tried another method of referring to the rows, which did not help;
'''
    ws1.Rows(d).EntireRow.Delete

'''
Which is also not functional.
I'm uncertain whether it's my method of Checking the string value of the cell that's flawed, or my method of deletion. To give you an idea of the intended effect of the code I've attached two tables, one displays the raw data, and one displays the intended effect of the code.

I initially had a table inserted here through text, but the formatting stuffed up, so I attached an image of the table as it appeared to me.
I'd be extremely appreciative of any help at all,
Thanks.

A: Your code deletes rows for me when the strings are in Column C, although not all of them because the incrementation of d causes you to be targeting rows going up, and you need to be going through them backwards if you want to get them all, because when you delete one the rows get renumbered.
Assuming that Count here is the number of rows to check, and you just want to check them all, reference usedRange.Rows.Count directly and step from the end to the beginning:
Dim ws1 As Worksheet: Set ws1 = ActiveSheet

For d = this.UsedRange.Rows.Count To 2 Step -1

  If ws1.Range("C" & d).Value = "CHK" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "SOR" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "CAN" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "FBE" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "CHP" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "FER" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "FPE" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "SUN" Then
      ws1.Range("C" & d).EntireRow.Delete
    ElseIf ws1.Range("C" & d).Value = "MAZ" Then
      ws1.Range("C" & d).EntireRow.Delete
    End If

 Next

and I think there are some ways to clean up that check.  You can use a regex, an array or LIKE, any of which will let you make one call.  Here are some implementations.  First with a regular expression, which will let you check all of the conditions at once.  I think specifying .Value is unnecessary so I'm just going to leave it out:
Dim ws1 As Worksheet: Set ws1 = ActiveSheet
Set parser = CreateObject("vbscript.regexp")
parser.Pattern = "^(CHK|SOR|CAN|FBE|CHP|FER|FPE|SUN|MAZ)$"

For d = ws1.UsedRange.Rows.Count To 2 Step -1

  If parser.test(ws1.Range("C" & d)) Then
    ws1.Range("C" & d).EntireRow.Delete
    End If

  Next

Now we've got one line of checking code and one line of deleting code to worry about trying to troubleshoot.  I'm also going to use the Cells() object to specify instead of Range (easier mathwise, you just specify row number and column number) and I'll also use Rows().Delete instead of Range.EntireRow.Delete.
Dim ws1 As Worksheet: Set ws1 = ActiveSheet
Set parser = CreateObject("vbscript.regexp")
parser.Pattern = "^(CHK|SOR|CAN|FBE|CHP|FER|FPE|SUN|MAZ)$"

For d = ws1.UsedRange.Rows.Count To 2 Step -1

  If parser.test(ws1.Cells(d, 3)) Then
    ws1.Rows(d).Delete
    End If

  Next

Just a little easier to work with, I think.  This works for me, it catches all the values, and it's going to be easier to troubleshoot because there's only a couple of lines to troubleshoot.
Now here's a version using like instead of the regular expression, you might find it simpler:
Dim ws1 As Worksheet: Set ws1 = ActiveSheet
Const vals As String = "|CHK|SOR|CAN|FBE|CHP|FER|FPE|SUN|MAZ|"

For d = ws1.UsedRange.Rows.Count To 2 Step -1

  If vals Like "*" & ws1.Cells(d, 3) & "*" Then
    ws1.Rows(d).Delete
    End If

  Next

or INSTR()
Dim ws1 As Worksheet: Set ws1 = ActiveSheet
Const vals As String = "|CHK|SOR|CAN|FBE|CHP|FER|FPE|SUN|MAZ|"

For d = ws1.UsedRange.Rows.Count To 2 Step -1

  If InStr(vals, ws1.Cells(d, 3)) Then
    ws1.Rows(d).Delete
    End If

  Next

Or you could use an array:
Dim ws1 As Worksheet: Set ws1 = ActiveSheet
Const vals As String = "CHK|SOR|CAN|FBE|CHP|FER|FPE|SUN|MAZ"
arr = Split(vals, "|")

For d = ws1.UsedRange.Rows.Count To 2 Step -1

  For Each a In arr
    If ws1.Cells(d, 3) = a Then
      ws1.Rows(d).Delete
      End If
    Next
  Next

This is slightly more complicated, but there are situations where looping through an array can be a little easier than trying to make text matches, for instance, if you had a list of numbers you want to check for.
Also, you can use filter on that array to return every element of the array that matches a certain value.  If it doesn't, the UBOUND of the returned array is -1.  If it returns a value (because the value in the cell matches one of the elements in the array), the UBOUND will be at least 0, so you can use that to make the check.  BUT if the cell is empty passing the empty string to filter will make it return every element in the array, so you have to check that the cell value is not "" in your IF statement:
Dim ws1 As Worksheet: Set ws1 = ActiveSheet
Const vals As String = "CHK|SOR|CAN|FBE|CHP|FER|FPE|SUN|MAZ"
arr = Split(vals, "|")

For d = ws1.UsedRange.Rows.Count To 2 Step -1

  If UBound(Filter(arr, ws1.Cells(d, 3))) >= 0 And ws1.Cells(d, 3) <> "" Then
    ws1.Rows(d).Delete
    End If

  Next

A: If...Then...Else vs Select Case
Dim drg As Range
Dim dCell As Range

For i = 1 To Count

    Set dCell = ws1.Range("C" & d)

    Select Case CStr(dCell.Value)
        Case "CHK", "SOR", "CAN", "FBE", "CHP", "FER", "FPE", "SUN", "MAZ"
            If drg Is Nothing Then
                Set drg = dCell
            Else
                Set drg = Union(drg, dCell)
            End If
    End Select

    d = d + 1

Next

If drg Is Nothing Then Exit Sub

drg.EntireRow.Delete

A: Try this.  It goes from the bottom, to the top, so that deleted rows do not cause a row to be bypassed.
Option Explicit

Sub aaaa()
    Dim Count As Long, i As Long
    Dim rangeCell As String
    Const valuesToDelete As String = "CHK,SOR,CAN,FBE,CHP,FER,FPE,SUN,MAZ"
    Dim ws1 As Excel.Worksheet
    Set ws1 = ActiveSheet

    Count = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row

    For i = Count To 1 Step -1
        rangeCell = ws1.Cells(i, "C").Value
        If InStr(rangeCell, valuesToDelete) > 0 Then
            ws1.Rows(i).EntireRow.Delete
        End If
    Next i

End Sub


text:
Q: Use mkcert certificate for local testing of PWA I'm trying to setup a local dev environment for a PWA I'm working on.
I have installed mkcert on my Mac and am able to host a https://localhost version on my computer.
Now I'd like to open the page on my Android phone. On the mkcert github it says:

Mobile devices
For the certificates to be trusted on mobile devices,
  you will have to install the root CA. It's the rootCA.pem file in the
  folder printed by mkcert -CAROOT.
On iOS, you can either use AirDrop, email the CA to yourself, or serve
  it from an HTTP server. After installing it, you must enable full
  trust in it. Note: earlier versions of mkcert ran into an iOS bug, if
  you can't see the root in "Certificate Trust Settings" you might have
  to update mkcert and regenerate the root.
For Android, you will have to install the CA and then enable user
  roots in the development build of your app. See this StackOverflow
  answer.
https://github.com/FiloSottile/mkcert

I installed the rootCA.pem on my phone. The part about "enabling user roots" doesn't apply, since this is not an app.
But when I open the page on my phone using https://[my-local-network-ip]:1234 I get a warning, that the certificate can't be trusted.
How can I trust the certificate so I can locally test the PWA on my phone?

A: I know you've probably moved on from this question, as it's almost a year on. However, I would like to share how I was able to test my PWA locally in a secure context.
Not making any assumptions about what framework / packaging / build system you're using:

*

*Generate a certificate & key using mkcert. If you are hosting your PWA locally & want to access it over your local IP address i.e. 192.168.1.x:3000 you also need to tell mkcert to generate a certificate that covers that IP address:

mkcert localhost 192.168.1.17

// The certificate is at "./localhost+1.pem" and the key at "./localhost+1-key.pem" ✅

Important note: most routers dynamically assign local IP addresses, so it's worthwhile assigning a static IP.

*Install your RootCA from mkcert onto your iOS or Android device. Follow the instructions in the mkcert docs

*Serve your generated certificates with your web server of choice. I use Create React App. You can see my answer about PWAs in secure context here

A: I agree with your goal - running a local TLS based setup can be useful in terms of productivity and early troubleshooting.
Your problem is DNS based and you need to access the TLS secured URL via the host name.
The only way you'll get DNS to match up on the Android side is to use an HTTP proxy, while running either an emulator or a device connected via USB.
In a nutshell I would do this:

*

*Issue your cert to a more real world domain name such as mycompany.com

*Add this domain name to DNS on your Mac book

*Install a free proxy such as proxyman on the Mac

*Configure the Android emulator or device to use the proxy (you will also need to trust the proxy's cert on Android and the Mac)

*Then browse to https://mycompany.com from Android

Full details are available in my write up


text:
Q: How to replace certain percentage of values with other values in image? I have an RGB image, I have to assign certain percentage of brightest pixels to 255 and certain percentage of darkest pixels to 0 for each channel. Is there a simple way to do this in numpy?

A: Here is a way to do it by sorting and finding the threshold and replacing them, however if you are looking for an efficient way, you really do not need to sort your image, you can use np.partition for it (your image is arr and I assume last dimension are for channels. Update 0.05 for desired percentage. For dark points it would be similar solution with minor changes):
b = arr.reshape(-1,arr.shape[-1])
n = int(0.05 * b.shape[0])
threshold = np.sort(b,0)[n]
arr[arr>threshold] = 100


text:
Q: Kubernetes - MinIO Failed to connect to console using browser According to the official MinIO Guide (https://docs.min.io/docs/minio-quickstart-guide.html):

For example, consider a MinIO deployment behind a proxy
https://minio.example.net, https://console.minio.example.net with
rules for forwarding traffic on port :9000 and :9001 to MinIO and the
MinIO Console respectively on the internal network. Set
MINIO_BROWSER_REDIRECT_URL to https://console.minio.example.net to
ensure the browser receives a valid reachable URL.

I have already setup a distributed minio using k3s and a Load Balancer service.
$ kubectl describe services minio-service -n minio

Name:                     minio-service
Namespace:                minio
Labels:                   app=minio
Annotations:              <none>
Selector:                 app=minio
Type:                     LoadBalancer
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.43.168.142
IPs:                      10.43.168.142
LoadBalancer Ingress:     192.168.10.119, 192.168.10.120, 192.168.10.70
Port:                     <unset>  9012/TCP
TargetPort:               9011/TCP
NodePort:                 <unset>  31423/TCP
Endpoints:                10.42.1.13:9011,10.42.2.12:9011
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

If I try curl -vf http://192.168.10.70:9012 I get

curl: (7) Failed to connect to 192.168.1.70 port 9012: Connection
timed out

Thus, I used export MINIO_BROWSER_REDIRECT_URL=http://192.168.10.70:9012 but it doesn't work. Am I doing something wrong with redirection? Does anyone know how to fix this?

A: I managed to make it work using port-forward.
Options:
kubectl port-forward minio-0 9000 -n minio

Forwarding from 127.0.0.1:9000 -> 9000

kubectl port-forward --address 192.168.10.70 pod/minio-0 9000 -n minio

Forwarding from 192.168.10.70:9000 -> 9000

kubectl port-forward --address 192.168.10.70 svc/minio-service 9012 -n minio

Forwarding from 192.168.10.70:9012 -> 9011

Note that in the third option, minio-service is a Load Balancer Service
apiVersion: v1
kind: Service
metadata:
  name: minio-service
  namespace: minio
  labels:
    app: minio
spec:
  type: LoadBalancer
  selector:
    app: minio
  ports:
  - port: 9012
    targetPort: 9011
    protocol: TCP

In statefulSet:
containers:
  ports:
  - containerPort: 9000
    hostPort: 9011


text:
Q: image into mail body in iphone how to insert uiimage into body of mail composer window.. i have with this code:

NSMutableString *emailBody = [[[NSMutableString allocinitWithString:@""] retain];
[emailBody appendString:@" type text here"];
UIImage *emailImage = [UIImage imageNamed:@"20-gear2.png"];    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
NSString *base64String = [imageData base64EncodedString];
[emailBody appendString:[NSString stringWithFormat:@"",base64String]];
NSLog(@"emailBody....%@", emailBody);
[emailBody appendString:@""];

    NSLog(@"emailBody1....%@", emailBody);

A: MFMailComposeViewController *mailComposerController =   [[MFMailComposeViewController alloc] init];
[mailComposerController  setSubject:@"Your subject"];
[mailComposerController setMessageBody:nil isHTML:YES];
NSData *imageData   =   UIImagePNGRepresentation([UIImage imageNamed:"your image.png"]);
[mailComposerController addAttachmentData:imageData mimeType:@"image/png" fileName:@"image.png"];

Hope this help you...

A: NSData *imageData = UIImagePNGRepresentation(yourImage);
[mailController addAttachmentData:imageData mimeType:@"image/png" fileName:imageName];


text:
Q: WTForm SelectField with values from database I want to extract values from the database and substitute them into the SelectField, but I get such an error. What am I doing wrong?
I tried the QuerySelectField, but as I understand it, I can not get the project value from there
forms.py
class SelectProjectForm(FlaskForm):
    project_choices = [(projects.id, projects.project) for projects in Projects.query.all()]
    project_select = SelectField("Project", choices=project_choices)

models.py
class Projects(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    project = db.Column(db.String(255), unique=True, nullable=False)

views.py
@main_blueprint.route("/")
def home():
    select_project = SelectProjectForm()
    return render_template("main/home.html",
                           select_project=select_project)

error
Traceback (most recent call last):
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/sqlalchemy/util/_collections.py", line 1030, in __call__
    return self.registry[key]
KeyError: 4504378816

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    app = create_app()
  File "/Users/davidamb/adv_it_flask_deploy_aws/accesses/project/server/__init__.py", line 49, in create_app
    from project.server.main.views import main_blueprint
  File "/Users/davidamb/adv_it_flask_deploy_aws/accesses/project/server/main/views.py", line 8, in <module>
    from project.server.main.forms import AddressForm, AppForm, SelectAddrForm, SelectAppForm, SelectProjectForm, AccessName, CreateProject
  File "/Users/davidamb/adv_it_flask_deploy_aws/accesses/project/server/main/forms.py", line 35, in <module>
    class SelectProjectForm(FlaskForm):
  File "/Users/davidamb/adv_it_flask_deploy_aws/accesses/project/server/main/forms.py", line 36, in SelectProjectForm
    project_choices = [(projects.id, projects.project) for projects in Projects.query.all()]
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 519, in __get__
    return type.query_class(mapper, session=self.sa.session())
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 78, in __call__
    return self.registry()
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/sqlalchemy/util/_collections.py", line 1032, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 3254, in __call__
    return self.class_(**local_kw)
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 136, in __init__
    self.app = app = db.get_app()
  File "/Users/davidamb/adv_it_flask_deploy_aws/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 982, in get_app
    'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

Thx for any help.


text:
Q: System.AggregateException at System.Threading.Tasks.TaskExceptionHolder.Finalize() Update:
Adding TaskCreationOptions.LongRunning solved the issue but is this a good approach ? If not, what is the best solution to get over this exception ?
There is an issue i am trying to troubleshoot. I have implemented the suggestions that were provided in StackOverFlow but those have not helped solve the issue. I have used other alternatives like ContinuwWith option instead of Task.WaitAll by attaching the extension method. This did not help either .
I have put Ex.handle { } and i have tried throw ex in the Catch(aggrgateException ex) in the exceptions but that did not help to catch the actual exception.
I have only .Net 4.0 installed so i cannot try the .Net 4.5 resolution to solve this
The exception that i have been getting all the time is

"System.AggregateException:" The task's exception was not observed either by waiting on the task or accessing the Exception property "

After this it simply kills worker process and the App crashes and i see an entry in the EventViewer
Any help here here will be appreciated.
We have the below code:
Task<List<MyBusinessObject>>[] tasks = new Task<List<MyBusinessObject>>[MyCollection.Count];

for (int i = 0; i < MyCollection.Count; i++)
{
    MyDTO dto = new MyDTO();

     --Some Property Assignment for the MyDTO object--

    tasks[i] = Task<List<MyBusinessObject>>.Factory.StartNew(MyDelegate, dto)

}

try
{
    Task.WaitAll(tasks);
}
catch (AggregateException e)
{
    AddToLogFile("Exceptions thrown by WaitAll() : ");

    for (int j = 0; j < e.InnerExceptions.Count; j++)
    {
        AddToLogFile(e.InnerExceptions[j].ToString());

    }
}
catch(Exception ex)

{

AddToLogFile(ex.Message);

}

Second Alternative
public Static Class Extensions
{
 public static void LogExceptions(this Task<List<<MyBusinessObject>> task)
        {
            task.ContinueWith(t =>
            {
                var aggException = t.Exception.Flatten();
                foreach (var exception in aggException.InnerExceptions)
                {
                    AddToLogFile("Task Exception: " + exception.Message);

                }
            },
            TaskContinuationOptions.OnlyOnFaulted);
        }
}
//In a different class call the extension method after starting the new tasks
Task<List<MyBusinessObject>>[] tasks = new Task<List<MyBusinessObject>>[MyCollection.Count];

for (int i = 0; i < MyCollection.Count; i++)
{
    MyDTO dto = new MyDTO();

     --Some Property Assignment for the MyDTO object--

    tasks[i] = Task<List<MyBusinessObject>>.Factory.StartNew(MyDelegate, dto).LogExceptions()

}

A: Instead of creating a new tasks for each iteration all at one time, i created the new task for 100 tasks every time. I then waited till all the tasks were complete and spwaned off another 100 tasks till all the tasks were finished
int count = Mycollection.Count();
                    Task>[] tasks;
        int i = 0;
                int j;
                while (i < count)
                {
                    j = 0;
                    tasks = new Task<List<MyBusinessObject>>[nbrOfTasks];
                    foreach (var p in Mycollection.Skip(i).Take(nbrOfTasks))
                    {
                        MyRequestDto dto = new MyRequestDto ();
                    --Some Proerty Assignment
                        tasks[j] = Task<List<MyBusinessObject>>.Factory.StartNew(MyDelegate, dto);
                        i++;
                        j++;
                    }

        try
                    {
                        // Wait for all the tasks to finish.
                        if (tasks != null && tasks.Count() > 0)
                        {
                            tasks = tasks.Where(t => t != null).ToArray();
                            Task.WaitAll(tasks);
                        }
                    }
        catch (AggregateException e)
                    {
            }

This is to do with the memory avaiable to service multiple tasks. If the required RAM was not available to service the concurrent tasks along the way, the App Would just crash.That is why it is best to spawn limited nbr of tasks. Instead of spwaning multiple and leaving it to the threadpool to manage.


text:
Q: "They are blindly optimistic to say the season is over."
They are blindly optimistic to say the season is over.

This is a line I am writing. I am trying to say

It is blindly optimistic of them to say the season is over.

Do the two sentences mean the same thing? I vaguely recall there is the structure "subject + be + adjective + to do something" that means the subject takes an action because they can be described as adjective. But I can't remember what the structure is called; nor am I able to find any explanation on the Internet.

A: I think the sentence is acceptable, but I would prefer:

They are blindly optimistic in saying the season is over.

The use of two present tense verbs, 'are' and 'saying', helps clarify the cause and effect nature of the statement you want to make.


text:
Q: How can I programmatically map XML fields in Excel 2013? I'm trying to programmatically map some fields from an XML file to a table in excel.
Manually, I go to the developer tab, hit the source button, select XML Maps, press the add button, paste in the path to my XML file, and Excel creates the XML map. I then click and drag the fields to certain cells in my worksheet. This works fine.
I figured I could use the macro recorder to capture this, however the actual mapping of the fields to the cells does not get recorded. The only thing that gets recorded is the creation of the map:
ActiveWorkbook.XmlMaps.Add( _
        "path_to_my_XML_file" _
        , "feed").Name = "feed_Map"

how can I programmatically map the fields to a range? Is it possible in VBA?


text:
Q: Second minimum salary with grouping I have such kind of table, imagine it's a salary per month for employee with id:

What query should I use to get second minimal salary for each employee?
Result should be smth like:
id month amount
 1   2     20
 2   2     30
 3   3     15

A: In ANSI standard SQL, you would use the dense_rank() function:
select t.*
from (select t.*,
              dense_rank() over (partition by id order by amount desc) as seqnum
      from t
     ) t
where seqnum = 2;

Note:  this gives the second largest value.  If there are ties for first, then it gives the second value.
EDIT:
In MySQL, you can do:
select t.*
from t
where t.amount = (select t2.amount
                  from t t2
                  where t.id = t2.id
                  order by t2.amount desc
                  limit 1, 1
                 );

Note:  this handles ties differently.  It will give the second amount, even if the same as the first.  I'm not sure which you want.


text:
Q: pandas replace column with mean for values I have a pandas dataframe and want replace each value with the mean for it.
    ID    X     Y
    1     a     1
    2     a     2
    3     a     3
    4     b     2
    5     b     4

How do I replace Y values with mean Y for every unique X?
    ID    X     Y
    1     a     2
    2     a     2
    3     a     2
    4     b     3
    5     b     3

A: Use transform:
df['Y'] = df.groupby('X')['Y'].transform('mean')
print (df)
   ID  X  Y
0   1  a  2
1   2  a  2
2   3  a  2
3   4  b  3
4   5  b  3

For new column in another DataFrame use map with drop_duplicates:
df1 = pd.DataFrame({'X':['a','a','b']})
print (df1)
   X
0  a
1  a
2  b

df1['Y'] = df1['X'].map(df.drop_duplicates('X').set_index('X')['Y'])
print (df1)
   X  Y
0  a  2
1  a  2
2  b  3

Another solution:
df1['Y'] = df1['X'].map(df.groupby('X')['Y'].mean())
print (df1)
   X  Y
0  a  2
1  a  2
2  b  3


text:
Q: replace some text in a existing PDF using PDFBOX To achieve this my approach is:-
1) first I will get the coordinates (X,Y) of the word which I have to replace
2)And then re-write on that word in Append mode.
Now, the problem is when I manually putting the coordinates after getting the coordinates separately. I am getting the appended file however, the text is appended at some other location
Last coordinate of char is:- s [(X=119.27521,Y=82.579956) height=5.52 width=4.3166428]
and I am writing through this code:-
contentStream.newLineAtOffset((float) 119.27521, (float) 82.579956);


text:
Q: I'm trying to trigger a directive by using a variable in the class but it is not working So if I run the following code my directive is triggered and everything works fine.

However, if I run ng-repeat with one of my variable, the directive is not triggered.
This is my ng-repeat statement

Here is the directive:
myApp.directive('message', [function() {
    return{
        restrict: "C",
        template:'Hello World!',
        link: function (scope, el, attrs) {
        }
    }
}])

Link to the fiddle
I could be wrong but I feel like I am overlooking something small. Thank you!

A: It will not going to work ever becuase ng-class is added after the directives of the element have been collected by angular. It's too late.
This issue explains it perfeclty.


text:
Q: Powershell get process statistics in percentage
How can I print CPU, memory, disk and network statistics in percentage for a particular process or service using Windows Powershell? I want to print the process statistics shown by task manager using Powershell. I tried using Get-Process cmdlet but it does not give values in percentage.


text:
Q: Get item name from Arraylist and compare I have an array list which is declared as
ArrayList<Item> items = new ArrayList<Item>();

In the below screenshot you can find out the array items in it:

Now how do I get that string and compare to my existing string value
Suppose I have a string name "inbox", how do I get the title named inbox.
public interface Item {

    public boolean isSection();

}

SectionItem
public class SectionItem implements Item{

    private final String title;

    public SectionItem(String title) {
        this.title = title;
    }

    public String getTitle(){
        return title;
    }

    @Override
    public boolean isSection() {
        return true;
    }

}

Can anyone suggest me a better way of handling this?

A: Using, get(int index) method of ArrayList.
which Returns the element at the specified position in this list.
In your case
String itemTitle = items.get(index).getTitle(); // Here index represent position of item you want to get title from current array list

A: The only way is to use a cast:
String sectiontitle = ((SectionItem)items.get(index)).getTitle();
Though, in my opinion, you should have a  String title; as a member of your interface Item

A: Just get the title by accesing the index, and if you are comparing strings you shuold use equals:
return items.get(index).getTitle().equals(myString);

if you want to iterate through the array do a for loop:
for(int index = 0; index < items.length() -1; index++) {
}


text:
Q: Usar arquivos JSON com JavaScript na web eu tenho um enorme array com inúmeros objetos, queria saber se posso exportalo para o meu arquivo JS principal?
já fiz:
module.exports = nomeDoArray
mas quando abro no navegador aparece a mensagem de error: 'require is not defined'

A: Se estiver usando Node apenas use require no arquivo json
const array = require('path./file.json');

no navegador vc pode usar o fetch ou o ajax para fazer a request do arquivo no servidor:
const array = await fetch('path/file.json').then(r => r.json());

A: Cara pelo o que entendi se está com um arquivo.html e dentro dele se tem um script.js e se quer que o script consiga acessar um arquivo com dados externo, certo?
Se for isso se vai ter que colocar o arquivo no teu código html, mas talvez vele apena avaliar uma mudança (atualização no teu código) que se for o que eu entendi tá bem arcaico


text:
Q: Python way to search for file in sys.path I would like to put my media and config files into a place where the Python program can find it from the working tree or from being installed. So in that question, it was suggested to put the stuff into the path. Is there some ready made function to search in the path?
If not, I will just make my own.

A: No, I don't think there's any python function to do this in the standard library. It should be very easy to write a function that searches each directory in sys.path for a file though.
A heavyweight alternative that may be suitable would be to look at packaging your module as a python package using setuptools and  and using pkg_resources.ResourceManager to load files from the package.


text:
Q: what does the expression stand for? What does the 0x%08x mean in the below statement?
printf("\t\t\t[in func3] i @ 0x%08x = %d\n", &i, i);

Does it mean prepend the result with 0x and give a 8 digit hexadecimal value?

A: printf("\t\t\t[in func3] i @ 0x%08x = %d\n", &i, i);

There are two format-strings here, and corresponding arguments:
%08x in 0x%08x: Print an int/unsigned with 8 hexadecimal digits including leading zeroes (after the 0x).
%#08x would be simpler for the same.
Anyway, it is Undefined Behavior as a pointer is not an int.
Use %p to print a data-pointer, after conversion to void*, char*, unsigned char* or signed char*.
The other one is %d for printing an int in standard decimal notation, so let's hope i is really one.
For reference, here the man-page for printf: http://man7.org/linux/man-pages/man3/printf.3.html


text:
Q: Android - How to make a pop up message notification like this? The pop up message is the Green one. I tried to use snackbar but many says Snackbar cant make custom layout and Toast doesnt have an action. So what should I use to make that green pop up message?

A: You can create a custom layout for Snackbar. Check-out the solution
https://stackoverflow.com/a/33441214/8122085


text:
Q: Numpy/Torch insert smallest value in case of collision I have an empty numpy array, a list of indices, and list of values associated with the indices. The issue is that there may be duplicates in the indices. In all these "collision" cases, I'd like the smallest value to be picked. Just wondering what is the best way to go about it.
Eg:
array = [0,0,0,0,0,0,0]
indices = [0, 0, 2, 3, 2, 4]
values = [1.0, 3.0, 3.5, 1.5, 2.5, 8.0]

Result:
out = [1.0, 0, 2.5, 1.5, 8.0, 0.0, 0.0]

A: You are looking for index_reduce_, which was introduced in PyTorch 1.12.
import torch

array = torch.zeros(7)
indices = torch.tensor([0, 0, 2, 3, 2, 4])
values = torch.tensor([1.0, 3.0, 3.5, 1.5, 2.5, 8.0])

out = array.index_reduce_(dim=0, index=indices, source=values, reduce='amin', include_self=False)

You'll get your desired output:

tensor([1.0000, 0.0000, 2.5000, 1.5000, 8.0000, 0.0000, 0.0000])

Note that this method is in "beta" and its API may change in future PyTorch versions.

A: You can always implement something manually like:
import numpy as np

def index_reduce(arr, indices, out, reducer=min):
    touched = np.zeros_like(out, dtype=np.bool_)
    for i, x in enumerate(indices):
        if not touched[x]:
            out[x] = arr[i]
            touched[x] = True
        else:
            out[x] = reducer(out[x], arr[i])
    return out

which essentially loops through the indices and assign the values of arr to out if not already touched (keeping track of this with the touched array) and reducing the output with the specified reducer.
NOTE: The reducer function needs to be such that the final result can only depend on the current and previous value.

The usage of this would be:
indices = [0, 0, 2, 3, 2, 4]
values = [1.0, 3.0, 3.5, 1.5, 2.5, 8.0]
array = np.zeros(7)

index_reduce(values, indices, array)
# array([1. , 0. , 2.5, 1.5, 8. , 0. , 0. ])

If performances are of concern, you can also accelerate the above code with Numba with a simple decoration provided that also the values and indices inputs are NumPy arrays:
import numba as nb

index_reduce_nb = nb.njit(index_reduce)

indices = np.array([0, 0, 2, 3, 2, 4])
values = np.array([1.0, 3.0, 3.5, 1.5, 2.5, 8.0])
array = np.zeros(7)

index_reduce_nb(values, indices, array)
# array([1. , 0. , 2.5, 1.5, 8. , 0. , 0. ])

Benchmarks
The above solutions can be compared to a Torch-based solution (reworked from @Shai's answer):
import torch

def index_reduce_torch(arr, indices, out, reduce_="amin"):
    arr = torch.from_numpy(arr)
    indices = torch.from_numpy(indices)
    out = torch.from_numpy(out)
    return out.index_reduce_(dim=0, index=indices, source=arr, reduce=reduce_, include_self=False).numpy()

or, with additional skipping of Torch gradients:
index_reduce_torch_ng = torch.no_grad()(index_reduce_torch)
index_reduce_torch_ng.__name__ = "index_reduce_torch_ng"

and a Pandas-based solution (reworked from @bpfrd's answer):
import pandas as pd

def index_reduce_pd(arr, indices, out, reducer=min):
    df = pd.DataFrame(data=zip(indices, arr))
    df1 = df.groupby(0, as_index=False).agg(reducer)
    out[df1[0]] = df1[1]
    return out

using the following code:
funcs = index_reduce, index_reduce_nb, index_reduce_pd, index_reduce_torch, index_reduce_torch_ng

timings = {}
for i in range(4, 18):
    n = 2 ** i
    print(f"n = {n}, i = {i}")
    extrema = 0, 2 * n
    indices = np.random.randint(*extrema, n)
    values = np.random.random(n)
    out = np.zeros(extrema[1] + 1)
    timings[n] = []
    base = funcs[0](values, indices, out)
    for func in funcs:
        res = func(values, indices, out)
        is_good = np.allclose(base, res)
        timed = %timeit -r 16 -n 16 -q -o func(values, indices, out)
        timing = timed.best * 1e6
        timings[n].append(timing if is_good else None)
        print(f"{func.__name__:>24}  {is_good}  {timing:10.3f} µs")

to produce with the additional lines:
import matplotlib.pyplot as plt

df = pd.DataFrame(data=timings, index=[func.__name__ for func in funcs]).transpose()
df.plot(marker='o', xlabel='Input size / #', ylabel='Best timing / µs', figsize=(6, 4))
df.plot(marker='o', xlabel='Input size / #', ylabel='Best timing / µs', ylim=[0, 500], figsize=(6, 4))
fig = plt.gcf()
fig.patch.set_facecolor('white')

these plots:

(the second is a zoomed-in version of the first).
These indicate that the Numba accelerated solution could be the fastest, closely followed by the Torch-based solution while the Pandas approach could be the slowest, even slower than the explicit solution without acceleration.

A: You can use pandas groupby agg as the following:
indices = [0, 0, 2, 3, 2, 4]
values = [1.0, 3.0, 3.5, 1.5, 2.5, 8.0]
array = [0,0,0,0,0,0,0]
df = pd.DataFrame(zip(indices, values), columns=['indices','values'])
df1 = df.groupby('indices', as_index=False).agg(values=('values', min))

for i,j in zip(df1['indices'].tolist(), df1['values'].tolist()):
    array[i] = j

output:
array
>[1.0, 0, 2.5, 1.5, 8.0, 0, 0]


text:
Q: RSpec stub a method that's used inside a controller I'm trying to stub a method that's called inside a controller, but it only gets stubbed within the test and not when it's called in the controller.
Target method:
class MyModel < ApplicationRecord
  def self.fetch_boolean(arg)
    MyModel.find_by({ name: arg })
    MyModel.value
  end
end

Target controller:
# controller
class OtherModelController < ApplicationController
  # ...

  if MyModel.fetch_boolean('123')
    # do something
  end

  # ...
end

RSpec test:
describe 'test' do
  before(:each) do
    allow(MyModel).to receive(:fetch_boolean).with('123').and_return(true)
  end

  it 'should do something' do
    get :show
    expect(response).to eq('hello')
  end
end

I called debugger within the RSpec test and called MyModel.fetch_boolean and got true. However, when I called it inside the controller, I got false (which is the stored value).
How do I make sure that the method inside the controller also gets stubbed?
RSpec version 3.7
Update:
Other stubbing syntaxes I've tried
allow(MyModel).to receive(:fetch_boolean).with('123') { true }
# same outcome

allow_any_instance_of(MyModel).to receive(:fetch_boolean).with('123') { true }
# error: MyModel does not implement #fetch_boolean

controller.stub(MyModel.fetch_boolean).with('123') { true }
# error: Wrong number of arguments. Expected 1, got 0

controller.stub(MyModel.fetch_boolean('123')) { true }
# error: true is not a symbol nor a string


text:
Q: How Can I Update Git on MacOS Version 10.15.5? I have Git version 2.24.3 on macOS and I don't know how to update it!

A: Download the latest stable Git release (latest source version
2.27.0) from the Git website. Click on the downloaded .dmg file, then double-click the .pkg icon to run the installer. This will install the new version of Git over the existing version:

When Git is installed check in the Terminal, launch the Terminal from /Applications/Utilities and check the version:
git --version

and the version will displayed.
Installing and upgrading Git from atlassian

A: Using HomeBrew you can use the brew update && brew upgrade to update all your programs via the terminal.
You should also check out this article: How To Upgrade Git


text:
Q: call mmap from assembly on Macos Catalina to reserve memory I have an assembly file with no linked libraries on MacOs Catalina that wants to call mmap to reserve some memory dynamically. I had thought I need to do something like
#define __NR_mmap 0x20000c5

#define PROT_READ 0x01
#define PROT_WRITE 0x02
#define PROT_EXEC 0x04
#define PROT_ALL (PROT_READ | PROT_WRITE | PROT_EXEC)

#define MAP_ANON 0x1000
#define MAP_SHARED      0x0001
#define MAP_PRIVATE     0x0002

#define USER_DEFS_SIZE 0x20000

        mov $__NR_mmap, %rax            //mmap
        xor %rdi,%rdi                   // start address
        and $USER_DEFS_SIZE,%rsi        // length
        mov $PROT_READ, %rdx            // rwx
        mov $(MAP_ANON|MAP_SHARED),%rcx // flags
        xor %r8,%r8                     // file descriptor
        xor %r9,%r9                     // offset
        syscall

but that returns 0x13 (ENODEV) in %rax. I tried passing file descriptor $-1 but that gives me an expected "bad file descriptor" error.
]

*

*Question1: What am I doing wrong - how do I call mmap correctly to reserve memory?

*Question2: how is the return address and errno returned? Can't rally both be in %rax, or can they? I'm unsure of the calling convention.
Thanks for helping me out.

A: First, there's the problem with %rsi being uninitialized, as Jester pointed out.
After that, you've got the system call ABI wrong. The fourth argument (the flags) should be passed in %r10, not %rcx.
An error is indicated by the CF flag of the flags register. If that is set, then %rax contains the errno; otherwise, the return value.
Finally, I should point out that Apple specifically states that the syscall ABI may be unstable from release to release of the OS. The stable ABI is the library wrapper layer (i.e. you should call _mmap from libSystem.dylib). They reserve the right to break at any time anything that does syscalls directly.


text:
Q: Why do we have $\|P_n-P\|_\mathcal{F}\to 0$ a.s.? I have a question about textbook high-dimensional statistics in Chapter 4.

Theorem: For a function class $\mathcal{F}$ is $b-$uniformly bounded, any positive $n\ge 1$ and any scalar $\delta\ge 0$ we have
$$
P(\|P_n-P\|_\mathcal{F}\le 2\mathcal{R}_n(\mathcal{F})+\delta)\le1-\exp(-\frac{n\delta^2}{2b^2})
$$
where $P_n$ is the sample mean and $P$ is the population average.
As $\mathcal{R}_n(\mathcal{F})=o(1)$, we have $\|P_n-P\|_\mathcal{F}\to 0$ in probability.

Question: why do we have $\|P_n-P\|_\mathcal{F}\to 0$ a.s.?

A: Define $A_n:=\{||P_n-P||_F\ge 2R_n(F)+\delta\}$. Note that $P(A_n)\le \exp(-n\delta^2/2b^2)$. Since $\sum_{n=1}^{\infty}P(A_n)<\infty$, it follows by Borel-Cantelli that $P(\{A_n i.o\})=0$. In other words, with probability $1$ only finitely many $A_n$'s happen. More elaborately, there exists a set $\Omega$ such that $P(\Omega)=1$ and for each $\omega\in \Omega$, we have $||P_n-P||_F\leq 2R_n(F)+\delta$ for all but finitely many $n$.


text:
Q: Why do we need hypothesis of complete measure in this version of Fubini's theorem? I'm reading below Fubini's theorem in page 3 of this lecture note.

Let $(X, \mathcal{A}, \mu)$ and $(Y, \mathcal{B}, \nu)$ be complete measure spaces, let $\gamma$ be the product outer measure on $X \times Y$ constructed above, and suppose that $f: X \times Y \rightarrow \mathbb{R}$ is $\gamma$-integrable. Then
(i) $f(x, y)$ is a $\mu$-integrable function of $x$ for $\nu$-a.e. $y \in Y$;
(ii) $\int_{X} f(x, y) d \mu(x)$ is a $\nu$-integrable function of y;
(iii) $\int_{Y}\left(\int_{X} f(x, y) d \mu(x)\right) d \nu(y)=\int_{X \times Y} f(x, y) d \gamma$.

In the proof,

*

*$C$ is a $\gamma$-measurable set of finite measure.

*For all $j$, $\left\{A_{i}^{j} \times B_{i}^{j}\mid i=1,2, \ldots\right\}$ is pairwise disjoint family of $\mathcal{A}, \mathcal{B}$ rectangles.

*$E=\cap_{j}\left(\cup_{i} A_{i}^{j} \times B_{i}^{j}\right) \setminus C$.
In my understanding, $E = \left [\cap_{j}\left(\cup_{i} A_{i}^{j} \times B_{i}^{j}\right) \right] \cap C^c$ is $\gamma$-measurable. Hence the $y$-slice $E_y$ of $E$ defined by $$E_y \triangleq \{x \in X \mid (x, y) \in E\}$$ is also measurable by the lemma in this question. I mean by this lemma that we don't need the hypothesis of measure completeness to obtain the measurability of $E_y$.
However, the author said that

But $\left.E \subset \cap\left(\cup_{i} E_{i}^{j} \times F_{i}^{j}\right)\right)$ and $\nu$ is a complete measure, so the slice $\{x:(x, y) \in E\}$ is also in $\mathcal{A}$ and also has $\mu$-measure zero for $\nu$-a.e. $y \in E$.

So they mean the measure completeness is necessary for the slice $E_y$ to be measurable.
Could you please elaborate on my confusion?

A: It is because $\gamma$ is not the product measure $\mu \times \nu$. Rather, $\gamma = \overline{\mu \times \nu}$, that is, $\gamma$ is the completion of the product measure $\mu \times \nu$. The measure space you are working with is $(X \times Y, \overline{\mathcal{A} \otimes \mathcal{B}}, \overline{\mu \times \nu})$.
It is not always the case that $E \in \overline{\mathcal{A} \otimes \mathcal{B}} \implies E_y \in \mathcal{A}$. For example, take $X = Y = [0, 1]$ with Lebesgue measure $m_1$ and Lebesgue sigma-algebra $L$. Let $S \subset [0, 1]$ be a set which is not Lebesgue-measurable. Then $E = S \times \{0\}$ is Lebesgue-measurable with $m_2(E) = 0$ since $S \times \{0\} \subset [0, 1] \times \{0\} \in L \otimes L$ and $m_2([0, 1] \times \{0\}) = 0$. However, $E_{0} = S$ is not Lebesgue-measurable.


text:
Q: How to make query with more than one argument in SSRS? There is a report with a few arguments - name, surname and others. For example, we have name "Jason" and surname "Statham". In this case I have to select all who are "Jason Statham". The second case: we have name "Jason" and surname empty. Now I need all "Jason" and surname doesn't matter.
When I used ms access I could do this with query like this:
SELECT name, surname, birthday
FROM dbo.guest AS g
INNER JOIN dbo.pass AS lp ON g.account = lp.account
WHERE name = @argName AND surname = @argSurname

But in SSRS, if surname isn't defined, this query select records where name is "Jason" and surname is empty. But when I don't define surname I mean "give me all Jason with any surname". How can I do it?


text:
Q: selenium declared package doesn't match expected package I am leaning selenium. I have trouble to run a sample script. Please help me to figure out what I did wrong. Thanks!
My installations:
JDK1.7.0._02
selenium-server-standalone-2.31.0.jar
Eclipse IDE 3.7.0
Selenium IDE 1.9.0 (Firefox plugin)
Eclipse indicates the following error message when I click on the package section in the code
1.the declared the package org.openqa.selenium.example; doesn't match expected package Seletest1
2. syntax error on token package, imported expected
Eclipse also suggested move Test1.java to package 'org.openqa.selenium.example
Please suggest the right action for me to take, should I imported org.openqa.selenium.example into the build path of my project or should I move Test1.java into the package?
where Can I find out the location of the package-org.openqa.selenium.example?
Here is my code copied from Google code get started with Selenium
my project structure SeleniumTest1>Src>SeleTet1
package SeleTest1;
package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Test1
{
    public static void main(String[] args)
    {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
    }

}

The error message showed when I execute the code
When I run the code in Eclipse, I received the following error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
   The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)

A: You have a duplicate package declaration on the top of your code. I would remove the second one (org.openqa.selenium.example) since your code is probably in the SeleTest1 folder.
Your package declaration is not required to match the one of the framework you are using.

A: When you export the selenmium IDE recorded test case into webdriver format, by default the package statement will get added as
package org.openqa.selenium.example;

We need to modify it as per our package name created in Eclipse.
So, in your case, you can remove the below duplicate line.
package org.openqa.selenium.example;

You will not get the 2nd error also once you have done this modification.


text:
Q: Javascript function parameter to String I have a javascript function which takes a parameter, like:
function getSomething(cat,handler) {

      varURI = 'text'+cat;
      document.write('
'+varURI+'
');

    }

What I see in the output is:
text[object Object]

How do I get the real textual value of the Object?

A: You need to override the toString method of the object -and give your object a "textual value"-.
You are getting "[object Object]" because the inherited Object.prototype.toString method is being executed, for example:
var cat = {
  name: 'Kitten',
  toString: function () {
    return this.name + ' meow';
  }
};

This own toString method will be executed when you make any implicit to string conversion (like when you concatenate a string to it), e.g.:
console.log(cat+' text'); // "Kitten meow text"

Note: If you mean by "textual value" a "string representation" of the object, (e.g. listing property/value pairs), your function will need to enumerate all the properties (using the for-in statement), but usually most of the time, that's done for debugging purposes, if that's the case, I would recommend you to get a debugger (like Firebug), and use the console.dir method.

A: I don't know what cat is, but usually you use the toString() method.
function getSomething(cat,handler) {

  varURI = 'text'+cat.toString();
  document.write('
'+varURI+'
');

}

A: You can make this:
function ObjectToString(input,KeysOnly) {
    var ret = [];
    if(KeysOnly)
       for(var k in input)
        ret[k] = input[k];
    else
        for(var k in input)
        ret.push(k);
    return ret.toString();
}

function getSomething(cat,handler) {

  varURI = 'text'+ObjectToString(cat);
  document.write('
'+varURI+'
');
}


text:
Q: Base table or view not found: 1146 Table 'prj_oxbir.permissions' doesn't exist Permissions file does exist on the folder though. Why this error is showing.

In Connection.php line 647:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
  'prj_oxbir.permissions' doesn't exist (SQL: select * from
  permissions)
In Connection.php line 319:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
  'prj_oxbir.permissions' doesn't exist

createrolestable.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('label')->nullable();
            $table->timestamps();
        });

        Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('label')->nullable();
            $table->timestamps();
        });

        Schema::create('permission_role', function (Blueprint $table) {
            $table->integer('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

            $table->integer('permission_id')->unsigned();
            $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');

            $table->primary(['role_id' , 'permission_id']);
        });

        Schema::create('role_user', function (Blueprint $table) {
            $table->integer('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->primary(['role_id' , 'user_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

A: First of all, make sure table permissions exist in the database.
Secondly, create a separate migrations for permissions table.
hope this helps.


text:
Q: How to have a horizontal line at the middle of a html heading with CSS? Ok I now use an image to do it, but I want to do it via CSS(no absolut or relative positioning, I'm looking to make it responsive).
Example here: http://teothemes.com/wp/services/. The heading is 'Services', right above the 3 content areas...I'd like to achieve the same effect with only CSS. I tried some things but it didn't work.
Thank you.

A: Here's how I'd do it -> http://tinkerbin.com/QN9efWHd

*

*CSS3 background-image

*span with background covering the background image.

the HTML...

    Services or Something

... for the CSS...
p {
    background: linear-gradient (to bottom,  rgba(145,37,37,0) 49%,
                rgba(145,37,37,1) 51%, rgba(145,37,37,1) 52%,
                rgba(145,37,37,0) 54%);
    text-align: center;
}

span {
    display: inline-block;
    padding: 0 10px;
    background: #fff;
}

A: Here's my go at it... Only thing is the spans have a set width.
HTML

    asdf

CSS
#hr span {
    width:200px;
    border-bottom:1px solid #ccc;
    display: inline-block;
    margin-bottom:5px;
}

DEMO

A: Using one floated span with a border:

Heading

.heading {
    width: 100%;
    text-align: center;
    line-height: 100%;
}

.heading span {
    float: left;
    margin: 20px 0 -8px;
    border: 1px solid;
    width: 100%;
}

.heading h3 {
    display: inline;
    padding: 0px 0px 0 20px;
    width: auto;
    margin: auto;
}

The negative base margin on the span may need to be adjusted for different heading sizes. , The background colour of the heading should match the background of the overall container.
JS Fiddle demo

A: I was looking at a bunch of solutions to this issue, and I really wanted something simple.  Why not just use the :before and :after to embed some content into the heading you want to have a horizontal-rule/line in.  In my CSS below I chose an EM DASH (unicode \2014) for the heading's horizontal line.  When making a larger horizontal line, and depending on your font, you need to take away letter spacing from multiple EM DASHes. Lastly you can add some padding to the head & tail of the EM DASH so that it doesn't press up against your heading text.
Here's some CSS, heading-1 is very simple, heading-2 has a longer line (see in action https://jsfiddle.net/pyxkh3jz/):
h1:before, h1:after {
    content:"\2014";
}
h2:before, h2:after {
    /* two dashes */
    content:"\2014\2014";
    /* depending on your font adjust this */
    letter-spacing: -6px;
}
/* add some padding so heading text isn't touching lines */
h2:before {
    padding-right: 15px;
}
h2:after {
    padding-left: 15px;
}

Haven't checked browser compatibility here; but this isn't radical CSS so it should work for some or most of you.  The lines and their length fit my use case.
This idea can probably be improved upon by other keeners...have at it!


text:
Q: rewriterules +httpd.conf +.htaccess problem (urgent-site down) I'm migrating one of my websites from dreamhost shared to dreamhost ps.
the files copied OK and DNS resolved to the new server. However trying to get a pagw brings error 403 access forbidden.
If I remove the .htaccess file from the directory of the site. the homepage loads OK but naturally any other page does not (because it requires rewriting currently defined in .htaccess).
I believe that httpd.conf blocks usage of .htaccess in the new server. quote:
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

I tried removing htaccess and implementing the rewrite rules in httpd.conf. without success.
My questions:
1. I tried AllowOverride All to make  .htacces work. It didn't change anything. What else should be checked/done to make it work?

*I created a directory section in httpd.conf with the directory in which the httpdocs sit and put all the rewrite rules there. (and restarted the server). it didn't have effect. Any hints on what should be done to add directory part with rewriterules to .httpd.conf and troubleshooting tips?

*How can I check if mod-rewrite is working on this server? It is enabled on the httpd.conf file. The server is on fastcgi mode.
Any other tips are very appreciated.
Thanks,
Niro
How can I move the rewrite rules in .htaccess in httpd.conf (and make it work)

A: The Directory / directive defines the base rules for all directories on the system.  Usually after defining a Directory / directive, you have a Directory /my/web/root/here directive with more liberal configuration settings.
Do not confuse Directory / to mean the webroot of your web site, this is not the case.
Your re-write rules should be applied either inside of the Directory /my/web/root/here directive, or the VirtualHost for the particular site (if you are using VirtualHosts, very common).
Changing AllowOverride to All in Directory / may be overwritten by a defined Directory /my/web/root/here, or a VirtualHost for the site in particular.
Perhaps if you could pastebin (http://www.paste2.org/) the entire Apache configuration, we could get a better idea of the issue.

A: The Apache user should have read access to the .htaccess file.

A: Thanks for the answers. I finally discovered that the actual httpd.conf file was under another path, It was not visible due to permissions. Just in case someone need it it was at:
/usr/local/dh/apache2/apache2-psnum/etc/ (psnum is the server number)
I placed the rewrites there under the directory section of my site and everything works.


text:
Q: Explain why the Hamming distance satisfies the triangle inequality
The Hamming distance satisfies the triangle inequality that is for all $x,y,u$ in $c$ such that $d(x,y) \le d(x,u) + d(u,y)$ where $c$ is a code. Also when does the equality hold?

My approach is: turn $x$ to $u$ by changing at most $d(x,u)$ letters and turn $u$ to $y$ by changing at most $d(u,y)$ letters. So turning $x$ to $t$ will change no more than $d(x,u) + d(u,y)$ letters.
By looking at the following example, $x = 001111, \ y = 111111, \ z = 011111$, the equality holds when changing $x$ to $y$, $z$ is just an intermediate step.
Does this make sense?

A: It's a good intuition, but some work is needed in order to translate it into a proof. For $x\in C$ assume that $x=x_1\ldots x_n$. For $x,y\in C$ let $D(x,y)=\{k:x_k\ne y_k\}$; then by definition $d(x,y)=|D(x,y)|$.
Now suppose that $x,y,z\in C$. Then
$$D(x,y)=D(x,z)\mathrel{\triangle}D(z,y)\subseteq D(x,z)\cup D(z,y)\;,$$
where $\triangle$ denotes the symmetric difference, and therefore
$$d(x,y)=|D(x,y)|\le|D(x,z)\cup D(z,y)|\le|D(x,z)|+|D(z,y)|=d(x,z)+d(z,y)\;.$$
The equality $D(x,y)=D(x,z)\mathrel{\triangle}D(z,y)$ is really just your observation that to get from $x$ to $y$, we can first flip the bits in $D(x,z)$ to get from $x$ to $z$ and then flip the bits in $D(z,y)$ to get from $z$ to $y$. The bits that are affected by at least one stage of this process are those in $D(x,z)\cup D(z,y)$, and those that are affected by both stages are those in $D(x,z)\cap D(z,y)$. Thus $D(x,y)$, the set of bits that are actually changed in going from $x$ to $y$ by way of $z$ are those in
$$\big(D(x,z)\cup D(z,y)\big)\setminus\big(D(x,z)\cap D(z,y)\big)=D(x,z)\mathrel{\triangle}D(z,y)\;.$$


text:
Q: RestFul web service which reads properties file I have got couple of Jersey REST Web services say SendPassword and ResetPassword whose purpose is to send email .
For sending email , i have configured a properties file under tomcat and all this works fine
The code of the SendPassword.java is somewhat this way
 @Path("/sendpassword")
    public class SendPassword {
        @GET
        @Produces("application/json")
        public String sendPasswordToEmail(@QueryParam("empid") String empid)
                throws JSONException
        {
            try {

            SendEmailUtility.sendmail("weqw","2312");

        }
        catch(Exception e)
        {
        }
}

SendEmailUtility.java
public class SendEmailUtility
    {
    public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
        String result = "fail";
        File configDir = new File(System.getProperty("catalina.base"), "conf");
        File configFile = new File(configDir, "email.properties");
        InputStream stream = new FileInputStream(configFile);
        Properties props_load = new Properties();
        props_load.load(stream);
        final String username = props_load.getProperty("username");
        final String password = props_load.getProperty("password");
        Properties props_send = new Properties();
        props_send.put("mail.smtp.auth","true");
        props_send.put("mail.smtp.starttls.enable","true");
                        Transport.send(message);
          // Some code to send email
            result = "success";
        } catch (MessagingException e) {
            result = "fail";
            e.printStackTrace();
        }
        return result;
    }

}

As you can see i am reading the properties file for every call of the websercice
(As reading operation is somewhat costly) , Is there any way to resolve this ??
Could you please let me know whats the best approach to handle this.
Thanks in advance .

A: I would recommend using resource bundle, which does not need InputStream
create a properties file and put directly inside your packages along with your java code
example folder structure
com
   - preethi
            -SendPassword.java
            -email.properties

Then you can code like
ResourceBundle props_load = ResourceBundle.getBundle("com.preethi.email");
final String username = props_load.getString("username");

This way you don't have to worry about opening and closing the stream or file path

A: There are few ways to do this the one way of doing it is to make the props_load a private static member of the class and call it like this
    public class SendEmailUtility
    {
       private static Properties props;

      private static Properties getProperties() {
       if (props == null) {
        File configDir = new File(System.getProperty("catalina.base"), "conf");
        File configFile = new File(configDir, "email.properties");
        InputStream stream = new FileInputStream(configFile);
        props = new Properties();
        props.load(stream);
    }
    return props;
    }
    public static String sendmail(String sendemalto,String generatedpwd) throws  IOException {
        String result = "fail";
        Properties props_load = getProperties();
        final String username = props_load.getProperty("username");
        final String password = props_load.getProperty("password");
        Properties props_send = new Properties();
        props_send.put("mail.smtp.auth","true");
        props_send.put("mail.smtp.starttls.enable","true");
                Transport.send(message);
          // Some code to send email
            result = "success";
        } catch (MessagingException e) {
            result = "fail";
            e.printStackTrace();
        }
        return result;
    }

}

The other design I would suggest is to make an email service class like EmailSender or EmailService and then inject it into SendPassword class
@Path("/sendpassword")
    public class SendPassword {
        @Autowired
        EmailService emailService;
        @GET
        @Produces("application/json")
        public String sendPasswordToEmail(@QueryParam("empid") String empid)
                throws JSONException
        {

A: You could use a lazy-getter to fetch and cache the Properties object.
private static Properties props;

private static Properties getProperties() {
    if (props == null) {
        File configDir = new File(System.getProperty("catalina.base"), "conf");
        File configFile = new File(configDir, "email.properties");
        InputStream stream = new FileInputStream(configFile);
        props = new Properties();
        props.load(stream);
    }
    return props;
}

Each time you want to use the Properties, call getProperties(). It will cache it the first time it's called. Each subsequent call will just return the cached object.
Note: This example does not catch any exceptions.