text:
Q: What version of Android is on the G1? I just uploaded my first app to the Android marketplace and one comments says, "It force closes on G1". What version of the Android OS does the G1 use?

A: The latest should have been Android 1.6, but originally it was shipped with Android 1.0 (Source).

A: Originally the G1 shipped with 1.0, then upgrades were released to update the phone to 1.1, 1.5 (Cupcake) and 1.6 (Donut).
So you would expect most users to be on 1.6.  However, there are a couple of extra things you may want to consider.
Firstly, some users will be running custom firmware.  A quite a few G1 users - me included - run community firmware on their devices, such as CyanogenMod.  Often these releases are 1.6 releases with 2.x functionality ported from the Android Open Source Project (AOSP) tree, so you could consider them as a hybrid release, putting the phone somewhere between 1.6 and 2.x.  I wouldn't worry about the people running custom firmware since they are so many different firmwares and builds of each firmware, and people who put custom firmware on their phone usually expect to fend for themselves.  I only mention it in case you get some weird bugs you really can't replicate which might be caused by this.
Secondly, I'd recommend looking at the Android Device Dashboard as this shows what fraction of users of all phones are running each release:

At the time of writing 31% of users are still on Android 1.5 and I would guess quite a few of these are running G1s.
So my advice would be to test your application on 1.5 and 1.6 if you want to support G1 users.

A: The latest update they've pushed out to the G1 is Android 1.6.  They're supposed to be working on trimming down 2.0 to make it fit on the G1 but so far it hasn't been available without hacking your phone.

A: Currently 1.6 (Donut), this is most likely the last OS version that will be on the G1.

A: Originally it was shipped with Android 1.0. Now it uses Android 1.6


text:
Q: PHP's mail() function causes a 500 Internal Server Error only after a certain point in the code Several days ago, all mail() calls in my custom PHP application cause a 500 Internal Server Error and the only error logged is Premature end of script headers. Running the file via SSH sometimes returns a segfault. The strange thing is no code changed between the time when the mail() call worked, and stopped working (changes are tracked in Git).
Even though no changes were made to the code, I still went through and did the normal checks (.htaccess, php.ini, custom error handler, etc), just to be safe.
I attempted to diagnose the problem by cutting out code in the application until the issue was pinpointed. However, this did not narrow it down to a specific piece of code, but rather the amount of code loaded into PHP (but not yet run) as the time of the mail() call.
In the trimmed application, I was able to get one mail() call to work, but the second would fail. The first call was immediately before an include call (require has same outcome). The second was at the very beginning of the included file (preceded only be the opening PHP tags).
My original thoughts were it was some sort of memory issue. Oddly, the memory usage required to cause the mail() call to throw an error changes based on which code is kept/removed from the overall application. In case it can still help, the memory usage for the current collection of code before including the file is:
Usage: 3113696
Max: 3352560
The memory usage after including the file is still unknown.
I've spoken to my host about the issue, and they claim nothing has changed that would cause this issue.
I have not been able to reproduce this issue in other applications.
Technologies Used

*

*PHP 5.3.10 (5.2.17 also affected)

*MySQLi (specifically custom class extending MySQLi)

*Suhosin Patch 0.9.10

Error Messages Logged

*

*Premature end of script headers: XXX, referer: XXX

TL;DR
What would cause my PHP application to start causing 500 Internal Server Errors when mail() is called after a certain point in the code (but not after any specific call) without any PHP code being changed?
Additional Notes

*

*Not a timeout issue - takes less than a second to load

*Not a memory limit issue - only using ~3MB when it crashes, but I have a 99MB limit

A: The problem appears if there are undeliverable emails - this can happen if you send an email to the same domain as you are web hosting. The webserver may be "misconfigured" to think it is mailserver for domain - this is the default setting in my new web host (w00t! or not)
Example: the web host for example.com sends a mail to archive@example.com but because of a misconfiguration(), the web host thinks it needs to deliver locally. This fails and the web server reports the mentioned error 500.
The fix is to configure server as not to act as a mail server for the domain. (My host had an option in the DNS control panel. :s). Test with sending to non-associated domain.

A: Sounds like sendmail or whatever mail() is trying to use to send the mail might be dying.  Try running the script in the command line and see what output you get.

A: Transferring to a different server with similar configuration solved the problem, so it appears that it was, in fact, and issue with the host's server (specific cause is unknown, and regrettably, it will probably remain a mystery).

A: This explicit code may be the reason, this page isn't working,
domain is currently unable to handle this request.
HTTP ERROR 500
can be avoided by using the advanced phpmailer class: https://github.com/PHPMailer/PHPMailer

A: The error must probably have occurred because the php file you used to send the mail was writable by group. You should use the permissions '644' for php.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'datetime.date' object has no attribute 'date' This code:
import datetime
d_tomorrow = datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
    ...
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)
    ...

resuls in this error:
'datetime.date' object has no attribute 'date'

What am I doing wrong?

A: Problem solved:
from datetime import datetime, time, date, timedelta
def tomorrow():
    d = date.today() + timedelta(days=1)
    t = time(0, 0)
    return datetime.combine(d, t)

models.DateTimeField expects the value to be datetime.datetime, not datetime.date
2015 Update:
Arrow makes this all much more straight forward.

Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios. Simply put, it helps you work with dates and times with fewer imports and a lot less code.
Arrow is heavily inspired by moment.js and requests.

A: I had this problem when using the model from django.contrib.admin. I had two similar models, both with a date field (and both using auto_now_date=True - complete red herring); one worked, one had this error.
Turned out to be
def __unicode__(self):
    return self.date

goes BANG, while this
def __unicode__(self):
    return u'%s' % self.date

works just fine. Which is kind of obvious after the event, as usual.

A: d_tomorrow is expected, by the Django ORM, to have a date attribute (apparently), but doesn't.
At any rate, you probably want to use a callable for the default date; otherwise, every model's default date will be "tomorrow" relative to the time the model class was initialized, not the time that the model is created. You might try this:
import datetime

def tomorrow():
  return datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
  timeout = models.DateTimeField(null=True, blank=True, default=tomorrow)

A: This works for me:
import datetime
from datetime import timedelta

tomorrow = datetime.date.today() + timedelta(days=1)

class Test(models.Model):
    timeout = models.DateTimeField(db_index=True, default=tomorrow)

Alternatively you could use tomorrow = datetime.datetime.now() + timedelta(days=1)

A: I tried out your code and it worked just fine. Can you verify that you are not modifying/redefining the import in some way?
Also try this:
import datetime as DT
d_tomorrow = DT.date.today() + DT.timedelta(days=1)

class Model(models.Model):
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)


text:
Q: Dropping Columns From Data frame to only show needed ones Basically i want to drop some columns that i don't need. And i'm kind of stumped why this is not working
import os
import pandas

def summarise(indir, outfile):
os.chdir(indir)
filelist = ".txt"
dflist = []
colnames = ["DSP Code", "Report Date", "Initial Date", "End Date", "Transaction Type", "Sale Type",
            "Distribution Channel", "Products Origin ID", "Product ID", "Artist", "Title", "Units Sold",
            "Retail Price", "Dealer Price", "Additional Revenue", "Warner Share", "Entity to be billed",
            "E retailer name", "E retailer Country", "End Consumer Country", "Price Code", "Currency Code"]
for filename in filelist:
    print(filename)
    df = pandas.read_csv('SYB_M_20171001_20171031.txt', header=None, encoding='utf-8', sep='\t', names=colnames,
                         skiprows=3)
    df['data_revenue'] = df['Units Sold'] * df['Dealer Price']  # Multiplying Units with Dealer price = Revenue
    df = df.sort_values(['End Consumer Country', 'Currency Code'])  # Sorts the columns alphabetically
    df.to_csv(outfile + r"\output.csv", index=None)
    dflist.append(filename)
    df.drop(columns='DSP Code')

summarise(r"O:\James Upson\Sound Track Your Brand Testing\SYB Test",
      r"O:\James Upson\Sound Track Your Brand Testing\SYB Test Formatted")

I want to drop all the column titles you can see in colnames excluding 'Units Sold', 'Dealer Price', 'End Consumer Country', 'Currency Code'. I tried to remove one column using df.drop(columns='DSP Code') but this doesn't seem to work.
Any help would be greatly appreciated :)

A: You Can do it like :
df.drop(['Col_1', 'col_2'], axis=1, inplace=True)

OR:
df = df.drop(columns=colnames)

As suggested in comment section use usecols which provides a kind of filter to trim down the column section to use only which are require rest columns will not be processes and thus efficiency will be increased and resource consumption will also be less:
df = pandas.read_csv('SYB_M_20171001_20171031.txt', encoding='utf-8', sep='\t', usecols=["col1", "col2", "col3"],skiprows=3)

A: df.drop(columns='DSP Code')

this bit is not working cause you are not assigning it to a new df
df = df.drop(columns='DSP Code')

You can also just keep the columns you care about by copying them into a second dataframe.

A: According to pandas.DataFrame.drop, it returns a dataframe unless you do the operation inplace.

Returns:
  dropped : pandas.DataFrame
inplace : bool, default False
If True, do operation inplace and return None.

Either do it in place: df.drop(columns=['DSP Code'], inplace=True) or store the returned dataframe: df=df.drop(columns=['DSP Code'])

A: Just do:
df = df['Units Sold', 'Dealer Price', 'End Consumer Country', 'Currency Code']

You keep the ones you want, instead of dropping the others.


text:
Q: Site fonts and javascripts running slow due to excess scripts I have a site that's taking a really long time to load its font-face kit styles, as well as a couple of other scripts that are running funny. This is happening because my scripts are all jumbled in my  section, but I'm afraid that I don't know enough about these scripts to clean up my files correctly. Can anyone take a stab at suggesting some things I could do to clean this up and improve the speed and functionality of my site, particularly with loading the font-face text more quickly? Any examples or specific references would be great - I'm pretty lost on what all exactly is going on with these scripts. Here's what's happening in my :
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=0.3">
    <meta name="google-translate-customization" content="d378d0a5e57245bf-c2ed76fd752675aa-g7014305900f205ae-13"></meta>

    <title>{embed:title}</title>
    <style type="text/css" media="screen">
         @import url("/common/css/all.css");
         @import url("/common/font_face/stylesheet.css");
         @import url("/common/css/jcf.css");
    </style>

    <script type="text/javascript" src="/common/js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="/common/js/jquery.main.js"></script>

    <!--fancybox script starts here-->
    <script type="text/javascript" src="/common/js/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
    <script type="text/javascript" src="/common/js/fancybox/source/jquery.fancybox.js?v=2.0.6"></script>
    <link rel="stylesheet" type="text/css" href="/common/js/fancybox/source/jquery.fancybox.css?v=2.0.6" media="screen" />
    <link rel="stylesheet" href="/common/js/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.2" type="text/css" media="screen" />
    <script type="text/javascript" src="/common/js/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.2"></script>
    <script type="text/javascript" src="/common/js/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.0"></script>
    <link rel="stylesheet" href="/common/js/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=2.0.6" type="text/css" media="screen" />
    <script type="text/javascript" src="/common/js/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=2.0.6"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            // fancybox for html pages
            $(".fancylink").fancybox({
                'height' : '100%',
                'autoScale' : false,
                'transitionIn' : 'none',
                'transitionOut' : 'none',
                'type' : 'iframe'
             });
             $(".fancylinksm").fancybox({
                'height' : 'auto',
                'autoScale' : false,
                'transitionIn' : 'none',
                'transitionOut' : 'none',
                'type' : 'iframe'
             });

             // fancybox for vimeo
             $(".vimeo").fancybox({
                width: 781,
                height: 440,
                type: 'iframe',
                fitToView : false,
                wrapCSS : 'fancybox-nav-video'
             });

             $('.fancybox').fancybox({
                padding : 0,
                openEffect  : 'elastic'
             });

             $(".fancybox").fancybox({
                wrapCSS    : 'fancybox-custom',
                closeClick : true,
                helpers : {
                   overlay : {
                      css : {
                         'background-color' : '#000'
                      }
                   },
                   thumbs : {
                      width : 50,
                      height : 50
                   }
                }
            });
         });
       $("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.png'],a[href$='.gif']").attr('rel', 'gallery').fancybox();
    </script>
    <!--fancybox script ends here-->
    <link rel="shortcut icon" href="/common/images/cut-and-paste-logo.ico" type="image/x-icon" />
</head>

UPDATED CODE
I compiled all of my scripts into one 'compiled.js' file and changed all @import calls to s, however it is still not making my fonts load any faster. Here is the new  section:
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=0.3">
    <meta name="google-translate-customization" content="d378d0a5e57245bf-c2ed76fd752675aa-g7014305900f205ae-13"></meta>

    <!-- meta data goes here -->
    <title>{embed:title}</title>

    <link rel='stylesheet' type='text/css' href='/common/font_face/stylesheet.css'>
    <link rel='stylesheet' type='text/css' href='/common/css/all.css'>
    <link rel='stylesheet' type='text/css' href='/common/css/jcf.css'>
    <link rel="stylesheet" type="text/css" href="/common/css/jquery.fancybox.css?v=2.0.6" media="screen" />
    <link rel="stylesheet" href="/common/css/jquery.fancybox-buttons.css?v=1.0.2" type="text/css" media="screen" />
    <link rel="stylesheet" href="/common/css/jquery.fancybox-thumbs.css?v=2.0.6" type="text/css" media="screen" />
    <link rel="shortcut icon" href="/common/images/characterized_logo_16x16.ico" type="image/x-icon" />
    <!--[if lt IE 9]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen"/><![endif]-->

    <script type="text/javascript" src="/common/js/compiled.js"></script>
</head>

A: You should change those @import statements to link tags, it affects performance in some browsers.
http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Ideally you want to concatenate all those JS files into one request. You can do that with a tool like Google closure compiler:
https://developers.google.com/closure/compiler/
So you run something like:
cd C:\path\to\src
java -jar C:\compiler.jar --js=jquery.main.js --js=jquery-1.8.3.js --js=fancybox\lib\jquery.mousewheel-3.0.6.pack.js --js_output_file=all.min.js

Here is some reading about using a JS bootloader to prevent blocking:
http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/

A: After optimizing my scripts, everything was running a bit faster, but not perfectly. As an experiment, in my main CSS file, I deleted the call for all of the @font-faces (there were about 10 of them).
I deleted these:
@font-face {
font-family: 'TradeGothicLTStdCnNo.18Ob';
src: url('../fonts/tradegothicltstd-cn18obl-webfont.eot');
src: url('../fonts/tradegothicltstd-cn18obl-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/tradegothicltstd-cn18obl-webfont.woff') format('woff'),
url('../fonts/tradegothicltstd-cn18obl-webfont.ttf') format('truetype'),
url('../fonts/tradegothicltstd-cn18obl-webfont.svg#TradeGothicLTStdCnNo.18Ob') format('svg');
font-weight: normal;
font-style: normal;
}

But am still calling this font css in my header
<link rel='stylesheet' type='text/css' href='/font_face/stylesheet.css'>

After doing that, everything is running smoothly, quickly, and across multiple browswers. Looks like @font-face was the real issue here. I still have my fonts being pulled through java script, so I have all of my custom fonts with no lag.


text:
Q: Intent.ACTION_SEND with image from resource I need to perform a realy simple thing - share an image with text.
What I found to be the best is the following
final Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, context
        .getString(R.string.fragment_etc_share_text));
sendIntent.setType("image/jpeg");
final Uri imageUri = Uri.parse("android.resource://"
        + getActivity().getPackageName() + "/"
        + R.drawable.share_attachment);
sendIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(sendIntent);

share_attachment is an .jpg picture.
It works fine except for the image extension. I got something like "23244232" in the attachment. If I download the file and add an ".jpg" to its name - it opens well. But without the extension many social networks don't send it.
I tried to use assets but had no success as it's not a file actually on the runtime.
Using an external storage is not an option because the app must work even on old devices without SD card and be stable on USB plug in and out.


text:
Q: What does $\lim\limits_{x \to \infty} f'(x)=3$ mean? What I did was to see that the function is behaving as a straight line with gradient $3$ at infinity which implies that the function has an oblique asymptote as $x \to \infty$ but my testing portal says the answer is wrong and that instead, the function is infinite of order $1$ with respect to $x$. I think both of these are correct otherwise I must be confusing terminologies here

A: Note that in order to have a oblique asymptotes

*

*$y=mx+n$ with $m,n\in \mathbb{R}$.

with
$$m=\lim_{x\rightarrow+\infty}\frac{f(x)}{x}$$
and
$$n=\lim_{x\rightarrow+\infty} (f(x)-mx)$$
both limit must exist.
Note that since the function is evantually strictly increasing $f(x)\to +\infty$ thus
$$\lim_{x\rightarrow+\infty}\frac{f(x)}{x}= \lim_{x\rightarrow+\infty}f'(x)=3$$
thus $f(x)=\mathcal O(x)$.

A: The existence of an oblique asymptote is too strong. The derivative may approach 3 while the graph is not necessarily asymptotic to the line y=3x+b. It may oscillate and cross that line infinitely many times.

A: An example of a function on $\mathbb R$ with $\lim_{x\to\infty} f'(x) = 0$ but does not have a horizontal asymptote is $\log(1+x^2)$. If you prefer $f'(x) = 3$, try
$$f(x) = 3x+\log(1+x^2).$$


text:
Q: Are there new shortcut keys in recent update (04-2019)? Alt+F1 and Alt+Tab+Right takes me to lock screen. Alt+Tab+Left takes me to a terminal outside of window manager.
Is this something that was introduced in a recent Ubuntu update, or is it just my system? These shortcuts do not appear in the keyboard settings.
edit: Using gnome, Ubuntu 18.04.2
edit2: After a reboot, everything is back to normal.


text:
Q: Kotlin Android, получить переменную из Strings в классе SQLite Как можно получить переменную из файла Strings в класса базы данных ?
Использую следующие методы, но безрезультативно, в активити все хорошо
var s = getString(R.string.peremOne)

Через
getResourses.getString()

тоже не работает
Спасибо за помощь


text:
Q: Are new orders of clone troopers immediately ready for deployment? To spark off the Clone Wars, Palpatine/Sidious had the clone army ordered a decade in advance, so that when the time comes they are ready for battle, and all that is needed is for him to "make it legal" for him to form a Grand Army of the Republic which, to the Jedi, is conveniently ready to defend the Republic when the Separatist droid army was discovered.
During the Clone Wars, new orders of clones were voted and approved by the Senate. Since the Kaminoans are in league with Palpatine, it is reasonable to assume these new orders were intended by Palpatine to fan the flames of war. As such, are these new orders for new baby clones or for new fully trained clones born ten years prior to the vote?

A: The original first generation clones all took about ten years to reach physical after they were decanted/born. So the clones who were ready to fight in Attack of the Clones were all 10 years old. When they say new units or new companies, the Kaminoans don't mean newly born, the just mean their training and maturity is finishing up just now.
Thus, the Republic bought the fully trained ready for action clones. The Senators voting for "a grand army of the republic" probably didn't know any of this, though.


text:
Q: How to create div, content of which will always be crossed out diagonally? So I have a div, content of which should always be crossed out diagonally.
I've tried few solutions with few elements that had absolute positions but it wasn't good enough, because content and size of the div that should be crossed out can vary, so crossing out should be adaptive as well.
Basically I need to make something like this: http://www.awesomescreenshot.com/0515d31j22

A: This should work for you.

.strike {
  position: relative;
  display: inline-block;
}
.strike:before {
  content: "";
  position: absolute;
  height: 1px;
  width: 120%;
  background: red;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(25deg);
}

$55.55

$555.55

$5555.55

A: A couple of linear gradients can do this and it will auto-size to the dimensions of the element and no degree notation is required.

div {
    width: 25%;
    height: 250px;
    margin: 1em auto;
    border:1px solid grey;
    position: relative;
}
div:after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top:0;
    left: 0;
background:
    linear-gradient(to bottom left, transparent 0%, transparent 50%, red 51%, transparent 51%, transparent 100%),
    linear-gradient(to bottom right, transparent 0%, transparent 50%, red 51%, transparent 51%, transparent 100%);

}


text:
Q: measure customized dojo widget performance In our application we have customized dojo widgets and we would like to calculate the performance in term of widget loading time and the time to load the large data sets with in widgets.
Could any one please let me know, do we have any tools available in the market to measure the performance of the widget?

A: I would use dojo unit tests frameworks DOH. Specifically this section. You might also find testing tools like selenium useful although I don't recommend it for this reason.


text:
Q: Event-B Rodin platform, Modelling relations for hotel system I'm a beginner on Event-B and I'm trying to model a hotel system. In context I have set of Rooms for booking Customer who can make a reservation, checkin, checkout and cancellation. I also have Permission when the room is Empty or Occupied and Options it means that the hotel has different types of room such as one beds, double beds, etc.
This is my context:
    CONTEXT
        HotelData   ›
    SETS
    ⚬   ROOMS    ›
    ⚬   CUSTOMERS    ›
    ⚬   PERMISSION   ›
    ⚬   OPTION   ›
    CONSTANTS
    ⚬   ROOM_NUMBER  ›
    ⚬   OCCUPIED     ›
    ⚬   EMPTY    ›
    ⚬   Options  ›
    AXIOMS
    ⚬   axm1:   finite(ROOMS) not theorem ›
    ⚬   axm3:   ROOM_NUMBER ∈ ROOMS → ℕ not theorem ›
    ⚬   axm4:   partition(PERMISSION, {OCCUPIED}, {EMPTY}) not theorem ›
    ⚬   axm5:   Options ∈ ROOMS ↔ OPTION not theorem ›
    ⚬   axm6:   dom(Options) = ROOMS not theorem ›
    ⚬   axm7:   ran(Options) = OPTION not theorem ›
    END

And my machine:
room_numbers is  showed at the first time as empty rooms.
vacant_room displayed whether it is OCCUPIED or EMPTY.
isBooked - relation between customer and room which our customer chose.
MACHINE
        HotelSystemBooking  ›
    SEES
    ⚬    HotelData
    VARIABLES
    ⚬   isBooked     ›
    ⚬   customer     ›
    ⚬   vacant_room  ›
    ⚬   r_number     ›
    ⚬   room_numbers     ›
    INVARIANTS
    ⚬   inv1:   isBooked ∈ CUSTOMERS ↔ ROOMS not theorem ›
    ⚬   inv2:   customer ∈ ℙ(CUSTOMERS) not theorem ›
    ⚬   inv3:   vacant_room ∈ PERMISSION not theorem ›
    ⚬   inv4:   r_number ∈ ROOMS ⇸ ℙ(ℕ) not theorem ›
    ⚬   inv5:   room_numbers ∈ ROOMS ⇸ ℕ not theorem ›
    ⚬   inv6:   ∀ f · f ∈ ROOMS ∧ f ∈ ran(isBooked) ⇒ f ∈ dom(r_number) ∧ f ∈ dom(room_numbers) ∧ f ∈ dom(Options) not theorem ›
    ⚬   inv7:   ¬(vacant_room = OCCUPIED ∧ vacant_room = EMPTY) not theorem ›
    EVENTS
    ⚬   INITIALISATION:  not extended ordinary ›
        THEN
        ⚬   act1:   isBooked ≔ ∅ ›
        ⚬   act2:   customer ≔ ∅ ›
        ⚬   act3:   vacant_room ≔ EMPTY ›
        ⚬   act4:   r_number ≔ ∅ ›
        ⚬   act5:   room_numbers ≔ ROOMS × {0} ›
        END

    ⚬   reservation:     not extended ordinary ›
        ANY
        ⚬   c    ›
        ⚬   r    ›
        ⚬   room_number  ›
        WHERE
        ⚬   grd1:   c ∈ CUSTOMERS not theorem ›
        ⚬   grd2:   r ∈ ROOMS not theorem ›
        ⚬   grd3:   room_number ∈ ℕ not theorem ›
        ⚬   grd4:   r ∈ dom(r_number) ∧ room_number ∉ r_number(r) not theorem ›
        ⚬   grd5:   room_number < room_numbers(r) not theorem ›
        THEN
        ⚬   act1:   isBooked ≔ isBooked ∪ {c ↦ r} ›
        ⚬   act2:   r_number(r) ≔ r_number(r) ∪ {room_number} ›
        END

    ⚬   cancellation:    not extended ordinary ›
        ANY
        ⚬   c    ›
        ⚬   r    ›
        ⚬   room_number  ›
        WHERE
        ⚬   grd1:   c ∈ CUSTOMERS ∧ r ∈ ROOMS ∧ (c ↦ r) ∈ isBooked not theorem ›
        ⚬   grd2:   r ∈ dom(room_numbers) ∧ room_number < room_numbers(r) not theorem ›
        ⚬   grd3:   r ∈ dom(r_number) ∧ room_number ∈ r_number(r) not theorem ›
        THEN
        ⚬   act1:   isBooked ≔ isBooked ∖ {c ↦ r} ›
        ⚬   act2:   r_number(r) ≔ r_number(r) ∖ {room_number} ›
        END

    ⚬   checkin:     not extended ordinary ›
        ANY
        ⚬   c    ›
        ⚬   size1    ›
        ⚬   r    ›
        WHERE
        ⚬   grd1:   c ∈ CUSTOMERS ∧ c ∈ dom(isBooked) not theorem ›
        ⚬   grd2:   size1 ∈ ℕ not theorem ›
        ⚬   grd3:   r ∈ ROOMS not theorem ›
        THEN
        ⚬   act1:   customer ≔ {c} ∪ dom(isBooked)  ›
        ⚬   act2:   room_numbers ≔ room_numbers ∪ {r ↦ size1} ›
        END

    ⚬   checkout:    not extended ordinary ›
        ANY
        ⚬   c    ›
        ⚬   r    ›
        WHERE
        ⚬   grd1:   c ∈ CUSTOMERS ∧ c ∈ dom(isBooked) ∧ r ∈ ROOMS ∧ (c ↦ r) ∈ isBooked not theorem ›
        THEN
        ⚬   act1:   isBooked ≔ {c} ⩤ isBooked ›
        ⚬   act2:   room_numbers ≔ {r} ⩤ room_numbers ›
        ⚬   act3:   r_number ≔ {r} ⩤ r_number ›
        END

    ⚬   reservation_query:   not extended ordinary ›
        ANY
        ⚬   r    ›
        WHERE
        ⚬   grd1:   r ∈ ROOMS not theorem ›
        THEN
        ⚬   act1:   customer ≔ isBooked∼[{r}] ›
        END

    ⚬   reservation_occupied:    not extended ordinary ›
        ANY
        ⚬   c    ›
        ⚬   o    ›
        WHERE
        ⚬   grd1:   c ∈ CUSTOMERS ∧ o ∈ OPTION ∧ (c ↦ o) ∈ isBooked;Options not theorem ›
        THEN
        ⚬   act1:   vacant_room ≔ OCCUPIED ›
        END

    ⚬   reservation_free:    not extended ordinary ›
        ANY
        ⚬   c    ›
        ⚬   o    ›
        WHERE
        ⚬   grd1:   c ∈ CUSTOMERS ∧ o ∈ OPTION ∧ (c ↦ o) ∉ isBooked;Options not theorem ›
        THEN
        ⚬   act1:   vacant_room ≔ EMPTY ›
        END

    END

I have some problems with reservation this line -> grd5:    room_number < room_numbers(r) what's wrog with that line? I have other problems in reservation but with inv6. The same inv but in cancellation. Inv5 - checkin and inv6 in checkout. I also want to improve it a little and want to know how can I express vacant_room in terms of room_numbers and thus I will remove that PERMISSION when it is OCCUPIED and EMPTY. Maybe you know how to make it better?
I tried to make a relations between different types of rooms and the customer but now it looks not so much as I expected. I think to update it a little bit and have some ideas. I thought that room_numbers need to decrease and to create a constant function for vacant_room to show maximum number of vacant rooms and maybe assign it once with room_numbers variable. And vacant_room variable express through room_numbers. But there is a question how can I make the relation between customer?


text:
Q: When a function should be declared inline in C++ I'm trying to rewrite some code I wrote time ago using some C++ good practices. To achieve such a goal I'm using as reference Effective C++ (1) and google coding convention (2). According to (2) a function should be declared inline if it is 10 lines or less, according to (1) furthermore the compiler could ignore the inline directive, for example when there are loops or recursion (just some example is provided so I don't know all the cases that would be ignored by the compiler).
Say I then have 2 functions, the first one is 10 lines, and there's no call to any other function and no external reference in general. The second one assume is still 10 lines but at some point there's a call to the first one
Something like
Type1 f(Type2 arg) {
   //10 lines of self contained code
}

Type3 g(Type4 arg) {
   //0 <= n <= 8 lines of code
   //g(x);
   //9 - n lines of code
}

I would declare the f inline, because of the suggestion given by google (fully justified) But I would be puzzled about g what would be a good practice here? Would declaring g as inline ignored by the compiler? If not can I still have the benefits of the inline directive?

A: In C++, the inline specifier does not affect whether a compiler will inline a function call. It has effects that make inlining possible, but that is not the main purpose. If you have a private helper function that you want to be inlined, instead ensure that it has internal linkage – e.g. by putting it in an anonymous namespace (C++11). A declaration with internal linkage can only be accessed from within the current compilation unit.
An inline function may have multiple definitions. This is important when you define a function inside a header file. Usually, you declare functions in a header and implement it in a .cpp file. Other compilation units include the declaration in the header and are later linked with the definition. But if the function is defined in a header, the same function now exists in multiple compilation units. When they are linked, the linker sees these multiple definitions for your function. Which is the correct definition? The linker will raise an error.
With an inline specifier, you tell the linker that these multiple definitions are OK, and they all refer to the same function. Additionally, the definition of an inline function must be present in the same compilation unit.
Some functions are implicitly inline – in particular, any methods and functions within a class declaration:
class Foo {
public:
  void method() { /* implicitly inline */ }
  static void static_method() { /* implicitly inline */ }
  friend void friend_function() { /* implicitly inline */ }
};

void free_function() { /* not implicitly inline */ }

Don't declare a function as inline because it is short. Declare it as inline because you've defined it in a header.
Further reading: inline specifier on cppreference.com
The Google style guide you cite does not discuss when the inline keyword should be used, but whether functions should be implemented inline (i.e. in the header file). For simple functions like getters in a class this is usually perfectly fine. For larger, more complicated functions, it is usually better to implement them separately (though this is not possible for templates).


text:
Q: Asterisk exit when answer() My asterisk can move around the extension with "Goto()" but it exits immediately when meets the answer application. Could anyone help me to figure out the problem?
Executing [6138@from-sip-external:1] Goto("SIP/10.65.104.17-00000005", "kiem-tra-so-goi-vao,s,1") in new stack
-- Goto (kiem-tra-so-goi-vao,s,1)
-- Executing [s@kiem-tra-so-goi-vao:1] Answer("SIP/10.65.104.17-00000005", "") in new stack
== Spawn extension (kiem-tra-so-goi-vao, s, 1) exited non-zero on 'SIP/10.65.104.17-00000005'

Below is my dialplan:
[from-sip-external]
exten => 1234,1(dest-ext),Goto(kiem-tra-so-goi-vao,s,1)

[kiem-tra-so-goi-vao]
exten => s,1,Answer()
exten => s,n,Playback(hello-world)
exten => s,n,hangup()

A: Most likly you have NAT or codec issues
To get more info you have enable sip debug
asterisk -r
sip set debug on

If you see in rtp part local ips, while connection from outside, that mean you have issues with nat.
IF you see "not acceptable here", that is codec.

A: I guess, it should be Hangup() not hangup(). I hope that will solve the problem. If not, most likely, codec mismatch is the culprit.
Change your last line to this.
same =>n, Hangup()


text:
Q: How can stylesheet auto-linking be stopped in Rails? By default, (at least, using scaffolding), Rails adds links to all stylesheets in the /app/assets/stylesheets directory.  I'd like to have multiple smaller stylesheets for organization, but only need to link to one that imports the rest in order to stay organized yet minimize HTTP requests.
Is there a way to disable this auto-inclusion, whether by configuring the asset pipeline or changing how they're included in the layout itself?
FWIW, I'm including the main stylesheet from application.html.haml using stylesheet_link_tag "application".

A: You can do this by modifying your application.css(.scss) file.
In that file there will be the following line:
require_tree .

Simply remove that and replace it with the includes you require.
application.css
require file1
require nested/folders/file2

Then you can have another file
main.css
require file2
require file3

And include them separately:
stylesheet_link_tag "application"
stylesheet_link_tag "main"

The stylesheet_link_tag can take an array too, if for some reason you want the css files to load in the same place, but with separate HTTP requests.
stylesheet_link_tag ["application", "main"]

The files with the requires are called manifest files.


text:
Q: create new UILabel when conditions are met looping through NSArray I have an NSArray with various parts divided by ,.
this array is much longer
citiesArray10000 = [NSArray arrayWithObjects:
                            @"33.572162&-112.087966&Phoenix&Arizona",
                            @"32.154289&-110.871062&735&Tucson Arizona ",
                            @"33.401926&-111.717379&Mesa&Arizona",
                            @"33.282874&-111.854943&Chandler&Arizona",
                            nil];

I loop through these to see if they meet certain conditions.
[citiesArray10000 enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
        // do something with object
        NSArray *coorArray = [object componentsSeparatedByString:@"&"];
        NSString *firstString = [coorArray objectAtIndex:0];
        NSString *secondString = [coorArray objectAtIndex:1];
        NSString *thirdString = [coorArray objectAtIndex:2];
        NSString *fourthString = [coorArray objectAtIndex:3];

if (fabs(crnLoc.coordinate.latitude - latitude) <= 1) {
            if (abs(crnLoc.coordinate.longitude - longitude <= 1)) {

                self.label.text = fourthString;
            }
        }

the labels will float on the surface of the screen depending on the coordinates of the object that meet the conditions
self.label.frame = CGRectMake(160,(((self.mheading-90)-β)*-5.688)+200, 30, 200);

self.label2.frame = CGRectMake(160,(((self.mheading-90)-β)*-5.688)+200, 30, 200);

where β has different values depending on the coordinates.
the problem is that if more than one object in the array meets the conditions I need to create another label and have it's text be the fourthString of that object.  Then when the condition isn't met any more delete that label.  Is there anyway to do this?

A: How about using tag?
When you iterating through the citiesArray10000 array, I think you can add a tag to the uilabel and later on, when the conditions not meet anymore, you can find the label by the tag and delete the label.
[citiesArray10000 enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
        // do something with object
        NSArray *coorArray = [object componentsSeparatedByString:@"&"];
        NSString *firstString = [coorArray objectAtIndex:0];
        NSString *secondString = [coorArray objectAtIndex:1];
        NSString *thirdString = [coorArray objectAtIndex:2];
        NSString *fourthString = [coorArray objectAtIndex:3];

if (fabs(crnLoc.coordinate.latitude - latitude) <= 1) {
            if (abs(crnLoc.coordinate.longitude - longitude <= 1)) {

                UILabel *label = (UILabel *)[self.view viewWithTag:idx];

                label.text = fourthString;

                // add the label to the view ...
            }
        }
    }


text:
Q: Cookies from within shiro ldap realm code I'm using shiro in my grails app for authentication and authorization. Out corporate architecture uses a separate LDAP server for each country we have offices in. Its a lot. I'm trying to set a cookie from with in the shiro realm code that I can check on the next login. I've tried the grails cookie plugin but apparently can't get the injection to work into the realm code.
Has anyone gotten something similar to work, if so any hints?

A: It helps if I put the injection in the right place, outside the method.


text:
Q: Speeding up COUNT(*) with multiple equality, in and join conditions I've got a little problem with how my SQL Server query performs.
This basically looks as follows (It's been generated by Dapper):
SELECT COUNT(*)
FROM Data AS D
INNER JOIN #Permission AS P
    ON P.CategoryId = D.CategoryId
    AND P.IndustryCode = D.IndustryCode
    AND P.GeographyId = D.GeographyId
WHERE D.Local = 0
AND D.DatasetId = @DatasetId
AND D.CurrencyId IN (@Currency0, @Currency1, @Currency2)
AND D.ExchangeId IN (@Exchange0, @Exchange1, @Exchange2);

Table has tens of millions of records and my counts seem to be too slow, taking like 15 seconds to execute, which is far too much. My temporary table contains about 100k rows. But this might vary due to user input.
This is the execution plan: https://www.brentozar.com/pastetheplan/?id=ryXwfmp8m
Table has the following relevant indexes:
CREATE NONCLUSTERED INDEX IX_Data_Test ON dbo.Data (Local, DatasetId, CurrencyId, ExchangeId) INCLUDE (CategoryId, IndustryCode, GeographyId)
WHERE Local = 0;

CREATE NONCLUSTERED INDEX IX_Data_Another ON dbo.Data (CategoryId, IndustryCode, GeographyId, Local, DatasetId, CurrencyId, ExchangeId)
WHERE Local = 0;

Both indexes seem to be useful, but SQL Server will ignore the second one and it builds query that will do the following:

*

*Seek predicate on Local

*Seek predicate on DatasetId

*Seek predicate range on CurrencyId (will build a internal values table first)

*Predicate range on ExchangeId

*Then do a HASH MATCH with #Permission table

What could be general recommendations to speed performance up of such a query? I have not yet tried dropping indexes and keeping the ones that have (CategoryId, IndustryCode, GeographyId) as first keys, but being able to filter these rows first would help a lot.
Also, I dislike IN clause that causes seek predicate ranges. Is it a good idea to rewrite query to run query per @Currency and per @Exchange and then SUM() their counts?


text:
Q: Azure Mobile Service: Serialization of Tables I have an Azure Mobile App Service, and PullAsync is failing silently.
At the back end, the DTO looks like this:
type TablesDto() =
    [<JsonProperty("id")>] member val Id = String.Empty with get, set
    [<JsonProperty("deleted")>] member val Deleted = false with get, set
    [<JsonProperty("createdAt")>] member val CreatedAt = Nullable<DateTimeOffset>() with get, set
    [<JsonProperty("updatedAt")>] member val UpdatedAt = Nullable<DateTimeOffset>() with get, set
    [<JsonProperty("version")>] member val Version = [||] with get, set
    interface ITableData with
        member this.Id with get() = this.Id and set(value) = this.Id <- value
        member this.Deleted with get() = this.Deleted and set(value) = this.Deleted <- value
        member this.CreatedAt with get() = this.CreatedAt and set(value) = this.CreatedAt <- value
        member this.UpdatedAt with get() = this.CreatedAt and set(value) = this.UpdatedAt <- value
        member this.Version with get() = this.Version and set(value) = this.Version <- value

type MyEntityDto() =
    inherit TablesDto()
    [<JsonProperty("entityName")>] member val EntityName = String.Empty with get, set

I am using a DomainManager to map objects from my database schema into this DTO form, but I'm not sure that's relevant.
At the front end (in the Xamarin Android app), the DTO is defined as
type MyEntityDto() =
    [<JsonProperty("id")>] member val Id = String.Empty with get, set
    [<JsonProperty("version"); AzureVersion>] member val Version = Unchecked.defaultof<String> with get, set
    [<JsonProperty("createdAt")>] member val CreatedUtc = DateTime.MinValue with get, set
    [<JsonProperty("updatedAt")>] member val UpdatedUtc = DateTime.MinValue with get, set
    [<JsonProperty("entityName")>] member val EntityName = String.Empty with get, set

For debugging purposes, I have used the following handler to inspect the JSON that comes back from the server:
#if DEBUG
type DebuggingHandler() =
    inherit DelegatingHandler()
    let deserialise content =
        try
            let deserialised = JsonConvert.DeserializeObject<MyEntitypDto[]>(content)
            deserialised |> ignore
        with
            | ex ->
                ex |> ignore
    override this.SendAsync(message, cancellationToken) =
        let sendAsync = base.SendAsync(message, cancellationToken)
        async {
            let! response = sendAsync |> Async.AwaitTask
            let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask
            deserialise content
            return response
        } |> Async.StartAsTask
#endif

Inspecting the content value in the debugger shows this:
[{"myEntityName@":"Harry","id@":"2","deleted@":true,"createdAt@":"2017-04-26T11:20:46.83Z","updatedAt@":"2017-04-26T11:20:46.83Z","version@":"AAAAAAAAO/Y="},
{"myEntityName@":"Gary","id@":"3","deleted@":false,"createdAt@":"2017-04-26T11:23:05.16Z","updatedAt@":"2017-04-26T11:23:05.16Z","version@":"AAAAAAAAO/c="}]

What is happening with this "@" symbol suffix? It prevents the object from deserialising in the debugger, and I suspect this is why the PullAsync method is recycling.
Is this some weird side-effect of F#? How can I get rid of these "@" symbols (if that is what is causing my tables sync to break)?
EDIT I've added a C# tag because this may be related to the difference between F# and C# in a typical enterprise environment.

A: Fyodor's comment was the prompt I needed to find the answer.
In Azure mobile apps, the JSON formatters that come out of the box with the table controller can't be trusted to serialise F# objects correctly. So you'll need the following pieces of customisation:

*

*Create a formatter that uses JSON.Net:
type JsonDotNetFormatter() as this =
    inherit MediaTypeFormatter()
    do this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"))
    let settings = new JsonSerializerSettings(ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
    do settings.ContractResolver <- new CamelCasePropertyNamesContractResolver()
    override __.CanReadType _ = true
    override __.CanWriteType _ = true
    override __.ReadFromStreamAsync(t, readStream, _, _) =
        async {
            use reader = new StreamReader(readStream)
            let! text = reader.ReadToEndAsync() |> Async.AwaitTask
            return JsonConvert.DeserializeObject(text, t)
        } |> Async.StartAsTask
    override __.WriteToStreamAsync(_, value, writeStream, _, _) =
        async {
            match box value with
            | null -> value |> ignore
            | _ ->
                let text = JsonConvert.SerializeObject(value, settings)
                use writer = new StreamWriter(writeStream)
                do! writer.WriteAsync(text) |> Async.AwaitTask
        } |> Async.StartAsTask :> Task

*Create a config provider, to be used in Startup.MobileApp.cs:
public class JsonDotNetConfigProvider : TableControllerConfigProvider
{
    public override void Configure(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        base.Configure(controllerSettings, controllerDescriptor);
        controllerSettings.Formatters.Insert(0, new JsonDotNetFormatter());
    }
}

*Add the config provider to your mobile app configuration in the Startup.Configure() method:
new MobileAppConfiguration()
    .AddTablesWithEntityFramework()
    .WithTableControllerConfigProvider(new JsonDotNetConfigProvider())
    .ApplyTo(config);

This should also work if you run into other generic serialisation issues unrelated to F#. I have mixed C# and F# in this example, but that is something you will probably have to do at some point if you want to write enterprise-level software based on F#.


text:
Q: VirtualHosts with Apache not respecting ServerName This has always bugged me and I've never got around to figuring out why Apache does this, I always resorted to the mod_vhost plugin to work around the issue.
Basically, I have 2 vhosts in sites-enabled (Ubuntu server), their contents:
<VirtualHost *>
DocumentRoot "/var/www/vhosta.domain.com/"
ServerName vhosta.domain.com
<Directory "/var/www/vhosta.domain.com/">
allow from all
Options +Indexes
</Directory>
</VirtualHost>

And
<VirtualHost *>
DocumentRoot "/var/www/vhostb.domain.com/"
ServerName vhostb.domain.com
<Directory "/var/www/vhostb.domain.com/">
allow from all
Options +Indexes
</Directory>
</VirtualHost>

Now logically these 2 would be accessible separately, however it seems that all requests to my server, no matter what vhosts I define on top of this, are going to vhosta.domain.com.
Am I missing something incredibly obvious? I really don't get why it's doing this..
Thanks

A: Before your virtual host definitions, you need something like:
NameVirtualHost *:80

You're doing name-based virtual hosts.  See the documentation here:
http://httpd.apache.org/docs/2.2/mod/core.html#namevirtualhost

A: You are missing a NameVirtualhost; however:

*

*DO NOT use VirtualHost *; use VirtualHost *:80 instead.

The following is the correct way:
NameVirtualHost *:80

<VirtualHost *:80>
  Servername vhosta
</VirtualHost>

<VirtualHost *:80>
  Servername vhostb
</VirtualHost>


text:
Q: CMake Error variable not found LIBXML2_INCLUDE_DIR (Gate-9.0) So, I'm currently installing Gate-9.0 it's a simulation kit based on Geant4. I'm following the installation guide in the documents which uses the
ccmake ../Gate-9.0

When itry to configure, it gives me this CMake Error:

CMake Error: The following variables are used in this project, but
they are set to NOTFOUND. Please set them or make sure they are set and tested correctly in the CMake files:
LIBXML2_INCLUDE_DIR(ADVANCED)
used as include directory in directory/home/art/Documents/Gate-9.0
used as include directory in directory /home/art/Documents/Gate-9.0
used as include directory in directory /home/art/Documents/Gate-9.0

I have the LIBXML2 library installed so i'm not really sure what to do. I'm not entirely familiar with linux-mint (and linux in general) so i appreciate any suggestions. Thanks! :)

A: I had a similar problem in the GATE 8.2 installation with optical photon applications. In ccmake, you need to press [t] to toggle advanced mode. There, you will have to find the lines that cause your problem:
*LIBXML2_INCLUDE_DIR      LIBXML2_INCLUDE_DIR-NOTFOUND
*LIBXML2-LIBRARY          LIBXML2_LIBRARY-NOTFOUND

Change them to:
*LIBXML2_INCLUDE_DIR      (path_to_include)/include/libxml2
*LIBXML2-LIBRARY          (path_to_lib)/lib/libxml2.so

After that, you should be able to successfully configure, generate and compile.


text:
Q: ¿Cómo encontrar un dato específico usando information_schema? Mi base de datos contiene varias tablas y desconozco totalmente en qué tabla vive mi dato, ni siquiera sé qué tipo de dato es, ¿cómo puedo usar information_schema para encontrar ese dato?
Por ejemplo, si tengo un número 5523456789 (pero podría ser un int, char, date...) y quiero saber en qué tabla y qué columna vive ese dato. ¿Cómo se haría?

A: Puedes hacer un dump (sqlDump) a tu base de dato(o bases de datos) y buscar el dato ahí.

A: Opción 1
Si usas PhpMyAdmin, el mismo cuenta con una opción de búsqueda global que puedes utilizar.
Opción 2
La siguiente procedure busca a través de todas las bases de datos - tablas - columnas:
Lo que hace básicamente es:

*

*Crea una tabla para almacenar la salida.

*Hace un bucle a través de la tabla COLUMNS de information_schema para obtener bases de datos, nombres de tablas y columnas.

*Ejecute una consulta count (*) en database.table para cada columna con la cadena de búsqueda apropiada en la condición where.

*Si count (*)> 0, significa que esa columna particular tiene el término de búsqueda.

*Inserta los datos (nombre de la base de datos, nombre de la tabla, nombre de la columna) en una tabla temporal.

*Hace un select * de la tabla para ver los nombres de bases de datos, tablas y columnas correspondientes con el término de búsqueda.

    -- Procedure para buscar en todos los campos de la BD
        DELIMITER $$
        -- Script para recorrer todas las tablas usando Information_Schema
        DROP PROCEDURE IF EXISTS get_table $$
        CREATE PROCEDURE get_table(in_search varchar(50))
        READS SQL DATA
        BEGIN
        DECLARE trunc_cmd VARCHAR(50);
        DECLARE search_string VARCHAR(250);
        DECLARE db,tbl,clmn CHAR(50);
        DECLARE done INT DEFAULT 0;
        DECLARE COUNTER INT;
        DECLARE table_cur CURSOR FOR
        SELECT concat('SELECT COUNT(*) INTO @CNT_VALUE FROM ',table_schema,'.',table_name,' WHERE ', column_name,' REGEXP "',in_search,'"') ,table_schema,table_name,column_name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA IN ('network_detail');
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
        -- Truncando la tabla para rellenar los datos para nuevas búsquedas.
        PREPARE trunc_cmd FROM "TRUNCATE TABLE temp_details;";
        EXECUTE trunc_cmd ;
        OPEN table_cur;
        table_loop:LOOP
        FETCH table_cur INTO search_string,db,tbl,clmn;
        -- Ejecutando la búsqueda
        SET @search_string = search_string;
        -- SELECT search_string;
        PREPARE search_string FROM @search_string;
        EXECUTE search_string;
        SET COUNTER = @CNT_VALUE;
        -- SELECT COUNTER;
        IF COUNTER>0 THEN
        -- Insertando resultados requeridos en la tabla
        INSERT INTO temp_details VALUES(db,tbl,clmn);
        END IF;
        IF done=1 THEN
        LEAVE table_loop;
        END IF;
        END LOOP;
        CLOSE table_cur;
        -- Mostrando los resultados
        SELECT concat("SELECT * FROM ",t_table, " WHERE ", t_field, " REGEXP '", in_search, "';") FROM temp_details;
        END $$
        DELIMITER ;


text:
Q: How can I improve sql paging query? I use following query for paging in my application (MVC4, SQL Server):
string sql = "SELECT Id, Name, Date, allCount FROM (" +
             "SELECT Id, Name, Date, COUNT(Id) OVER() as allCount, " +
             "ROW_NUMBER() OVER (ORDER BY Date DESC, Id ) AS RowNum FROM Products) AS SOD " +
             "WHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1 AND @RowsPerPage*(@PageNumber) ORDER BY Date DESC";

This works for me, but I want to know is it a normal approach to count allCount many times? I am afraid that to count allCount many times, will affect the speed for bulk data. But, In view I need count of all products to make pagination. Is it normal code if not, how can I change it?

A: I would perhaps inline your Between operation parameters in your .net. You can control the calculation to run only once. I personally don't trust SQL server to decide what is "deterministic" since I have been bitten a few times. Also why do you need to return allcount in EVERY row. If you are using ADO.Net rather than an ORM, then you can control your SQL as you want.
Do
SELECT Count(*);

SELECT id,
       name,
       date
FROM   (SELECT id,
               name,
               date,
               Row_number()
                 OVER (
                   ORDER BY date DESC, id ) AS RowNum
        FROM   products) AS SOD
WHERE  SOD.rownum BETWEEN @Start AND @End
ORDER  BY date DESC

Although I suspect that you can just use a HAVING clause instead of your inner query with WHERE.

A: Even though it might seem from the resulting data, that the COUNT(Id)-operation is performed once for every record in the dataset, the count is in fact only performed once. The query optimizer knows that the expression COUNT(Id) OVER() is independent of the current record, which allows it to only do the count once.
As such, I don't see anything wrong with your query, in terms of paging.


text:
Q: How to get the raw text from lxml element with Python I want to get the following inline text strings from the root element.
from lxml import etree

root = root = etree.fromstring(
'''

    text-first

        Child 1

    text-middle

        Child 2

    text-last

''')

root.text only returns the "text-first" including newlines
>>> build_text_list = etree.XPath("//text()")

>>> texts = build_text_list(root)
>>>
>>> texts
['\n    text-first\n    ', '\n        Child 1\n    ', '\n    text-middle\n    ', '\n        Child 2\n    ', '\n    text-last\n']
>>>
>>> for t in texts:
...     print t
...     print t.__dict__
...

    text-first

{'_parent': <Element p at 0x10140f638>, 'is_attribute': False, 'attrname': None, 'is_text': True, 'is_tail': False}

        Child 1

{'_parent': <Element span at 0x10140be18>, 'is_attribute': False, 'attrname': None, 'is_text': True, 'is_tail': False}

    text-middle

{'_parent': <Element span at 0x10140be18>, 'is_attribute': False, 'attrname': None, 'is_text': False, 'is_tail': True}

        Child 2

{'_parent': <Element span at 0x10140be60>, 'is_attribute': False, 'attrname': None, 'is_text': True, 'is_tail': False}

    text-last

{'_parent': <Element span at 0x10140be60>, 'is_attribute': False, 'attrname': None, 'is_text': False, 'is_tail': True}
>>>
>>> root.xpath("./p/following-sibling::text()") # following https://stackoverflow.com/a/39832753/1677041
[]

So, how can I get the text-first/middle/last parts from this?

A: etree is perfectly capable of this:
from lxml import etree

root: etree.Element = etree.fromstring(
'''

    text-first

        Child 1

    text-middle

        Child 2

    text-last

''')

print(
    root.text,
    root[0].tail,
    root[1].tail,
)

All elements are lists of their subelements, so the indexing here refers to the 2  elements. The tail attribute of any element contains the text directly after that element.
It will of course include newlines, so you might want to strip() the results: root.text.strip()

A: Your initial guess, //text() means: select all text nodes, no matter where in the document they are. What you actually would like to select are text nodes if they are an immediate child of p, or alternatively if they are not children of span.
The most precise answer given the input document you are showing is /p/text():
>>> root = etree.fromstring(
'''

text-first

    Child 1

text-middle

    Child 2

text-last

''')

>>> etree.XPath("/p/text()")(root)
['\n    text-first\n    ', '\n    text-middle\n    ', '\n    text-last\n']

Your own solution child::text() means: select text nodes if they are a child of the current context node. It works because XPath expressions are in this case evaluated using the root element, p, as context. That is why simply text() also works.
>>> etree.XPath("text()")(root)
['\n    text-first\n    ', '\n    text-middle\n    ', '\n    text-last\n']

A: My bad, xpath saves me in the end.
>>> root.xpath('child::text()')
['\n    text-first\n    ', '\n    text-middle\n    ', '\n    text-last\n']

A: print(root.xpath('normalize-space(//*)'))


text:
Q: I want to use pandas2ri in JUPYTER but tzlocal issue? Everytime I try to import the pandas2ri in jupyter, python interface:
from rpy2.robjects import pandas2ri

I get the following error:
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-28-cc52694d111a> in <module>()
----> 1 from rpy2.robjects import pandas2ri

/Users/sondosayyash/anaconda/lib/python3.6/site-packages/rpy2/robjects/pandas2ri.py in <module>()
     21 import numpy
     22 import pytz
---> 23 import tzlocal
     24 import warnings
     25

ModuleNotFoundError: No module named 'tzlocal'

I tried to use
from dateutil.tz import tzlocal

but that didn't seem to fix the issue.
I've already installed tzlocal and it is on my computer.  When I import pandas2ri on ipython, there is no problem.. the problem only occurs when calling in the jupyter environment.
this is the message I get when I try to install tzlocal again:
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020.

Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Requirement already satisfied: tzlocal in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (1.5.1)
Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from tzlocal) (2017.2)

A: I had a similar issue when running rpy2 in Jupyter. I did not have the package installed previously. I just installed the package and the error went away. You can try installing the package again to see if it helps resolve your issue.
pip install tzlocal

I must add that I am using Python 3.6.8 not 2.7

A: If using conda:
conda install tzlocal

worked.

A: I had a similar issue as yours. It turns out that my local lib did not have the tzlocal package. So I installed the package through Anaconda prompt:
pip install tzlocal

And the issue is gone.


text:
Q: Std mac / Windows issues I want to make my c++ program cross-platform and it uses std::cos and std::sin, I have no issues with it on windows but it doesn't work on mac, why is this and how can I solve the problem?
It gives out this error "no member named cos in std"
Thanks


text:
Q: "Unable to instantiate activity" error One of my Android apps has about 100,000 users and, about 10 times a week, I get the following exception being reported to me via Google's market tool:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{org.rebm.asp/org.rebm.asp.MainActivity}:
  java.lang.ClassNotFoundException: org.rebm.asp.MainActivity in loader dalvik.system.PathClassLoader[/mnt/asec/org.rebm.asp-1/pkg.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2753)
at android.app.ActivityThread.access$2500(ActivityThread.java:129)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2107)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: org.rebm.asp.MainActivity in loader dalvik.system.PathClassLoader[/mnt/asec/org.rebm.asp-1/pkg.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2651)
... 11 more

From searching online, this error usually indicates something is wrong with the manifest file and the package names being used. However, I can't reproduce this error on my own devices or on the emulator. I only know of this error through the market tool. All I can conclude is that it's a rare error because I know lots of people are using the app and none of the reviews indicate it crashes.
Does anyone know what the issue might be or how I can diagnose it?

A: Having the same "rare" issue on all published games.
Might be an issue with installs to SD card, or moving app to the SD card, then removing the SD card.
Other guess is that the app gets downloaded or installed multiple times somehow.
I haven't been able to reproduce this so not able to nail it down either.

A: The stack trace that you give in the question contains the proof that the problem is due to moving the app to the SD card:

java.lang.RuntimeException: Unable to
  instantiate activity
  ComponentInfo{org.rebm.asp/org.rebm.asp.MainActivity}:
  java.lang.ClassNotFoundException:
  org.rebm.asp.MainActivity in loader
  dalvik.system.PathClassLoader[/mnt/asec/org.rebm.asp-1/pkg.apk]

As you can see, the path to your application is contains /mnt/asec which is the Android secure application mount point.
In order to verify if this problem happens due to Apps2SD, you should check to see if all the stack traces you have include the /mnt/asec directory in the path to your application. If they are all so, you can be sure that it is an Apps2SD error.
As others have said, these kinds of problems sometime arise due to the SD card not being available when the application is being loaded or from a corrupt asec partition on the SD card.
Does your app, in any way, register itself to launch at boot or is it some sort of a widget that the system would try to load even when the SD card has not been mounted yet? If so, maybe you should turn off the option of moving the app to the SD card.

A: I had this issue but not with activity. Fixed with a workaround:
ClassLoader myClassLoader = TroubleClass.class.getClassLoader();
Thread.currentThread().setContextClassLoader(myClassLoader);

A: Try the following links:
"Unable to instantiate activity 1"
"Unable to instantiate activity 2"
Force close after adding resources and textview

A: It may happen that the app works fine on your eclipse and mobile, when you install it from eclipse but may crash when in the market (Happened to me), if the same happens to you, there are 2 things you need to do and you will get out of this situation.

*

*Clean the project and rebuild. (Using Project-Clean)

*Delete and re-include the libraries, if any.


text:
Q: How to be more memory efficient than melt.data.table? For reshaping wide to long data, I've generally found that melt.data.table from the data.table package is the most memory efficient method. This has been compared favourably to the dplyr and base packages online in terms of memory. However, I've found myself unable to melt an object of about 11GB in size, returning the message:
Error: cannot allocate vector of size 10.5 Gb

My Windows computer has 32GB RAM, using 64-bit R. My melt command with a 5-row verison of the dataset is included below (which works). The actual data has nearly 200 million rows.
library(data.table)
test <- structure(list(time = structure(c(667150201.25, 667153801.25, 667157401.25, 667161001.25, 667164601.25), tzone = "UTC", class = c("POSIXct", "POSIXt")),
                       red = c(-2.25, -2.375, -2.5, -0.5, -1.625),
                       orange = c(1.625, 1.375, 1.625, 2.25, 2.5),
                       yellow = c(1.25, 0.5, 1.5, 1.5, 1.625),
                       green = c(2.875, 2.625, 2.5, 3.25, 3),
                       blue = c(4.75, 4.5, 4.75, 4.75, 5.125),
                       purple = c(0.125, -0.125, 0.5, 1.25, 1.375),
                       violet = c(3.125, 2.875, 3.125, 3.375, 3.375),
                       pink = c(3.75, 1.75, 1.5, 1, 0.5)),
                       row.names = c(NA, -5L), class = c("data.table","data.frame"))
melt(test, id.vars='time',
  measure.vars=c('red','orange','yellow','green','blue','purple','violet','pink'),
  variable.name='color', value.name="value")

Is there a more memory efficient method to convert the data form wide to long? The goal is to have a dataset with 3 columns: time, color, and the value.

A: If memory is the issue then taking smaller steps should solve it:
mv <- c('red','orange','yellow','green','blue','purple','violet','pink')
OUT <- data.table(color = character(0L), value = numeric(0L))
for (m in mv) {
  OUT <- rbind(OUT, test[, .(color = m, value = get(m))])
  set(test, j = m, value = NULL) # Delete the data since it is not necessary anymore
}
OUT[, time := rep(test$time, .N/nrow(test))]

A another option to try is RSQLite which will move the data straight into disk instead of memory:
library(RSQLite)

db_path <- 'C:/temp/temp.db'
test[, time := as.character(time)]
con <- dbConnect(SQLite(), db_path)
mv <- c('red','orange','yellow','green','blue','purple','violet','pink')
OUT <- data.table(time = character(0L), color = character(0L), value = numeric(0L))
dbWriteTable(con, "long", OUT)
for (m in mv) {
  dbWriteTable(
    con, "long",
    test[, .(time = time, color = m, value = get(m))],
    append = TRUE
  )
}

Now in a fresh session you can read it in steps:
step_size <- 20000L
IN <- data.table(time = character(0L), color = character(0L), value = numeric(0L))
rs <- dbSendQuery(con, "SELECT * FROM long")
while (!dbHasCompleted(rs)) {
  IN <- rbind(IN, dbFetch(rs, n = step_size))
}
dbClearResult(rs)
dbDisconnect(con)

A: perhaps an approach like this could work? I have no idea how to measure actual mem-usage..
library(data.table)
test.split <- split.default(test[, -1], names(test)[-1], )
data.table::rbindlist(lapply(test.split, cbind, test$time), use.names = FALSE, id = "color")


text:
Q: How do I set the matplotlib window size for the MacOSX backend? I have a python plotting function that creates a grid of matplotlib subplots and I want the size of the window the plots are drawn in to depend on the size of the subplot grid. For example, if the subplots grid is 5 rows by 5 columns (25 subplots) the window size needs to be bigger than one where there is only 5 subplots in a single column. I'm not sure how to control the window size matplotlib creates plots in. Can someone tell me how to control the plot window size for matplotlib using the MacOSX backend?

A: For all backends, the window size is controlled by the figsize argument.
For example:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(5, 5, figsize=(12, 10))
plt.show()

If you're creating the figure and subplots separately, you can specify the size to plt.figure (This is exactly equivalent to the snippet above):
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(12, 10))
for i in range(1, 26):
    fig.add_subplot(5, 5, i)
plt.show()

In general, for any matplotlib figure object, you can also call fig.set_size_inches((width, height)) to change the size of the figure.


text:
Q: need help on java swing layout Below are my code to add label and textfield.
i want to add it such that its [label] [textfield] in 2 column
i know i can do it by using gridlayout but the number of rows need to be fixed, hence is there another method to add it such that no matters how many [label] [textfield] i add in, it will be 2 column
the picture shows the expected view
but currently it is [label] [textfield] [label2] [textfield2] [label3] [textfield3]
  public WizardPage page1() {
           WizardPage page1 = new WizardPage("1", "Page 1") {
               {
                   JTextField txt1 = new JTextField();
                   JTextField txt2 = new JTextField();
                   JTextField txt3 = new JTextField();
                   JTextField txt4 = new JTextField();

                   txt1.setName("text1");
                   txt2.setName("text2");
                   txt3.setName("text3");
                   txt4.setName("text4");

                   txt1.setPreferredSize(new Dimension(50, 20));
                   txt2.setPreferredSize(new Dimension(50, 20));
                   txt3.setPreferredSize(new Dimension(50, 20));
                   txt4.setPreferredSize(new Dimension(50, 20));

                   add(new JLabel("text1"));
                   add(txt1);
                   add(new JLabel("text2"));
                   add(txt2);
                   add(new JLabel("text3"));
                   add(txt3);
                   add(new JLabel("text4"));
                   add(txt4);
               }
           };
           return page1;
       }

>    public WizardPage(String title, String description){
>
>        PropertyConfigurator.configure("config/log4j.properties");
>        log = Logger.getLogger(WizardPage.class);
>
>       _title = title;
>       _description = description;
>
>
>     setLayout(new FlowLayout()); );

      addContainerListener(new WPContainerListener());
      this.setDoubleBuffered(true);
   }

A: The simplest way to have unspecified number of rows in a grid is to use GridLayout with 0 as the row count:
setLayout(new GridLayout(0, 2));

This will result in 2 columns, and rows being added as needed. The downside of GridLayout is that the labels and text fields  will have the same width, which may not be what you want.
Another easy approach is nesting layouts: you could place each label + text field combination to a JPanel, and then continue adding those panels to a vertical BoxLayout as needed. This neither, is flawless, and can result in a layout like:
label | text
-----------------
long label | text

If you need a grid that can make the columns and rows different width, investigate other grid based layouts: GridBagLayout comes with the standard library, and is capable of such grids, but is a bit complicated to use. If you find yourself making a lot of such layouts, consider using a third party layout manager, such as MiGLayout.


text:
Q: Register instance with mef2 in uwp I downloaded the nuget package Microsoft.Composition and tried to register a service with mef2. It seems the whole framework changed. CompositionContainer, AggregateCatalog and the RegistrationBuilder are gone. The CompositionContainer seems to be replaced by the CompositeHost. I tried to register my instance on the CompositeHost but there are only functions for GetExport.
How can I register my instance to the CompositeHost?
Also I couldn't find a documentation how to use mef2 in uwp.


text:
Q: Pandas: methods to transpose DataFrame and Series? I wanted to respond and extend this post in order to stick together all the similar information about transpose. It was said to me that I have to make a separated question.
Swapping Axes in Pandas
If you have a simple DF you have two default axis: 'index' and 'columns'. Then you can use methods or functions like this:
df1 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
df1.T
df1.transpose()
df1.swapaxes(axis1= 'columns',axis2= 'index')
# Edit: adding examples
df1
Out[98]:
   one  two
0  1.0  4.0
1  2.0  3.0
2  3.0  2.0
3  4.0  1.0

df1.T
Out[99]:
       0    1    2    3
one  1.0  2.0  3.0  4.0
two  4.0  3.0  2.0  1.0

df1.one
Out[100]:
0    1.0
1    2.0
2    3.0
3    4.0
Name: one, dtype: float64

df1.one.equals(df1.one.T)
Out[106]: True

But since Series have an 'index' axis but not a 'columns' axis how could be possible to transpose it?.
I hope this time I'm following all the SO recomendation about asking.

A: Here's one way:
s = df1['one'].to_frame().T

OUTPUT:
       0    1    2    3
one  1.0  2.0  3.0  4.0


text:
Q: How to deploy my umbraco site in my own live serve with out umbraco cloud I'm deploying my site to Umbraco Cloud and that's working fine, but I want to deploy to my own live server without Umbraco CLoud services.
I know the process of Umbraco cloud service.
If I change any content on local Umbraco that can effect on server system without Umbraco as a service, is there any alternate process to do that?

A: I have not used Umbraco as a Service but when hosting sites yourselves there is no standard feature to push content changes from one environment to another.
Umbraco offer A closed-source licensed package Courier that is designed to manage the deployment of content:
https://umbraco.com/products-and-support/courier/
Additionally you may wish to investigate uSync.Content. I have used uSync (for document types ect.) with great success but have not used the Content edition: https://our.umbraco.org/projects/developer-tools/usynccontentedition/
The final, more hands on, approach is to do a database compare between environments to generate update scripts that can be applied but this does require a good understanding of the Umbraco schema to avoid overwriting/loosing content.


text:
Q: Why the filter method does not filter out long values? I have problem with method filter. I can't filter out values less than 4,000,000. Do you have any ideas?
public class Euler2 {

    public static void main(String[] args) {
        long sum = calculateSumOfTheEvenValuesOfTheFibonacciSequence();
        System.out.println(sum);
    }

    static long calculateSumOfTheEvenValuesOfTheFibonacciSequence() {
        return Stream.iterate(new Long[]{1L, 2L}, x -> new Long[]{x[1], x[0] + x[1]})
                .flatMap(Arrays::stream)
                .filter(new Predicate<Long>() {
                    @Override
                    public boolean test(Long x) {
                        if (x < 4_000_000) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                })
                .filter(x -> x % 2 == 0)
                .reduce(0L, Long::sum);
    }
}

A: Instead of that filter, you really want a :
.takeWhile(x -> x < 4_000_000)

so that you make it finite. Otherwise, that Long::sum will overflow.
You can replace that reduce that you have with .reduce(0L, Math::addExact); and see that it fails.


text:
Q: Glyph 144 missing from current font I'm on a mac using matplotlib.pyplot
I have been searching for a while to solve the problems.
I have try:
from matplotlib import font_manager as fm, rcParams

plt.rcParams['font.sans-serif']=['SimHei'] #Show Chinese label
plt.rcParams['axes.unicode_minus']=False

BUT, it DOESN'T work.
I find the number after "Glyph" in the solution above is much larger than mine. I suppose the solution can only solve warnings such as: Glyph 39057, Glyph 24352 ...
My warning is:
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 150 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 157 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 132 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 144 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 156 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 151 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 152 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 128 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Python/3.7/lib/python/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 153 missing from current font.
  font.set_text(s, 0, flags=flags)

New to Python and ipynb, Thanks for the help!


text:
Q: Merge ruby hashes adding keys I have two hashes with the same keys
{1=>2, 2=>450, 3=>3}

and
{1=>'1232', 2=>'ffsa', 3=>'vdsvds'}

I want to merge them to this
{
  1=> {:number => 2, :string => '1232'},
  2=>{:number => 450, :string => 'ffsa'},
  3=>{:number => 3, :string => 'vdsvds'}
}

getting values for subkey 'number' from the first hash and values for subkey 'string' from the second hash. What is the best way to achieve this?

A: Here is a way :
h1 = {1=>2, 2=>450, 3=>3}
h2 = {1=>'1232', 2=>'ffsa', 3=>'vdsvds'}

h1.merge(h2) { |_, o, n| { number: o, string: n } }
# => {
#      1=>{:number=>2, :string=>"1232"},
#      2=>{:number=>450, :string=>"ffsa"},
#      3=>{:number=>3, :string=>"vdsvds"}
#     }


text:
Q: Kotlin - coroutines Channels - do they block the calling thread? i know channels is experiemental and we can think of channels as the same as a blocking Queue in java. that being said lets take a look at this simple block of code:
fun main(args: Array<String>) {

    val channel = Channel<Int>()
    GlobalScope.launch {
        for (x in 1..50000) {
            println("from channel $x")
            channel.send(x * x)
        }
    }
    // here we print five received integers:
    runBlocking {repeat(5) { println(channel.receive()) }}
    println("Done!")

}

i'd like to know what happens to the rest of the integers.  look at the output from running this:
 from channel 1
1
from channel 2
from channel 3
4
9
from channel 4
from channel 5
16
from channel 6
25
Done!

why it did not print all 50000 integers ? I have it in a global scope. so this line: println("from channel $x") should have been called 50000 times. why did it not ?

A: send is a suspend function and blocks the coroutine (not thread) if there is no one to receive/dequeue at the other end. This is how back pressure is supported in coroutine world. Your runBlocking repeats only for 5 iterations and your main exits.

A: The default capacity of the channel's internal queue is 1. It's a so-called rendezvous channel because the producer and the consumer coroutine have to meet to exchange the item. Since you consume only five items, the producer is only able to produce five of them and suspend before delivering the sixth one, at which your entire program completes.
So, here's a modification of your program that prints all 50,000 items:
fun main() {
    val channel = Channel<Int>(Channel.UNLIMITED)
    GlobalScope.launch {
        for (x in 1..50000) {
            println("from channel $x")
            channel.send(x * x)
        }
    }
    Thread.sleep(1000)
    println("Done!")
}

Note there was no need to consume any of them this time.


text:
Q: Artisan::call() outside the Laravel framework I want to create a cron job for Laravel 5.2
My shared host (on OVH), only allows me to point to the full path of a file, and I am not able to use the recommended Cron entry from Laravel's docs, ie :
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Therefore, I have to call the Artisan command from a .php file, outside of the Laravel framework.
Here is what my public/cron.php file looks like so far:
<?php

require __DIR__.'/../bootstrap/autoload.php';

use Illuminate\Support\Facades\Artisan;

Artisan::call('refresh');

refresh being my command for regenerating thumbnails inside my app.
When accessing cron.php through my browser (testing on local XAMPP), the following error occurs:
Fatal error: Uncaught RuntimeException: A facade root has not been set. in
C:\xampp\htdocs\site\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:210

Stack trace:
#0 C:\xampp\htdocs\site\public\cron.php(7): Illuminate\Support\Facades\Facade::__callStatic('call', Array)
#1 {main} thrown in C:\xampp\htdocs\site\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 210

I have also tried to boot the app, but it doesn't make any differences
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->boot();

To avoid using the Artisan Facade, I tried calling the underlying Kernel Class directly:
use Illuminate\Contracts\Console\Kernel;

$kernel = new Kernel;
$kernel->call('refresh');

But this returns:
Uncaught Error: Cannot instantiate interface Illuminate\Contracts\Console\Kernel

EDIT: Here is a screenshot of OVH cron interface. The cron task is customized by OVH and only allows to point to the fullpath uri of a file - which file would execute my artisan command-. My question is, what should I put in this file, and should it be a PHP file, or a CMD?

A: Just try simple:
shell_exec('php artisan refresh');

If it doesn't work, try to add appropriate paths to both php and artisan.

A: What you want to do is run a specific Artisan command from within a script.
You can achieve this by copying artisan.php and forcing the input to what you want:
#!/usr/bin/env php
<?php

require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

$status = $kernel->handle(
    $input = new Symfony\Component\Console\Input\ArrayInput(['command' => 'refresh']),
    new Symfony\Component\Console\Output\ConsoleOutput
);

$kernel->terminate($input, $status);

exit($status);

If you compare this script to artisan.php, you'll see that I've just forced the input passed to $kernel->handle() method. It does not read the input from the CLI anymore, it takes these arguments, as an array. See Symfony Console Component documentation for more details.
If you need to pass arguments to your script, just set the input accordingly:
$input = new Symfony\Component\Console\Input\ArrayInput([
    'command' => 'refresh',
    'arg_foo' => 'foo',
    '--option_bar' => 42
]);

$status = $kernel->handle(
    $input,
    new Symfony\Component\Console\Output\ConsoleOutput
);

Now, you can put this script where you want, it does not need to be accessible through web via a browser (it should not, by the way).
If you put it at the root of your hosting at OVH, I mean NOT in www, you just have to fill the form very simply:

If you want your script to be accessible through the web (which is not recommanded for obvious security reasons, but still), place it in your www directory, change the paths to bootstrap/autoload.php and bootstrap/app.php and give your script a name that is not easy to guess.
In the form in the OVH manager, don't forget to add www/ at the beginning of the path of the script.
There is no need to specify php script_name, since the manager handles it for you, when you choose PHP version. Just type the path of the script PHP will execute.

A: If you just want set a cron job. please edit crontab and use "your/app/path/php artisan cron:job" to excute your command directly.


text:
Q: Converting a string to an expression in MATLAB I'm writing a small MATLAB package and I'd like to ask for user input for a function. So if the user enters:
x.^2 + sin(x)

I want to use this user input to appear elsewhere in the code, but x would already be defined and so the expression above would be a vector (or scalar if length(x) is 1).

A: You can use the eval function for this. For example:
>> x = 5

x =

     5

>> eval('x*3')

ans =

    15

A: You can create a function handle:
% some variable you already defined
myVar = 5;

% Create an anonymous function in some z
f = str2func('@(z) z.^2 + sin(z)');

% Call function supplying the input
f(myVar)


text:
Q: How can I make www.mywebapp.com/bin return a 404 in ASP.NET MVC? I'm using ASP.NET MVC to develop a web application, deploying to IIS 7.  I've hidden my Files and Views directories with web.config files in those directories (they just return a normal 404).
However, I haven't been able to get the web.config method to work in hiding my bin directory.  When I access www.mywebapp.com/bin, I instead get a too-revealing page with this message:

HTTP Error 404.8 - Not Found
The
  request filtering module is configured
  to deny a path in the URL that
  contains a hiddenSegment section.

The page reveals part of my directory structure.  I just want it to return my 404 page like the Files and Views directories do.  How can I get this behavior?

A: A better bet would be to handle both 404 and 404.8 errors with the same, more user-friendly, error page that doesn't reveal the precise error code. You would also probably want to handle 403 errors (and probably some others that will be suggested by other SO users) in the same way.
For this, you need to use the <customErrors /> element in the web.config.

A: I was able to solve this problem by adding a small web.config file in my ~/Files directory that rebuffs all attempts at exploration through the web.  The web.config is very similar to what ASP.NET MVC puts in the Views directory by default:
<?xml version="1.0"?>
<configuration>
  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
    </handlers>
  </system.webServer>
</configuration>

A: I have put in my error handling for pathing issues within my global.asax.  I then check to see what the error was, in your case 404, and if it's a 404 I redirect them to /Home/Index.
If it's another error I direct to my error controller and handle the error there.
I hope this helps you.  If you want code let me know.


text:
Q: Clojure: zipper -> html After a few days of trying to wrap my brain around zippers, I think I finally understand how to create them from sequential data.
However, after searching for a few days, I can't seem to find any resources on how convert a zipper into something else. Basically, I want to convert some data into a format that I can pass to Hiccup to generate some HTML.
Are there any good resources on what I should be doing to convert a zipper tree into a different data structure?

A: I think you have it backwards, but that is a good thing. The way to use zippers is to create a zipper that works for your datastructure, not the other way around. Hickory is an excellent example. This is a good example for a zipper that uses maps instead of sequences.


text:
Q: How do I remove the "eye symbol" from password fields in Windows 8? While I was entering my password in Gmail and other mail accounts, I could see a symbol of an "eye" in the text box.
This is really dangerous because once you click on the eye, your password is revealed.
Is there any way I can disable that eye symbol? I'm getting this in Internet Explorer. Has anyone else encountered it?

A: The new 'eye' symbol is present in all the password fields in Internet Explorer 10 which comes default with Windows 8 (and is also available for Windows 7).  To reveal the password, the user needs to keep the 'eye' symbol pressed.
Disabling it (in Windows 8):
Please note that to do the following, you will need to access the Local Group Policy Editor, which is only available in Windows 8 Pro. You can see if you have Windows 8 Pro by pressing Win+Pause, which opens the System Properties window. If under "Windows Edition" you see Windows 8 Pro, you will be able to access the Group Policy Editor.
To disable the "eye" symbol, follow these steps:

*

*Open the Run dialog (Win+R)

*Enter gpedit.msc and press Enter

*Local Group Policy editor will open:

*Navigate to Computer Configuration → Administrative Templates → Windows Components → Credential User Interface:

*Double-click on "Do not display the password reveal button" and select the "Enabled" option:

*The behaviour is disabled, you can enable it with the same method.
Source: (From Wayback machine Web archive) Enable or Disable Password reveal option in Windows 8


text:
Q: array variable index in that rare SimpleXML functions I have a label on a form select and I get that value with $ _POST like this:
$gallery = array($_POST['gallery']);

and that value will put it here:
$image = $sitemap->gallery[$gallery]->addChild('image');

the problem is giving me error is as follows:
Fatal error: Call to a member function addChild() on a non-object in

I do not understand is that if I put a value directly asin me do it like so:
$gallery = 0;
$Image = $sitemap->gallery[$gallery]->addChild('image');

I do well, what happens is that I want the user to choose,
Kind of strange as it may fix.

A: use this:
$gallery = $_POST['gallery'];

instead of this:
$gallery = array($_POST['gallery']);

You passing an array that you did not index properly
Or you can try it this way:
$gallery = array('gallery' => $_POST ['gallery']);

or
$image = $sitemap->gallery[$gallery[0]]->addChild('image');

either way should fix the problem

A: thank you very much, but I tested this and is giving me the same error
  $gallery=array('gallery'=>$_POST['galeria']);
$image = $sitemap->gallery[$gallery]->addChild('image');

I do not understand the select form that I have is as follows:
<select id="textfield" name="galeria">
        <option id="textfield" value="">Escoger de la Lista</option>
        <?php
    $source = 'content.xml';
    // load as string
    $xmlstr = file_get_contents($source);
    $sitemap = new SimpleXMLElement($xmlstr);
    // load as file
    $sitemap = new SimpleXMLElement($source,null,true);
    //$bar_count = $sitemap->gallery->count();
    //for($i=0;$i<$bar_count;$i++){
    $contador="0";
    foreach($sitemap->gallery as $content) {
    $atributo = $content->attributes();
    echo "<option id='textfield' value='".$contador."'>".$atributo['Name']. "</option>";
    //}
    $contador++;
    }
    ?>
      </select>

anyway I've tried has done an echo and I get the result, do not really understand

A: Understanding Arrays:
$gallery = array($_POST['gallery']);
echo "Gallery Array:
".print_r($gallery,true)."

";

Output:
Array
(
    [0] => 'value in array'
)

How to get the value out of an array:
echo "Get Array Value: ".$gallery[0]."
"; // You should be displaying the array index 0

Adding a custom index
$gallery = array('gallery' => $_POST['gallery']);
echo "Gallery Array:
".print_r($gallery,true)."

";

Output:
Array
(
    [gallery] => 'value in array'
)

Getting the value from the customer index array
echo "Get Array Value: ".$gallery['gallery']."
"; // You should be displaying the array index gallery


text:
Q: xml to relational data for the lazy I am sitting with lots of data in multiple xml files, which I would like to convert to relational data, for better being able to analyze it. Are there any tools that can transform the data / import to a database with a minimum of work?
In this specific case, the data will map very nicely to relational data, It is not completely flat, but the structure have a simple parent-child nesting. However there are no IDs, so keys and foreign keys will need to be generated.
I have been looking at Xpath queries, SQLXML Bulk load, SSIS and so on, and they seem to be too much work. Yes I know, I am being lazy, but knowing that the xml schema may change from time to time, I don't want to put too much work in it, I just want an easy way to summarize the data, without having to tinker with building a database schema manually, and then scripting queries to populate the DB.
Any tips or tools?


text:
Q: Scrapy Pagination FormRequest I am trying to scrape all of the comments from this page:
https://steamcommunity.com/sharedfiles/filedetails/comments/2479197624
There are two pages of comments, and I'm able to scrape the first page, but do not know how to make the scrapy Spider go to the second page to scrape those comments as well. This is my current code:
contributor_id = "".join(filter(str.isdigit, response.css('a.commentthread_author_link::attr(href)').get()))
        workshop_id_number = response.css('form.smallForm > input::attr(value)').get()

        if int(response.css('span.tabCount::text').getall()[1]) > 50:

            url = f'https://steamcommunity.com/comment/PublishedFile_Public/render/{contributor_id}/{workshop_id_number}/'

            headers = {
                'Accept':   'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding':  'gzip, deflate, br',
                'Accept-Language':  'en-US,en;q=0.5',
                'Connection':   'keep-alive',
                'Host': 'steamcommunity.com',
                'Upgrade-Insecure-Requests':    '1',
                'User-Agent':   'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0'
            }

            data = {
                "start": "1",
                "totalcount": "133",
                "count": "133",
                "sessionid": "d880ab2338b70926db0a9591",
                "extended_data": "{\"contributors\":[\"76561198401810552\",{}],\"appid\":289070,\"sharedfile\":{\"m_parentsDetails\":null,\"m_parentBundlesDetails\":null,\"m_bundledChildren\":[],\"m_ownedBundledItems\":[]},\"parent_item_reported\":false}",
                "feature2": "-1"
            }

            yield FormRequest(url, formdata=data, callback=self.parse_paginated_comments, dont_filter=True,)

How do I get the scraper to get to the next page?


text:
Q: Azure Active Directory Authentication Process with Xamarin.iOS I have my application registered with Azure AD and have got the required details to perform application authentication with Azure AD.
But when i run
new AuthenticationContext(UserContext.AzureCommonAuthority);

this line it throws an exception-
"The type initializer for 'Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache' threw an exception." with error code "cannot_access_publisher_keychain".

Working with Xamarin.iOS project.
Thanks in advance!

A: I have the same problem , im working on it if i found the solution ill post it.
EDIT : I was testing on the iphone simulator , i dont get any error on a real device :/


text:
Q: Not able to play sound on iphone using JavaScript but able to play on Android I am trying to play a sound notification on android and iPhone using JavaScript library but I am only able to play the sound on android and not on iPhone.
I am using JavaScript ion.sound.play("beep") this function to play the sound. I have kept the sound file in my folder. Can any one help me out; how can I play sound on iPhone using JavaScript?

A: The sounds require user input in iOS9. You can initialize the sound with an "invisible" button that disappears after one press at the initialization of your app. Once triggered, you should be able to call ion.sound.play("beep") programatically. I will help You.
CSS:

JAVASCRIPT:
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {

    document.write('');

    function sndInit(){
    ion.sound.play("beep");
    ion.sound.pause("beep");
    document.getElementById('init').style.display = 'none';
    }
}


text:
Q: IP Address Info on Azure devops commits is there a way to get the ip address from where the commits are done?I verified  get commit stats api call but does not have ip address info.

A:
IP Address Info on Azure devops commits

For this issue , I think it is impossible to get the IP address from where commits are done .
From the response body of Commits - Get rest api we can know that it does not contain IP address information. In addition,it is not safe to include IP address in the commit information. The main risk of using a public IP address: It allows anyone, anywhere to connect to your device directly from the Internet — and that includes cybercriminals. What's more, attackers can change your Internet access settings, for example, forcing the router to feed you phishing websites where they can pinch your login credentials. For more dangers about public IP address,you can refer to this blog. Therefore, it is also not recommended to include the IP address of the machine where commits are done in the commit info.