text:
Q: How to unit-test a class which needs a specific file to be present I'm currently trying to learn proper unit-test. So now I'm trying to write unit-tests for a class that should map data from an XML-File to the proper objects. Of course all functionality of the class is dependent on the existence of the corresponding XML-file. The XML-file is loaded in the constructor of the class.
I'm using C# with NUnit. So far I've got two tests:
[Test]
public void ShouldAllowInstanceToBeCreatedWhenXMLFileIsPresent()
{
    if (File.Exists(SettingsReader.XML_SETTINGS_PATH))
    {
        SettingsReader settingsReader = new SettingsReader();
        Assert.AreNotEqual(null, settingsReader);
    }
}

[Test]
[ExpectedException("Telekanzlei.Clientmanager.XMLDataLayer.XMLFileNotFoundException")]
public void ShouldThrowExceptionWhenXMLFileIsNotPresent()
{
    if (!File.Exists(SettingsReader.XML_SETTINGS_PATH))
    {
        SettingsReader settingsReader = new SettingsReader();
    }
        else
            throw new XMLFileNotFoundException();
    }

I'm not sure if checking the existence of the file in the test is a proper way to go, so any suggestions on those test are welcome too. But my question is, how to proceed with the following tests. Obviously all following tests are going to fail, if the XML-file is not present.
So do I assume that the XML-file is present, while keeping in mind, that a failing test could just mean that it's not? That wouldn't seem right to me.
Is there a general pattern, to handle a problem like this?
Thx for any help
edit: rewrote the second test, as it was failing if the file was actually present...
edit2: May it is helping to tell you, what the SettingsReader actually does. So far it looks like this:
public class SettingsReader
{
    public static readonly string XML_SETTINGS_PATH = "C:\\Telekanzlei\\Clientmanager_2.0\\Settings.xml";

    public XElement RootXElement { get; private set; }

    public SettingsReader()
    {
        if (!File.Exists(XML_SETTINGS_PATH))
            throw new XMLFileNotFoundException();
        using (var fs = File.OpenRead(XML_SETTINGS_PATH))
        {
            RootXElement = XElement.Load(fs);
        }
    }

}

I'm not sure, but I guess a StreamReader wouldn't be the way to go here, would it?

A: If you must I suggest you use SetUp method to copy or verify that the file exist.
I suggest making sure the file is present by adding it to the test project and marking it as "copy always" once you get that working there is no need to re-check it.
If you have a lot of tests that require external files perhaps you should use MsTest - it has an attribute called DeploymentItem that makes sure that the file is copied to the same location as the test.

A: Consider rewriting code so dependencies can be passed in or somehow else stubbed for the code you want to unit-test.
I.e. pass something like "IMySettingsFileProvider" instance to SettingsReader constructor where IMySettingsFileProvider.SettingsXml returns some setting stream. This way you can mock IMySettingsFileProvider interface for the test instead of requiring file to be present on disk.

A: The problem is not with your unit tests but with the design of the class. I'd suggest refactoring the class so it doesn't open the file but instead operates on a stream. Then your unit tests could simply replace a file stream for a memory stream - simples! :)
public class SettingsReader()
{
    public SettingsReader(System.IO.StreamReader reader)
    {
        // read contents of stream...
    }
}

// In production code:
new SettingsReader(new StreamReader(File.Open("settings.xml")));

// In unit test:
new SettingsReader(new StringReader("<settings>dummy settings</settings>"));

Remember, opening a file and parsing settings data are two very different concerns.

A: One option is to put this at the top of the test fixture.  Then the tests will only be valid when the file exists.
[SetUp]
public void Setup()
{
    Assume.That(File.Exists(SettingsReader.XML_SETTINGS_PATH));
}


text:
Q: Prevent Excel from changing x-axis on a dynamic chart I wanted to make a dynamic chart that plots out the graph of a standard curve for a bio assay we perform frequently. Often to boost the fit of the curve you may drop one or two data points on either end of the data set. So using vlookups and if statements I have a scheme that performs that data trimming, such that my data always starts in Row 1 and the column length simply shortens.
My table works great, but my xy scatter chart goes bananas on these changes. I have the plot on a log log scale, which looks fine if the full data set is present. I lose the x axis detail when I perform a trim. The x- axis then resets to range of 1 to length of my data set.
How can I prevent this?
UPDATE
I added some information. I know there are VBA ways to do this but I would prefer to keep the spreadsheet as simple as possible. I would think excel should be able to handle this.

So if I have a bad fit I may want to trim the data series either from the beginning or end of the data set. I accomplish that with the spinner buttons to dynamically change the table but the following happens

My formula that updates the columns looks like the following. Its messy.
=IF(ISNA(IF(VLOOKUP(F6,$C$4:$D$11,2,FALSE)+1>8-($B$5-1),"",INDEX(C$4:C$11,VLOOKUP(F6,$C$4:$D$11,2,FALSE)+1))),"",IF(VLOOKUP(F6,$C$4:$D$11,2,FALSE)+1>8-($B$5-1),"",INDEX(C$4:C$11,VLOOKUP(F6,$C$4:$D$11,2,FALSE)+1)))

A: In the formulas use NA() instead of "". Filling cell with "" does not result in a true empty cell and is the reason why you are experiencing issues with your chart.
Hope that helps.

A: I may be missing the obvious here, but just hard-code the graph with a range of your choosing. In the sample screenshot, making the graph auto defaults the max range to 100,000. I went in and hard-coded the maximum to 50,000 (circled). Afterwards, the 5th data point is not displayed in the chart. Doesn't matter what the data shows at this point.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I highlight the search terms with DB2 Text Search in 9.5.2? I have a working search query with the new Text Search functions in DB2 9.5.2:
select *
from prevue.mysearchabletable mst
where contains(mst.searchabletext, 'porsche') = 1;

However, this only tells me which ones match, as well as what the score is (score function has been omitted for brevity).  Is there a way to use the text search in 9.5.2 to highlight search terms?
I know there were functions for this in the old Net Search Extender, but I haven't found equivalents (or a workaround) in the new text search system yet.


text:
Q: BlockUI in a Table - Not Working I am "trying" to use BlockUI in a table to have one row blocked out when a user already selected something.  I am able to block out all other elements on the page except anything in the table or the table itself.  Has anyone else run into this issue or have any suggestions on how to solve?

A: According to this forum post:

Blocking table cells may work in some browsers but in won't work
  reliably in an x-browser environment.  The blocked element needs to be
  an element that can have a relative position, and that is not true of
  TRs and TDs.  Further, the "block" overlay (a div) is appended to the
  blocked element, and appending a div to a table is not valid.  If you
  need to block a table, wrap it in a div and block that div instead.
  If you need to block a table cell, wrap the cell contents in a div and
  block that div instead.  If you need to block a row, block each TD's
  content div.

Basically, you could embed your td's content inside another div, which can be blocked and then call block() on all of those divs instead:
HTML:

Row 1 Col 1

Row 1 Col 2

Row 2 Col 1	Row 2 Col 2

Row 3 Col 1	Row 3 Col 2

JavaScript:
$("tr:eq(0) td > div.row").block({
    message: null
});

I've applied a class row to each td's content so that I can call block() on those elements instead.  The selector selects the first trs tds divs with class "row."
Here's a working example: http://jsfiddle.net/yWwR5/ (The large amount of code up front is just the BlockUI plugin).
You could follow this strategy (as outlined in the forum post) for any element that's part of the table.
Edit: If you can't edit the HTML for some reason, you could wrap the contents of each td in the div with JavaScript:
$("tr td").contents().wrap("
");

A: This is kind-of an extension of @Andrew Whitaker. I wanted to block a TBODY and show a message so did something like this...
$("tbody").find("td:first").block();
$("tbody").find("td:not(:first)").block({message: null});

http://jsfiddle.net/g49xofgh/3/
Bonus: I was actually doing this for a Knockout project, so I made a custom binding that could also handle table, tbody, and tr...
http://jsfiddle.net/o4945uxv/


text:
Q: asp.net --> forgot password functionality  I am doing "forgotpassword functionality" in asp.net
My forgotpassword.aspx page consists of a username, security question, security answer, new password,retype password and a submit button.
When I click on the "forgotpassword" link at the previous page, it should prompt me about the security question and when I enter the answer at the security answer textbox, the control should take those two (security quesion and security answer) to the backend (database) and validate that the security answer is correct.  It should reply with a boolean value. Then the next 'new password' and 'retype password' should get activated.
By means the operation of going back to database should occur when the control comes out of the security answer textbox. In windows forms  we can use the 'leave' event (ex:textbox1_leave) but in web forms we don't have that.
If the solution is to use javascript, please give me the step by step process to handle the aspx (source page) and also the .cs file coding

A: you could use microsofts membershipprovider interfaces. you just have to implement it for your own requirements (database structure).
just have a look at http://www.asp.net/learn/security-videos/ there you can watch a lot of helpful videos for understanding and implementing membership and role providers.
it helped me also to implement my first membershipprovider.
this link might be also usefull http://weblogs.asp.net/scottgu/archive/2006/05/07/ASP.NET-2.0-Membership-and-Roles-Tutorial-Series.aspx
as soon as you have finished, you can use all microsoft login controls.
good luck

A: There is a forgot password component in ASP.NET 2.0 - just use that and configure it.

A: http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider.resetpassword.aspx
http://www.asp.net/web-forms/tutorials/security/admin/recovering-and-changing-passwords-cs


text:
Q: Center image on splash screen while taking into account system bars On my Android app (react-native but it doesn't matter) I have a splash screen. I created res/drawable and added a image called "emblem.png". I then center that with gravity of center as seen in my xml here:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item name="android:windowBackground">@drawable/background</item>

    <item>
        <bitmap android:gravity="center" android:src="@drawable/emblem"/>
    </item>

</layer-list>

However this centering does not take into consideration the "top status bar" height nor the "width of 'system nav bar' when landscape"/"height of 'system nav bar' when in portrait". Is there a way to do this?
Thanks

A: THIS IS NOT AN ANSWER, I'M JUST SHARING SOME CODELayout file - activity_splash.xml
<?xml version="1.0+ encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
xmlns:tools="http://schemas.android.com/tools"
android:id=@+id/activity_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
tools:context="com.splash.splash.Splash">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/iV"
android:gravity="center"
android:src="@drawable/applogo"/>
<TextView
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:text="My welcome screen"
android:textsize="25sp"
android:textStyle="bold"
android:textcolor="@color/white"
android:layout_marginTop="10dp"
android:id="@+id/tV"  />
</LinearLayout>
</RelativeLayout>

MainActivity.java
public class Splash extends AppCompatActivity{
private TextView tv;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState){
super.OnCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
tv= findViewById(R.id.tV);
iv= findViewById(R.id.iV);
final intent i = new intent(this,MainActivity.class);
Thread timer = new thread(){
  public void run(){
try{
  sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
finally{
startActivity(i);
finish();
}
}
};
timer.start();
}
}

This is how I set a splash screen in android. Hope this helps you.


text:
Q: Can adhoc interface connect to AP mode interface? In IEEE 802.11, is it possible for an adhoc mode interface to connect to an interface in AP (infrastructure) mode?

A: Simple answer = no
Ad hoc mode:
An Ad-hoc network allows each device to communicate directly with each other. There is no central Access Point controlling device communication. Ad-hoc networks are only able to communicate with other Ad-hoc devices, they are not able to communicate with any Infrastructure devices or any other devices connected to a wired network.
Infrastructure mode:
An Infrastructure mode network requires the use of an Access Point. The Access Point controls Wireless communication and offers several important advantages over an Ad-hoc network. For example, a Infrastructure based network supports increased levels of security, synchronized communication through beacon intervals, potentially faster data transmission speeds and integration with a wired network.


text:
Q: Fail to declare variable in mysql This is the error I got when I try to run the query shown below:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE productCount INT DEFAULT 0' at line 1

I am using Mysql workbench on ubuntu

*

*MySQL Workbench Community (GPL) for Linux/Unix version 6.3.8 CE build 1228 (64 bit)

*Cairo Version: 1.15.10

*OS: Linux 5.3.0-47-generic

*CPU: 4x Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz (500.028MHz) - 15.53GiB RAM

*Distribution: Ubuntu 18.04.4 LTS

*Fips mode enabled: no

A: DECLARE only can be used in triggers,functions and stored procedures betewenn BEGIN and END see mysql maual
If you want to  use a variable declare a user defined variable like @msg
use testdb;
SET @msg := 'testme if you can';
SET @testcount := 0;

SELECT @msg,@testcount + 1;

Result:
# @msg, @testcount + 1
testme if you can, 1

A: You can declare variables only inside routines.

A: You can use DECLARE only in stored procedures. Here is a simple example of passing two variables to a stored procedure and declaring one variable inside the stored procedure
CREATE DEFINER=`myslq_user`@`%` PROCEDURE `createRecord`(IN _name NVARCHAR(255), IN _userID int)
BEGIN
    DECLARE val INT DEFAULT 0;
        INSERT INTO tbldata (Name, UserID, Value) VALUES (_name, _userID, val);
    END IF;
END


text:
Q: How to render smarty inside vue? how Can I render smarty inside vue? I wanted to create vue instance on everything in my app and connect it with smarty. I want to use vue for frontend data and smarty for backend data. When I generate code like in example it appears and when vue render disappear

{$smartyVariable}

A: Maybe to late but... You can use the {LITERAL} in your *.tpl
Something like this:

{literal}  {{ message  }} {/literal}

{literal}

{/literal}


text:
Q: iOS PHP like array, for storing multiple values systematically I have some NSDates that are incremented and looped.
In the loop I need to check if the current date isEqualToDate in my array.
Each date key then needs to have multiple string values associated with it, something like this in PHP
$array['date'][0]['string']
$array['date'][1]['string']
etc

I have read a little, and I understand that Objective-C does not support these kinds of arrays, what would be the best way to do this?

A: Mutable Dictionary to hold everything
NSMutableDictionary *myDates = [[NSMutableDictionary alloc] init];

Adding values to your dictionary
[myDates setObject:myArrayOfStrings forKey:myDate];

Comparing dates without comparing the time (hours/minutes/seconds).
Credit where credit is due: iOS: Compare two NSDate-s without time portion
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDateComponents *date1Components = [calendar components:comps
                                            fromDate: date1];
NSDateComponents *date2Components = [calendar components:comps
                                            fromDate: date2];

date1 = [calendar dateFromComponents:date1Components];
date2 = [calendar dateFromComponents:date2Components];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
    //the same
}

A: In Objective-C this is like an NSArray into  NSDictionary with date key.
example:-
NSDictionary *dict = @{@"date":@[@"date-1", @"date-2"]};

Output is:
date = (
    "date-1",
    "date-2"
);

And you can fetch those dates like:
NSString *dateString = [[dict objectForKey:@"date"] objectAtIndex:0];

OR
// This is new syntax of dictionary and array
NSString *dateString = dict[@"date"][0];

It will give you date of 0 index.
This is about array type, Now See How to check date is present in array or not. If your date is NSString type then you can check simply
if ([[dic objectForKey:@"date"] containsObject:@"date-1"])
{
    // date-1 is present in array
}

If date is NSDate then
NSArray *dates = [dic objectForKey:@"date"];
for (id obj in dates)
{
    NSComparisonResult result = [currentDate compare:obj];
    if (result == NSOrderedSame)
    {
        // NSDate is present;
        break;
    }
}


text:
Q: Use sendfile() to copy file with threads or other efficient copy file method I'm trying to use the Linux system call sendfile() to copy a file using threads.
I'm interested in optimizing these parts of the code:
fseek(fin, size * (number) / MAX_THREADS, SEEK_SET);
fseek(fout, size * (number) / MAX_THREADS, SEEK_SET);
/* ... */
fwrite(buff, 1, len, fout);

Code:
void* FileOperate::FileCpThread::threadCp(void *param)
{
    Info *ft = (Info *)param;
    FILE *fin = fopen(ft->fromfile, "r+");
    FILE *fout = fopen(ft->tofile, "w+");

    int size = getFileSize(ft->fromfile);

    int number =  ft->num;
    fseek(fin, size * (number) / MAX_THREADS, SEEK_SET);
    fseek(fout, size * (number) / MAX_THREADS, SEEK_SET);

    char buff[1024] = {'\0'};
    int len = 0;
    int total = 0;

    while((len = fread(buff, 1, sizeof(buff), fin)) > 0)
    {
        fwrite(buff, 1, len, fout);
        total += len;

        if(total > size/MAX_THREADS)
        {
            break;
        }
    }

    fclose(fin);
    fclose(fout);
}

A: File copying is not CPU bound; if it were you're likely to find that the limitation is at the kernel level and nothing you can do at the user leve would parallelize it.
Such "improvements" done on mechanical drives will in fact degrade the throughput. You're wasting time seeking along the file instead of reading and writing it.
If the file is long and you don't expect to need the read or written data anytime soon, it might be tempting to use the O_DIRECT flag on open. That's a bad idea, since the O_DIRECT API is essentially broken by design.
Instead, you should use posix_fadvise on both source and destination files, with POSIX_FADV_SEQUENTIAL and POSIX_FADV_NOREUSE flags. After the write (or sendfile) call is finished, you need to advise that the data is not needed anymore - pass POSIX_FADV_DONTNEED. That way the page cache will only be used to the extent needed to keep the data flowing, and the pages will be recycled as soon as the data has been consumed (written to disk).
The sendfile will not push file data over to the user space, so it further relaxes some of the pressure from memory and processor cache. That's about the only other sensible improvement you can make for copying of files that's not device-specific.
Choosing a sensible chunk size is also desirable. Given that modern drives push over a 100Mbytes/s, you might want to push a megabyte at a time, and always a multiple of the 4096 byte page size - thus (4096*256) is a decent starting chunk size to handle in a single sendfile or read/write calls.
Read parallelization, as you propose it, only makes sense on RAID 0 volumes, and only when both the input and output files straddle the physical disks. You can then have one thread per the lesser of the number of source and destination volume physical disks straddled by the file. That's only necessary if you're not using asynchronous file I/O. With async I/O you wouldn't need more than one thread anyway, especially not if the chunk sizes are large (megabyte+) and the single-thread latency penalty is negligible.
There's no sense for parallelization of a single file copy on SSDs, unless you were on some very odd system indeed.


text:
Q: Django InconsistentMigrationHistory with fresh restore
*

*I am having trouble with migrations from this new dump that I received from my test server.

*This is the error that I am getting in the terminal after I execute the command python manage.py migrate.

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration rmas.0001_initial is applied before its dependency equipment.0002_auto_20210629_1540 on database 'default'.

I have been looking through some of the other related questions in StackOverflow and I have done about every suggestion including:

*

*drop the database

*delete django_migrations

*comment out admin in urls.py

*make sure that AUTH_USER_MODEL is in the .py files for dependency issues

migrations.swappable_dependency(settings.AUTH_USER_MODEL)

This is after running the command python manage.py showmigrations and you can see that it is just this one file that is causing a whole lot of issues.
equipment
 [X] 0001_initial
 [ ] 0002_auto_20210629_1540
guardian
 [X] 0001_initial
inspections
 [X] 0001_initial
 [ ] 0002_auto_20210629_1540
notifications
 [X] 0001_initial
pendingsrns
 [X] 0001_initial
 [X] 0002_pendingsrn_verified_srn
product_support
 (no migrations)
repairs
 [X] 0001_initial
 [ ] 0002_auto_20210629_1540
reversion
 [X] 0001_initial
rmas
 [X] 0001_initial

For context if you need it:

*

*Django version = 1.11.24

*Python version = 2.7

*PostgreSQL 12

Please let me know if you need any additional information in order to make sense of this.
Thank you.


text:
Q: Can I send a zip file that is imported using input type and get the same zip in python? I wanted to get the zip file in Python. I tried the following.
    receive :function (event) {
        var zipFile = new JSZip()
            var file = event.target.files[0];
            zipFile.loadAsync(file).then(function(content) {
                return content.files["test.pdf"].async('text');
            }).then(function (txt) {
                 var user = session.uid;
                rpc.query({
                    model: 'account.invoice',
                    method: 'create',
                    args: [user,txt],
                    }).then(function (e) {
                        location.reload();
                    });
            });

    },

this is work on the change event on change of the input file. Here I am able to get the text inside the XML and can send it to python. But What if I have multiple files in the zip. If I am able to send the zip directly and can use the zip operation in python that would be perfect.
Thanks,
Lot of help is appreciated


text:
Q: How to load fish configuration from a remote repository? I have a zillion machines in different places (home network, cloud, ...) and I use fish on each of them. The problem is that I have to synchronize their configuration every time I change something in there.
Is there a way to load the configuration from a remote repository? (= a place where it would be stored, not necessarily git but ideally I would manage them in GitHub). In such a case I would just have a one liner everywhere.

*

*I do not care too much about startup time, loading the config each time would be acceptable

*I cannot push the configuration to the machines (via Ansible for instance) - not of them are reachable from everywhere directly - but all of them can reach Internet

A: There are two parts to your question. Part one is not specific to fish. For systems I use on a regular basis I use Dropbox. I put my ~/.config/fish directory in a Dropbox directory and symlink to it. For machines I use infrequently, such as VMs I use for investigating problems unique to a distro, I use rsync to copy from my main desktop machine. For example,
rsync --verbose --archive --delete -L --exclude 'fishd.*' krader@macpro:.config .

Note the exclusion of the fishd.* pattern. That's part two of your question and is unique to fish. Files in your ~/.config/fish directory named with that pattern are the universal variable storage and are currently unique for each machine. We want to change that -- see https://github.com/fish-shell/fish-shell/issues/1912. The problem is that file contains the color theme variables. So to copy your color theme requires exporting those vars on one machine:
set -U | grep fish_color_

Then doing set -U on the new machine for each line of output from the preceding command. Obviously if you have other universal variables you want synced you should just do set -U and import all of them.

A: Disclaimer: I wouldn't choose this solution myself. Using a cloud storage client as Kurtis Rader suggested or a periodic cron job to pull changes from a git repository (+ symlinks) seems a lot easier and fail-proof.

On those systems where you can't or don't want to sync with your cloud storage, you can download the configuration file specifically, using curl for example. Some precious I/O time can be saved by utilizing HTTP cache control mechanisms. With or without cache control, you will still need to create a connection to a remote server each time (or each X times or each Y time passed) and that wastes quite some time already.
Following is a suggestion for such a fish script, to get you started:
#!/usr/bin/fish

set -l TMP_CONFIG /tmp/shared_config.fish

curl -s -o $TMP_CONFIG -D $TMP_CONFIG.headers \
 -H "If-None-Match: \"$SHARED_CONFIG_ETAG\"" \
 https://raw.githubusercontent.com/woj/dotfiles/master/fish/config.fish

if test -s $TMP_CONFIG
  mv $TMP_CONFIG ~/.config/fish/conf.d/shared_config.fish
  set -U SHARED_CONFIG_ETAG (sed -En 's/ETag: "(\w+)"/\1/p' $TMP_CONFIG.headers)
end

Notes:

*

*Warning: Not tested nearly enough

*Assumes fish v2.3 or higher.

*sed behavior varies from platform to platform.

*Replace woj/dotfiles/master/fish/config.fish with the repository, branch and path that apply to your case.

You can run this from a cron job, but if you insist to update the configuration file on every init, change the script to place the configuration in a path that's not already automatically loaded by fish, e.g.:
mv $TMP_CONFIG ~/.config/fish/shared_config.fish
 and in your config.fish run this whole script file, followed by a
source ~/.config/fish/shared_config.fish


text:
Q: IF condition is always false in this case I am trying to reduce opacity with JavaScript. But the problem is that 'if' condition is always false therefor the opacity is getting 0. Please can anyone explain why this is happening and the correct solution.
var opacity = 1;
var decrement = 0.01;
var id = setInterval(frame, 10);
function frame(){
    if (opacity == 0.4) //It is always false..
    {
        clearInterval(id);//Not able to clear Interval
    }
    else
    {
        opacity = opacity-decrement;
        document.getElementsByClassName('menu_bar')[0].style.backgroundColor='rgba(66,64,61,'+opacity+')';
    }
}

A:  if(Math.abs(opacity - 0.4) < 0.01) {

Floating point math is "broken", therefore you have to be fault tolerant.

A: Instead of using opacity == 0.4 in your code, try using opacity < 0.5 or opacity <= 0.4 as fractions are not very reliable in javascript.
Try running 1-0.1-0.1-0.1-0.1-0.1-0.1 (The math that happens before your == 0.4 check should return true) in your console to see what I mean.

A: As mentioned, the floating point math is broke.
A simple fix is to use integers and divide the end result with 100.
That will also avoid any extra Math.abs, or calc, at every interval.
Stack snippet

var opacity = 100;
var decrement = 1;
var id = setInterval(frame, 10);

function frame() {
  if (opacity == 40)
  {
    clearInterval(id);
  } else {
    opacity = opacity - decrement;
    //document.getElementsByClassName('menu_bar')[0].style.backgroundColor='rgba(66,64,61,'+opacity/100+')';
    document.body.style.backgroundColor='rgba(66,64,61,'+opacity/100+')';
  }
}

A: You can use opacity.toFixed(2) to restrict the decimal digits to 2, this will sole the issue

var opacity = 1;
var decrement = 0.01;
var id = setInterval(frame, 10);
function frame(){
    if (opacity.toFixed(2) == 0.40) //It is always false..
    {
        console.log("Cleared");
        clearInterval(id);//Not able to clear Interval
    }
    else
    {
        opacity = opacity-decrement;
       // document.getElementsByClassName('menu_bar')[0].style.backgroundColor='rgba(66,64,61,'+opacity+')';
    }
}


text:
Q: How does the javascript preloading work? I don't want to know a way to preload images, I found much on the net, but I want to know how it works.
How is javascript able to preload images?
I mean, I tried a snippet from here, and even if it works, it doesn't seem to preload images.
When I check firebug, I can see that the image is loaded twice, once while the preloading, another time when displaying it!
To improve this code I'd like to know how it works.
Here is what i do:
 function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){
            $('')[0].src = this;
            //(new Image()).src = this;
            alert(this +'  &&   ' + i++);

        });
    }

then i do something like that:
preloader = function() {
    preload(myImages);
}

$(document).ready(preloader);

Here is how i display/add the image :
$("li.works").click(function() {
             $("#viewer").children().empty();
             $('#viewer').children().append('')
             $("#viewer").children().fadeIn();

A: Javascript preloading works by taking advantage of the caching mechanism used by browsers.
The basic idea is that once a resource is downloaded, it is stored for a period of time locally on the client machine so that the browser doesn't have to retrieve the resource again from across the net, the next time it is required for display/use by the browser.
Your code is probably working just fine and you're just misinterpeting what Fire Bug is displaying.
To test this theory just hit www.google.com with a clean cache. I.e. clear your download history first.
The first time through everything will likely have a status of 200 OK. Meaning your browser requested the resource and the server sent it. If you look at the bottom on the Fire Bug window it will says how big the page was say 195Kb and how much of that was pulled from cache. In this case 0Kb.
Then reload the same page without clearing your cache, and you will still see the same number of requests in FireBug.
The reason for this is simple enough. The page hasn't changed and still needs all the same resources it needed before.
What is different is that for the majority of these requests the server returned a 304 Not Modified Status, so the browser checked it's cache to see if it already had the resource stored locally, which in this case it did from the previous page load. So the browser just pulled the resource from the local cache.
If you look at the bottom of the Fire Bug window you will see that page size is still the same (195Kb) but that the majority of it, in my case 188Kb, was pulled locally from cache.
So the cache did work and the second time i hit Google I saved 188Kb of download.
I'm sure you will find the same thing with preloading your images. The request is still made but if the server returns a status of 304 then you will see that the image is in fact just pulled from local cache and not the net.
So with caching, the advantage is NOT that you kill off all future resource requests, i.e. a Uri lookup is still made to the net but rather that if possible the browser will pull from the local cache to satisify the need for the content, rather than run around the net looking for it.

A: You may be confused by the concept of "preloading". If you have a bunch of images in your HTML with , they cannot be preloaded with Javascript, they just load with the page.
Preloading images with Javascript is about loading images not already in the document source, then displaying them later. They are loaded after the page has rendered for the first time. They are preloaded in order to eliminate/minimize loading time when it comes to making them appear, for example when changing an image on mouse rollover.
For most applications, it is usually better practice to use "CSS sprites" as a form of preloading, in lieu of Javascript. SO should have a ton of questions on this.

A: Your basic Javascript preloader does this:
var image = new Image();
image.src = '/path/to/the/image.jpg';

The way it works is simply by creating a new Image object and setting the src of it, the browser is going to go grab the image. We're not adding this particular image to the browser, but when the time comes to show the image in the page via whatever method we have setup, the browser will already have it in its cache and will not go fetch it again. I can't really tell you why whatever you have isn't working this way without looking at the code, though.
One interesting gotcha that is discussed in this question is what happens when you have an array of images and try preloading them all by using the same Image object:
var images = ['image1.jpg','image2.jpg'];
var image = new Image();
for(var x = 0; x < images.length; x++) {
    image.src = images[x];
}

This will only preload the last image as the rest will not have time to preload before the loop comes around again to change the source of the object. View an example of this. You should be able to instantly see the second image once you click on the button, but the first one will have to load as it didn't get a chance to preload when you try to view it.
As such, the proper way to do many at once would be:
var images = ['image1.jpg','image2.jpg'];
for(var x = 0; x < images.length; x++) {
    var image = new Image();
    image.src = images[x];
}

A: It just involves making a new DOM image object and setting the src attribute. Nothing clever and AFAIK, it has always worked for me.
Is it possible the second "load" firebug is showing you is it loading it from cache?

A:
The index on the loop is only looking
  at the first image. Change it to use
  the index:
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(i){   // Note the argument
        $('')[i].src = this;    // Note the i
        //(new Image()).src = this;
        alert(this +'  &&   ' + i++);

    });
}

Edit: In retrospect, this was wrong and I can see you're trying to create image elements. I don't understand why the index is there at all, there need not be an index. I think the function should look like this:
function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {
        $('').attr('src', this);
    });
}

And to instantiate it, why not just do this:
$(function () {    // Equivalent to $(document).ready()
    preload(myImages);
});

JavaScript image preloading works because when a DOM element that contains an image is created, the image is downloaded and cached. Even if another request is made when the image is actually rendered from the HTML, the server will send back a 304 (not changed), and the browser will simply load the image from its cache.
Paolo suggests using the following notation to create an image object:
var image = new Image();

While this will work, the DOM-compliant way of doing this is:
var image = document.createElement('img');
image.setAttribute('src', 'path/to/image.jpg');

Which is the way it is being done in the script, except it's using jQuery's HTML string literal syntax to do it. Additionally, most modern browsers offer compatibility with the Image() constructor by simply calling DOM-standard methods. For example, if you open up the Google Chrome JavaScript console and type Image, this is what you'll get:
function Image() {
    return document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
}

Chrome merely uses the native DOM methods to create an image element.


text:
Q: PyQt5 Terminate the app without hitting any button or clicking on anything import sys
from PyQt5.QtWidgets import (QMainWindow, QLabel, QGridLayout, qApp,
                             QApplication, QWidget, QPushButton)
from PyQt5.QtCore import QSize, Qt

class HelloWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Hello world")

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        title = QLabel("Hello World from PyQt")
        title.setAlignment(Qt.AlignCenter) # <---

        gridLayout = QGridLayout(centralWidget)
        gridLayout.addWidget(title,  0, 0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    mainWin.close()
    app.quit()
    sys.exit( app.exec_() )

I want the app to be closed "automatically" (without hitting any button or clicking the "x"). I tried close() and app.quit() however it just closes the window. The app is still running on.
Can you, please, help me to overcome this problem?

A: I think I found a solution. Modifying the cod like this gives the desired answer

import sys
from PyQt5.QtWidgets import (QMainWindow, QLabel, QGridLayout, qApp,
                             QApplication, QWidget, QPushButton)
from PyQt5.QtCore import QSize, Qt

class HelloWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Hello world")

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        title = QLabel("Hello World from PyQt")
        title.setAlignment(Qt.AlignCenter) # <---

        gridLayout = QGridLayout(centralWidget)
        gridLayout.addWidget(title,  0, 0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    timer = QTimer()
    timer.timeout.connect(lambda: app.quit())
    timer.start(100)
    sys.exit( app.exec_() )

The problem here is that we don't have any Python events set up yet. So our event loop never churns the Python interpreter and so our signal delivered to the Python process is never processed. Therefore, our Python process never sees the signal until we hit the exit button of our Qt application window. (source: https://machinekoder.com/how-to-not-shoot-yourself-in-the-foot-using-python-qt/)


text:
Q: A more efficient proof of associativity law for a given binary operation Consider the following definition for a binary operation on the real numbers.

Let $x$ and $y$ be real numbers. Define the operation $*$ as follows.
$$x * y = \begin{cases} x, & \text{if} & x \geq y \\ y, & \text{if} & x \leq y. \end{cases}$$

Let $a$, $b$ and $c$ be real numbers. Prove that $(a * b) * c = a * (b * c).$
As a first attempt, we could use the Trichotomy Law and treat each case separately. Although, when we think of the number of cases that we have to consider, we easily give up on this approach. (Since we would have to consider about $13$ cases, if I'm not wrong.)
I am seeking now an alternative (and possibly, a more efficient) proof for this result.
Does anyone have an idea of how to do it?
I also tried to rely on the meaning of this operation, i.e., looking at the definition, we easily conclude that $a * b$ gives the greatest number, if $a \neq b$, or just $a$ or $b$ in the case $a = b.$ But this not seems very formal to me.

A: As you say, this is precisely the maximum operation $\text{max}(x, y)$, and $\text{max}$ is associative because
$$\text{max}(\text{max}(x, y), z) = \text{max}(x, \text{max}(y, z)) = \text{max}(x, y, z)$$
is just the maximum among the three numbers $x, y, z$; no casework is necessary.


text:
Q: How to respect ratio size when merging ggplot2 figures I'm looking for help in order to merge two plots and respect their respective scale size.
Here is a reproductible example:
    data1<- subset(mtcars, cyl = 4)
    data1$mpg <- data1$mp*5.6
    data2<- subset(mtcars, cyl = 8)

    p1 <- ggplot(data1, aes(wt, mpg, colour = cyl)) + geom_point()
    p2 <- ggplot(data2, aes(wt, mpg, colour = cyl)) + geom_point()

    grid.arrange(p1, p2, ncol = 2)

But what I'm looking for is to merge the two plots and respect the scale size and get something like :

It would be nice to not use a package which need to define the ratio since it's difficult to known how much I should reduce the second plot compared to the first one... And event more difficult when we have more than 2 plots.

A: I think what you are trying to achieve is something like this:
library(tidyverse)

mtcars %>%
        filter(cyl %in% c(4, 8)) %>%
        mutate(mpg = ifelse(cyl == 4, mpg * 5.6, mpg)) %>%
        ggplot(aes(x = wt, y = mpg, col = as.factor(cyl))) +
        geom_point(show.legend = FALSE) +
        facet_wrap(~ cyl)

NOTE: I see some bugs in your original code. For example, if you want to use subset() to subset your data, you have to change your code from:
data1 <- subset(mtcars, cyl = 4)

to:
data1 <- subset(mtcars, cyl == 4)

subset(mtcars, cyl = 4) does not do anything.


text:
Q: How to align logo at left and navigation on right side? How to align the logo to my navigation bar?
My HTML code is:

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="icon" type="image/png" href="SENCOR_Logo.ico">
<title>SENCOR</title>

Monitoring

Process

Post and Create Email/Excel

Reports

Tools

Sales

and heres my style.css code:
body{
    margin: 0;
    padding: 0;
    font-size: 15px;
}

/* Navigation */
nav{
    margin: 0;
    overflow:hidden;
    text-align: center;
}

nav ul{
    margin: 0;
    padding: 0;
}

nav ul li{
    display: inline-block;
    list-style-type: none;
}

nav > ul > li > a{
    color: #aaa;
    display: block;
    line-height: 2em;
    padding: 0.5em 1em;
    text-decoration: none;
}
-----------
.logo-img{
    position: relative;
    margin: 10px 15px 15px 10px;
}
.bg-div{
    background:#333;
}

I want to display the logo at the left side and the navigation bar to the right side.

A: Made a pen far more simpler:
https://codepen.io/DevAlokes/pen/yLEJEYY
* {
  text-decoration: none;
  list-style-type:none;
  color: white
}
.bg-div {
  background-color: #333;
  display: flex;
  justify-content: space-between;
}
nav ul {
  display: flex;
}
nav ul li{
  margin: 0 12px;
}

A: The simplest and most basic answer is, use floats.
.logo-img {
    float: left;
}
nav {
    float: right;
}

A: Normally, it's better to use "position: fixed;" for navigation bars on top. So, your css can do like this:
.logo-img{
    position: fixed;
    margin: 10px 15px 15px 10px;
    left: 0;
    display:inline;
}

.bg-div{
    background:#333;
    height: 50px;
}

.bg-div nav {
    position: fixed;
    display:inline;
    right: 0;
}


text:
Q: Pandas DataFrame from Dictionary with Lists I have an API that returns a single row of data as a Python dictionary. Most of the keys have a single value, but some of the keys have values that are lists (or even lists-of-lists or lists-of-dictionaries).
When I throw the dictionary into pd.DataFrame to try to convert it to a pandas DataFrame, it throws a "Arrays must be the same length" error. This is because it cannot process the keys which have multiple values (i.e. the keys which have values of lists).
How do I get pandas to treat the lists as 'single values'?
As a hypothetical example:
data = { 'building': 'White House', 'DC?': True,
         'occupants': ['Barack', 'Michelle', 'Sasha', 'Malia'] }

I want to turn it into a DataFrame like this:
ix   building         DC?      occupants
0    'White House'    True     ['Barack', 'Michelle', 'Sasha', 'Malia']

A: This turns out to be very trivial in the end
data = { 'building': 'White House', 'DC?': True, 'occupants': ['Barack', 'Michelle', 'Sasha', 'Malia'] }
df = pandas.DataFrame([data])
print df

Which results in:
    DC?     building                         occupants
0  True  White House  [Barack, Michelle, Sasha, Malia]

A: This works if you pass a list (of rows):
In [11]: pd.DataFrame(data)
Out[11]:
    DC?     building occupants
0  True  White House    Barack
1  True  White House  Michelle
2  True  White House     Sasha
3  True  White House     Malia

In [12]: pd.DataFrame([data])
Out[12]:
    DC?     building                         occupants
0  True  White House  [Barack, Michelle, Sasha, Malia]

A: Solution to make dataframe from dictionary of lists where keys become a sorted index and column names are provided. Good for creating dataframes from scraped html tables.
d = { 'B':[10,11], 'A':[20,21] }
df = pd.DataFrame(d.values(),columns=['C1','C2'],index=d.keys()).sort_index()
df

    C1  C2
A   20  21
B   10  11

A: Would it be acceptable if instead of having one entry with a list of occupants, you had individual entries for each occupant? If so you could just do
n = len(data['occupants'])
for key, val in data.items():
    if key != 'occupants':
        data[key] = n*[val]

EDIT: Actually, I'm getting this behavior in pandas (i.e. just with pd.DataFrame(data)) even without this pre-processing. What version are you using?

A: I had a closely related problem, but my data structure was a multi-level dictionary with lists in the second level dictionary:
result = {'hamster': {'confidence': 1, 'ids': ['id1', 'id2']},
          'zombie': {'confidence': 1, 'ids': ['id3']}}

When importing this with pd.DataFrame([result]), I end up with columns named hamster and zombie. The (for me) correct import would be to have these as row titles, and confidence and ids as column titles. To achieve this, I used pd.DataFrame.from_dict:
In [42]: pd.DataFrame.from_dict(result, orient="index")
Out[42]:
         confidence         ids
hamster           1  [id1, id2]
zombie            1       [id3]

This works for me with python 3.8 + pandas 1.2.3.

A: if you know the keys of the dictionary beforehand, why not first create an empty data frame and then keep adding rows?


text:
Q: Strange behavior with external library of Tikz and media9 package When using external library of Tikz and includemedia of media9 package in a beamer presentation, PDF files generated by external library has an abnormal size.
In the simple example below, when compile without including the video, PDF standalone files for tikz figure are very small (about 1ko) but when compile with the video, PDF files are much bigger (5.5 Mo !! for the second figure).
My presentation uses a lot of tikz figures (more than 100 !) and some videos (about 40 Mo each). When I compile it (MacTex 2015 / Tekmaker) more than 4Go of PDF files are generated !!!
I tried to deactivate externalize with \tikzexternaldisable .... \tikzexternalenable but it has no effect ...
How can I solve this ....
Thank's for Help.
\documentclass[aspectratio=43,8pt]{beamer}
\usepackage{media9,tikz,graphicx}
\usetikzlibrary{external}

\tikzexternalize
\tikzsetexternalprefix{./tikz-fig/}

\begin{document}

\begin{frame}
Example of tikz figure :
\begin{figure}
   \begin{tikzpicture}
         \draw [black,fill=red!10,very thick](0,0) rectangle (5,5);
         \draw [black,fill=blue!10,very thick] (3,2) circle(1);
   \end{tikzpicture}
\end{figure}
\end{frame}

\begin{frame}
Example of video :

\begin{center}
        \includemedia
        [
        playbutton=plain,
        activate=onclick,
        addresource=big_buck_bunny.mp4,
        flashvars={source=big_buck_bunny.mp4}
        ]
        {\includegraphics[width=0.5\textwidth]{poster.png}}{VPlayer.swf}
 \end{center}
 \end{frame}

 \begin{frame}
       Example of tikz figure :
       \begin{figure}
          \begin{tikzpicture}
                \draw [black,fill=red!10,very thick](0,0) rectangle (5,5);
               \draw [black,fill=blue!10,very thick] (4,4) circle(1);
          \end{tikzpicture}
       \end{figure}
 \end{frame}
 \end{document}


text:
Q: How to format phone number from a child input with jquery? I want to format the child input to phone. I think there's something wrong to the phone format when apply to the destination. But I can't figure.

$(document).ready(function() {
  $('.src').on('input', function() {
    var $src = $(this);
    var dst = $src.data('dest');
    $('.tel #' + dst).val($src.val().replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'));
//apply the format to input .tel and # from data-dest
  });
});

Src 1: <input type="text" class="src" data-dest="dest1">
Dest 1: <input type="text" id="dest1" readonly>

Src 2: <input type="text" class="src" data-dest="dest2">
Dest 2: <input type="text" class="tel" id="dest2" readonly>

I expect dest1 to duplicate data from src1. But dest2 format in phone number as well.

A: 1 - just use $('#' + dst) it is an ID, they are unique, no need to prefix with class
2 - Your first input has no class tel
3 - $('.tel #' + dst) targets an element inside of the tel class(descendent) which you don't have
4 - in the new jquery it is recommend that you use $(function() { instead of the good old document ready. They both work currently

$(function() {
  $('.src').on('input', function() {
    var $src = $(this);
    var dst = $src.data('dest');
    $('#' + dst).val($src.val().replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'));
//apply the format to input .tel and # from data-dest
  });
});

Src 1: <input type="text" class="src" data-dest="dest1">
Dest 1: <input type="text" id="dest1" readonly>

Src 2: <input type="text" class="src" data-dest="dest2">
Dest 2: <input type="text" class="tel" id="dest2" readonly>

A: I think you mean:
$('.tel#' + dst)

without the space before the hashtag since you want to match the element with both class "tel" and id "destX".
But writing in the first input won't have any effect as there is no such class on it.

A: Since there is no tel class it doesn't find the dest elements:
Use #dest1 as selector for destination.

$(document).ready(function() {
  $('.src').on('input', function() {
    var $src = $(this);
    const formattedphone = $src.val().replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
    $('#dest1').val(formattedphone);
  });
});

Src 1: <input type="text" class="src" data-dest="dest1" maxlength="10">
Dest 1: <input type="text" id="dest1" readonly>

Src 2: <input type="text" class="src" data-dest="dest2" maxlength="10">
Dest 2: <input type="text" class="tel" id="dest2" readonly>


text:
Q: Custome page when Apache Server is down I've looked at Apache ErrorDocument directive on how to do this. I found an answer here and it mentioned :

You should use a URL to point to your ErrorDocument otherwise if you use a filesystem reference you will get an additional 503 whilst trying to find it.

So here's how my virtualhost looks like. For test purpose i'm pointing it at Google
<VirtualHost *:80>
    ServerName shabbasheep.mydomain.com
    ServerAlias www.mydomain.com

    ErrorDocument 503 https://www.google.com
    ...
    ...
</VirtualHost>

I'm trying to show a maintenance page when my apache server goes down. I'm currently testing this on my local machine before applying it on the live server.
To Test this I stop my apache server and try to access my page hoping the page gets re-directed to the Google Page.
It goes not work :| and I get Firefox can't establish a connection to the server at shabbasheep.mydomain.com.
After doing some further re-search I found a solution that uses RewriteEngine so i went along and added the following to my virtual host.
RewriteEngine On
RewriteCond %{REQUEST_URI} $
RewriteRule $ /https://www.google.com [R=503,L]

Still no luck of redirecting to Google when my server is down. Excuse my understanding on this subject.
Any help on how to solve this is much appreciated.
Thanks in advance


text:
Q: Does Ribbon dynamic tabs exist in Delphi 2010? I am writing an application with ribbon in Delphi. I don't know what are these tabs called technically, but is there any way that I can have tabs that are added when a condition is met and have a different color?
Just like the one when you insert a shape in Word 2007 ("Format" tab) that comes at the end of all the tabs and is dynamic (appears in run-time)?

A: They are called "Context Tabs", and if I'm not mistaken, they are not supported currently.

A: We looked at this when the Ribbon control was first introduced in Delphi. They were not supported in the original ribbon control with Delphi, but I haven't checked to see if they are supported in newer versions.
We looked at the Ribbon controls from DevExpress and TMS, and adopted the TMS cxomponents, as theirs was the only one (at that time) that supported the feature.
Looking at their websites, TMS shows this feature being used. Check the TMS AdvToolBar component. DevExpress' TdxRibbon implements it with the Contexts property.


text:
Q: Filter by one column and then min of another column in PostgreSQL I have PostgreSQL like so
team goals points
ABC  2     45
ABC  4     25
XYZ  5     32
ABC  1     25
XYZ  6     23
ABC  1     35
ABC  8     35

How do I get the row where the goals are minimum for teams ABC
The expected out put is
team goals points
ABC  1     25
ABC  1     35

I thought it was simple (may be it is) but I am not able to figure it out.
I am new to PostgreSQL, so please guide me.

A: Assuming the table is called: team_stats, you can just query by team to get all rows of the team you need, and then just order by the number of goals (from lowest to highest) and choose the first row
    select *
    from team_stats
    where team = 'ABC'
    order by goals asc
    limit 1

This code below is when there are mutiples rows with min goals & all are needed
select * from team_stats
where team = 'ABC'
and goals = (select min(goals) from team_stats where team='ABC')

A: Try distinct on.  This limits to one row per entity, and the order by clause helps you determine which entity to pick:
select distinct on (team)
  team, goals, points
from team_goals
where
  team = 'ABC'
order by
  team, goals

The advantage of this is it will continue to work if you remove the team = ABC filter.
This is a more concise version of this, which should also work:
with cte as (
  select
    team, goals, points,
    min (goals) over (partition by team) as min_goals
  from team_goals
)
select
  team, goals, points
from cte
where
  goals = min_goals and
  team = 'ABC'

The CTE approach can result in duplicates when you have multiple records where the min goals is the same.  This may or may not be desirable, depending on your use case.  row_number could remove duplicates.


text:
Q: Finding a representation $N = x^2 + ny^2$ efficiently I want to find a representation of an integer $N$ of the form $N = x^2 + ny^2$. Any single non-trivial representation (i.e. $x \gt 0, y \gt 0, n \ge 1$) suffices.
A naive algorithm that I have implemented checks for $x, n$ in the ranges
$$
\begin{align}
1 & \le x \le \sqrt N \\
1 & \le n \le \sqrt N
\end{align}
$$
and checks if $Y = N - x^2$ is divisible by $n$ and if it is then checks if $Y/n = y^2$ is a perfect square. If yes, then we have a representation $N = x^2 + ny^2$. This gives a complexity of $O(N)$.
Is there a better algorithm?
Note: I know if factors of $N$ are known and both have representations of the form $a^2 + nb^2$, we could use the Brahmagupta identity. In this case factors of $N$ are unknown and I would like to avoid factoring.


text:
Q: How to pass ENUM variable as input for POSTGRESQL functions I have a function in MySQL  which works fine:
CREATE  PROCEDURE `Accounts_Active`(IN_DeptName VARCHAR(255), IN_Src ENUM('TRAINING','ELZA'))
BEGIN
END$$
DELIMITER ;

But when converted to PostgreSQL:
CREATE or replace FUNCTION Accounts_Active(IN_DeptName VARCHAR(255), IN_Src ENUM('TRAINING','ELZA'))
RETURNS void
AS
$$
BEGIN
      RAISE INFO '    ';
END;
$$ LANGUAGE plpgsql;

The following error occurs:
ERROR:  type enum does not exist
SQL state: 42704

Any guidance on how I can fix this error would be appreciated.

A: Create an enum data type:
CREATE TYPE atype AS ENUM ('TRAINING', 'ELZA');

Then you can use it as function parameter:
CREATE FUNCTION Accounts_Active(
   IN_DeptName text,
   IN_Src atype
) RETURNS void
...

When using enums, remember that you can add values to such a data type, but never again remove them. Often you will be better of using a string data type like text, but of course then you have to write code that checks the input for validity.


text:
Q: Variable scope value along with URL helper rails In my routes.rb, I have configured routes as:
scope "/(:city)", constraints: {city: /ny|dc/} do
    resources :bookings do
        collection do
            get 'checkout'
            ...
end

I want my URL to be /ny/bookings/checkout. If I hardcode it in my controller, it works fine (redirect_to '/ny/bookings/checkout').
But I want to use URL helpers, as I think that would be easier to manage in future instead of hardcoding in many places. How can I pass the city scope along with the helper, so as to get the correct URL? The value of city is stored in the session.
Using redirect_to checkout_bookings(session[:city]) generates a URL /bookings/checkout?city=ny

A: redirect_to checkout_bookings_path(city: 'ny')
# => "/ny/bookings/checkout"


text:
Q: Starting and ending points of a line is given, how to get all the intermediate coordinates ? , android Starting  and ending points of a line is given, how to get all the intermediate coordinates in android ?

A: Google for Bresenham's line algorithm!

A: Equation of a line, two-point form: http://en.wikipedia.org/wiki/Linear_equation#Two-point_form

A: You have two points. All you need is the slope. There is a two-point form for obtaining the slope.


text:
Q: debug python code running in docker container from host using vscode I have a container running on my host with a python process and I have the vs code installed on the host. Is it possible to debug the python process from the host installed vscode ? If yes, how can this be achieved ?

A: Since I do not know what python process you have running, I'll use FastAPI as an example.

*

*First, you need to define a new configuration in the file <project_root>/.vscode/launch.json. To access this file, you can go to the Run & Debug section on the activity bar, and press the cog/wheel at the top.

Add a new item in the configurations like shown below.
{
    "version": "0.2.0",
    "configurations": [
        {
        "name": "Python: Remote Attach",
        "type": "python",
        "request": "attach",
        "connect": {
            "host": "localhost",
            "port": 5678
        },
        "pathMappings": [
            {
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "."
            }
        ]
        }
    ]
}

*Now you need to include debugpy. If you are using a requirements file, you can just add it there. If you use Poetry, you can run poetry add debugpy in your terminal (the Dockerfile example shows how you can use Poetry in a docker image).

*First option - In your Dockerfile you need to run debugpy and make it listen for port 5678.
Now the debugger will start every time you run the container and await attachment.
FROM python:3.10.0

# Set the working directory:
WORKDIR /usr/src

# Copy the pyproject.toml file (or requirements.txt) to cache them in the docker layer:
COPY [ "./src/pyproject.toml", "./"]

# Set the python path if needed.
# For example, if main.py is not located in the project root:
ENV PYTHONPATH="$PYTHONPATH:${PWD}"

# Upgrade pip and install Poetry:
RUN pip install --upgrade pip && pip install poetry==1.1.12

# Project initialization using Poetry:
RUN poetry config virtualenvs.create false \
    && poetry install --no-interaction --no-ansi

# Run the application:
CMD ["python", "-m", "debugpy", "--wait-for-client", "--listen", "0.0.0.0:5678", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload", "--reload-exclude", "tests"]

EXPOSE 8000 5678

*Second option - Set up the debugger in the main.py file by adding the lines below. This means that the debugger will be attached to the container when it starts; if the debugger variable is set to True.

debugger = True

if __name__ == "__main__":
    if debugger:
        import debugpy
        debugpy.listen(("0.0.0.0", 5678))
        debugpy.wait_for_client()

    uvicorn.run(
        "main:app",
        host="localhost",
        port=8000,
        log_level="info",
        reload=True,
    )

*Both examples need the Dockerfile to expose the port 5678.
Now, after running the container, the debugger will "pause" and await attachment. To attach the debugger, go back to Run & Debug section on the activity bar in VSCode and select Python: Remote Attach from the dropdown menu and press play.

Now you should be able to use the debugger inside the docker container.


text:
Q: When to use Fermat's Little Theorem and Euler's Generalization of Fermat's Little Theorem I guess I am having a lot of trouble doing questions and knowing that I have to use either one of these theorems.  For a first year group theory/ring theory class what are some tell-tale hints for when to use either one of these theorems?

A: Fermat's little theorem applies only if $p$ is a prime, whereas the Euler-Fermat theorem can be used for any number. When in doubt, use the generalisation. (I could give a more specific answer if you gave some examples of problems where you don't know which theorem to use).


text:
Q: Assign orignal Image instead of taking UIImage in string
In swift 4 or even in previous version we can get the complete image though this code
ProfileImg.Image = marker.png

etc but In swift 4.2, we can only have
UIimage.init(named: "marker")

Is it a version mistake or removed by own.???

A: From the Xcode 10 beta release notes:

*

*Code completion for Swift image literals was removed in Xcode 10. (38087260)

I imagine this was because the image literals were appearing in the completion list for everything and not just when the context involved UIImage, which was driving everybody crazy. Or maybe it's because the new editor can't accommodate the display of image literals.
The feature will either be restored in a future release or will be abandoned altogether. Time will tell!

A: When you started to write mar.. you ll see the picker that contains your image in the assets. You can pick from here directly.


text:
Q: find a matching line in a txt with python I can test whether a string is in a text file with python like the following:
if(pdfname in open(filename).read()):
   //do something

But how I can I verify it? I want the matching line show up. Thanks.

A: Just loop over the file:
handle = open(filename, 'r')

for line in handle:
  if pdfname in line:
    print line

handle.close()

A: You can print out the relevant lines with the second for statement below, which I've added to your existing code for illustration:
pdfname = "statementConcentrator"
if (pdfname in open("line56.good").read()):
    print "Found it"

lineNum = 0
for line in open("line56.good").readlines():
    lineNum = lineNum + 1
    if pdfname in line:
        print "#%5d: %s"%(lineNum, line[:-1])

This outputs your current line plus my output for verification:
Found it
#  115:  statementConcentrator=0

and, checking that file, that is indeed the line it's found on.
Note that you can simply use a script as follows to do both jobs in a single loop:
pdfname = "statementConcentrator"
lineNum = 0
count = 0
for line in open("line56.good").readlines():
    lineNum = lineNum + 1
    if pdfname in line:
        print "#%5d: %s"%(lineNum, line[:-1])
        count = count + 1
print "Found on %d line(s)."%(count)


text:
Q: storing duplicates in Firestore i currently made a code that allows to import a CSV file into the website,transform it to JSON and then upload it to the firestore database,however in the unique ID that i want to provide for the document names,i have duplicates,because some information in the duplicates are different but i need them none the less,so when there are duplicates firestore only inserts the first document and if it's duplicated it ignores it,my question is,how can i do something that when firestore,finds duplicates,it adds them to a different collection,for example,i have an id called BMW for a collection called cars,BMW will be added to cars collection,then let's say i have 2 more instances of BMW,i want them to be added to the collection called CARS(duplicate)and i want both BMWS to be uploaded into that collection,not just 1,is this achievable? if yes how can i achieve this?,
thank you


text:
Q: why do I get this error if I return value using questionmark operator in Vue.js I just tried to return the value using questionmark operator instead of using return twice. But I got an error "Cannot read property 'omitDescription' of undefined" .
buttonText() {
  return this.omitDescription ? 'プロフィールをもっと見る' : 'プロフィールを閉じる'
  // return function() {
  //   if(this.omitDescription) {
  //     return 'プロフィールをもっと見る'
  //   } else {
  //     return 'プロフィールを閉じる'
  //   }
  // }
}

The part where I commented out did work instead, so I could not figure out the difference.
Thank you!

A: Its not the same, in the previous approach you return an function. Try it like this:
buttonText() {
    return () => this.omitDescription ? 'プロフィールをもっと見る' : 'プロフィールを閉じる';
}


text:
Q: Encoding audio files then renaming them with a bash script I'm writing a Bash script that will run on Linux to convert/encode audio files
The conversion works fine so far, but when it comes to renaming the produced files according to a specific pattern that I have to stick with it produces errors.
A file with the name Audio-001.flac has to be renamed to
2552011-Unit05-Fil001.flac following the pattern: [Recording Date-Recording Unit ID-File ID]
The code I'm using for rename:
echo "Enter Recording Date, Recording Unit-ID, and File-ID Separated by SPACE"
read RD RU FID
echo "Your input is: $RD, $RU, $FD " >> /home/user-name/Music/User-Input.txt #This is for logging
mv $FLACS/*.flac $FLACS/${RD}-${RU}-${FID}.$flac
I'm getting an error: mv: target 22112011-Unit05-File0. is not a directory
Can I use find and sed?
find bar -iname "*.wav" -printf 'mv %p %p\n' \
   | sed 's/*\.wav$/${RD}-${RU}-${FID}\.flac/' \
   | while read l; do eval $l; done`

A: Nice breakdown of needed work, so:

1 - Parse a folder tree (full of .WAV files)

This can be done with several ways, form:
find WHERE -print | grep -i PATTERN #or
find WHERE -name ... print0 | xargs -0 -I% ....  #or the simple
echo ./**/*.wav

2 - use an open source tool such as flac and ffmpeg
  to convert all the .WAV files in that folder tree to .FLAC

Yes, youre right. The general syntax is
flac [<general-options>] [<format-options>] [<encoding options>] [inputfile [...]]

3- Place the .FLAC files in a newly
  created folder tree that is identical
  to the original

Not a hard task. In Linux you can make a directory with the mkdir command. You can get the identical tree from the find command (1). Probably will need to use the dirname command too. (here is other ways too, but dirname is nice)

4- when naming the new .FLAC and their
  respective folders it will add a
  unique identifier to the file names
  i.e folder named 2582001 contains the
  files 2582001-1.wav and 2582001-2.wav
  will be recreated and will contain two
  .FLAC files with the names
  2582001-REC05-FIL1.FLAC and
  2582001-REC05-FIL2.FLAC. This
  structure of the new file names is
  [Recording Date - Recording Unit ID -
  File ID].

Again not a hard task, you can use the following:
command > "${RecordingDate} - ${RecordingUnitID} - ${FileID}"

but not recommening this. Sure will be better name the files without spaces, for example:
command > "${RecordingDate}-${RecordingUnitID}-${FileID}"

if you want rename the file use the mv command, like:
mv oldfilename.ext "${RecordingDate}-${RecordingUnitID}-${FileID}.$newext"

Ps: if you want some more precise answer, try ask more precise. :)

A: You're trying mv more files into "one file".
mv $FLACS/*.flac $FLACS/${RD}-${RU}-${FID}.$flac

*.flac is expanded to more files. You cant move more files into one. When moving more files, the mv want as his last argument a directory.
You probably want:
mv $FLACS/some_one_file.flac  $FLACS/${RD}-${RU}-${FID}.flac


text:
Q: Why do I have 70k instances of ck-get-x11-server-pid running? I have a Ubuntu 14.04 server which currently has 69890 instances of ck-get-x11-server-pid running. The server is headless, but users can login to a using x2go.
Why would there be so many instances of ck-get-x11-server-pid, and can I safely killall ck-get-x11-server-pid?


text:
Q: How to deal with __EVENTVALIDATION in asp.net web scraping? I am dealing with an asp.net page to scrape a table with all rows and all columns, finally converting the scraped data into pandas dataframe.
scrape URL: http://164.100.47.194/Loksabha/Legislation/NewAdvsearch.aspx
configuration :

total bills : 8946
The page looks like this:

Since it's an asp.net page, I used the cookies and all to fetch all data, here is my code:
import requests
from urllib import request
from bs4 import BeautifulSoup
import io
import pandas as pd

from tqdm import tqdm
import requests

def get_res(m_no = 349):
    cookies = {
        'ASP.NET_SessionId': 'kardiuqwo0uwtujdolqgad1w',
        'BNES_ASP.NET_SessionId': 'ItVZt0BeJnb2+gWjdTq7zU5vFrp8Ms0fM9OVEFmTX8eqFxJq469Ts1hO3xbbkLa6PCxSq+jxzbM0s5S4IFhfMD497glM+D7fFOshSi5cC3PoSM8En9W87A==',
    }

    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Mobile Safari/537.36',
        'Origin': 'http://164.100.47.194',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Referer': 'http://164.100.47.194/Loksabha/Legislation/NewAdvsearch.aspx',
        'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
    }

    data = {
      '__EVENTTARGET': 'ctl00$ContentPlaceHolder1$GR1',
      '__EVENTARGUMENT': f'Page${m_no}',
      '__LASTFOCUS': '',
      '__VIEWSTATE': '7aYz0DTI41EdOkRTXKaokkalAlKIRA2Yn..,
      '__VIEWSTATEGENERATOR': 'FB1370BC',
      '__VIEWSTATEENCRYPTED': '',
      '__EVENTVALIDATION': '[encoded data, 5760 characters]',
      'ctl00$txtSearchGlobal': '',
      'ctl00$ContentPlaceHolder1$RadioBttnhouse': 'both',
      'ctl00$ContentPlaceHolder1$RadioBttnbilltyp': 'All',
      'ctl00$ContentPlaceHolder1$RadioButtonList1': '6',
      'ctl00$ContentPlaceHolder1$STitle': '',
      'ctl00$ContentPlaceHolder1$ddlMember': '--- Please Select ---',
      'ctl00$ContentPlaceHolder1$RadioBttnmember': 'Current',
      'ctl00$ContentPlaceHolder1$ddlMinistry': '--- Please Select ---',
      'ctl00$ContentPlaceHolder1$ddlCategory': '--- Please Select ---',
      'ctl00$ContentPlaceHolder1$ddlYear1': 'Select',
      'ctl00$ContentPlaceHolder1$ddlYear2': 'Select',
      'ctl00$ContentPlaceHolder1$ddlfile': '.xls'
    }

    response = requests.post('http://164.100.47.194/Loksabha/Legislation/NewAdvsearch.aspx', headers=headers, cookies=cookies, data=data, verify=False)

    soup     = BeautifulSoup(response.text)
    tables   = soup.findChildren('table')
    return tables

def get_all_bills(html):
    soup  = BeautifulSoup(html)
    links = soup.findAll('a')
    return links

def single_table_values(row_id):

    df_values = {'Year': [], 'Bill No': [], 'Short Title': [],
                 'Type': [], 'Member': [], 'Date of Introduction / House': [],
                 'Debate / Passed in LS': [],
                 'Debate / Passed in RS': [],
                 'Referred to Committee / Report Presented': [],
                 'Assent Date/ Gazette Notification / Act No.': [], 'Synopsis': [], 'Status': [], 'link': []}

    col_seq = {0: 'Year', 1: 'Bill No', 2: 'Short Title', 3: 'Type', 4: 'Member',
               5: 'Date of Introduction / House', 6: 'Debate / Passed in LS',
               7: 'Debate / Passed in RS',
               8: 'Referred to Committee / Report Presented',
               9: 'Assent Date/ Gazette Notification / Act No.',
               10: 'Synopsis', 11: 'Status', 12: 'link'}

    data = row_id.findChildren('td')
    for value in range(len(data)):

        try:
            if value == 2:
                try:
                    df_values['link'].append(data[value].find_all('a')[1]['href'])
                except Exception as e:
                    df_values['link'].append('no_link')
                df_values['Short Title'].append(data[value].text)
            else:
                df_values[col_seq[value]].append(data[value].text.strip())

        except Exception as e:
            pass
    try:
        df = pd.DataFrame(df_values)

    except Exception as e:
        df_values = {'Year': [], 'Bill No': [], 'Short Title': [],
                 'Type': [], 'Member': [], 'Date of Introduction / House': [],
                 'Debate / Passed in LS': [],
                 'Debate / Passed in RS': [],
                 'Referred to Committee / Report Presented': [],
                 'Assent Date/ Gazette Notification / Act No.': [], 'Synopsis': [], 'Status': [], 'link': []}

        df = pd.DataFrame(df_values)
    return df

The problem is above code works for page no 349:
mj       = get_res(m_no = 349)
rows     = mj[7].findChildren(['th', 'tr'])
single_table_values(rows[17])

the result looks like this:

But if I use some cookies and code for another page such as 3,4 etc then it scrapes no data, but if I change the _EVENTVALIDATION in data then it works, I want to fetch all pages in the loop, how I can use the same above setup ( cookies, etc ) for all pages?


text:
Q: Drag and Drop images from another website to mine I ran a quick google and SO search and found similar questions but none were well formed and most were old and looked abandoned (no answers, and no comments for a while). So here goes...
I want to be able to collect the url (only the url) of an image being dropped onto my site from another website.. (i.e. I have two chrome windows open. Window A has my application in it. Window B has imgur in it. I open an image click and drag it to my window and let go. Now I need to know the url of the image dropped on my page).
Here is the code I was working with for local files.
$(document).on('drop', function(e) {
    var data = e.dataTransfer || e.originalEvent.dataTransfer;
    console.log(data); // data.files is empty
    e.preventDefault();
    return false;
});

Again I do not want to upload anything.. i'm not trying to do anything fancy... I just need to know the location of the image being dropped on the page from another website.

A: You can use this
$(document).bind('drop', function (e) {
    var url = $(e.originalEvent.dataTransfer.getData('text/html')).filter('img').attr('src');
    if (url) {
        jQuery('<img/>', {
            src: url,
            alt: "resim"
        }).appendTo('#yourId');
    }
    return false;
})

A: Based on Yunus's answer , this seems to work in FF:
e.originalEvent.dataTransfer.getData('text/html').match(/src\s*=\s*"(.+?)"/)[1]

A: Try this: http://jsfiddle.net/2Jet2/70/
$(document).on('dragover', function(e) {
     e.preventDefault();
});
$(document).on('drop', function(e) {
    e.preventDefault();
    e.originalEvent.dataTransfer.items[0].getAsString(function(url){
        alert(url);
    });
});

I get "http://static3.flattr.net/thing/image/9/4/5/5/0/huge.png?1326712342" When I dragged that image from another browser window.
.getAsString takes a callback which gets the url as argument once it's called
Doesn't work on firefox


text:
Q: Regex for lex I am developing a simple translator from MathML to Latex, using Lex and Yacc. In my lex file containing the regex rules I have one defined for arithmetic operators [-+*=/]. I want to extended so that it would recognize plus-minus (+-) and invisible times ('&InvisibleTimes'), but I'm unfamiliar with regex and I need some help.

A: Would something like this work?
(?:[-+*=/]|\+-|&InvisibleTimes)

A: Try this:
([-+*=/]|\+-|&InvisibleTimes)

Note that you need to escape the + in +- because it's an operator outside of character classes. You can do this with backslash (as I've done here) or with double quotes. (The double-quote syntax is pretty unusual -- most other regex implementations only use backslash for escaping, so I'd be inclined to use backslashes as it makes the regex more "conventional".)

A: I'm not very familiar with MathML, so I have the opposite problem of you. As others have said, you can do this all in one regex, like this:

[-+*=/]|\+-|&InvisibleTimes

However, if you want to have different actions associated with each of these, you need to do it like this:

[-+*=/]            {/* action 1 here */}
\+-                {/* action 2 here */}
&InvisibleTimes    {/* action 3 here */}


text:
Q: Excel to WiKi macro I need one macro for converting Excel spreadsheet to wiki format and post the same in wiki.
Sample data
Column-1    Column-2    Column-3
A           Val1          Val1
B           Val2          Val2
C           Val3          Val3

Lets say that we want to post the converted table to dummy := https://wiki.com/w/Qc/MyPage

A: i Managed to develop the below code which almost makes a WikiSyntax.
Select the cell range to convert and run the macro.
Sub SelectionToWiki()
PadConst = "cellpadding=""1"" cellspacing=""1"" border=""1"" style=""width: 100%;"""
result = ""
result = result & " "

For i = 1 To Selection.Rows.Count
    For j = 1 To Selection.Columns.Count
        Dim cell As Range
        Set cell = Selection.Cells(i, j)
        cellStr = cell.Value
        result = result & Chr(13) & "| " & cellStr
    Next
    result = result & Chr(13) & "|-" & Chr(13)
Next

result = "{| " & PadConst & result & "|}"
Dim MyDataObj As New DataObject
MyDataObj.SetText result
MyDataObj.PutInClipboard

MsgBox "Wiki table copied to clipboard: " & Chr(13) & Chr(13) & result

End Sub
Enhancements will be much appreciated.


text:
Q: What is the similar key type in Google Cloud Platform like Access Key to AWS? I am trying to create an application where I have to access all the projects of Google Cloud Platform.
I came up with an option of generating Service Accounts for all the Projects and add them to my project.
Is there any way to access all the Projects with one service token or a similar one just like AWS Access Key to access all the AWS projects at once?

A: You can do this within an organisation via an org level service key.
https://cloud.google.com/resource-manager/docs/quickstart-organizations


text:
Q: Fix crash due to SIGILL in OpenSSL I've read several Q&As here regarding the fact that OpenSSL tries different instructions to test if cpu supports them, which causes SIGILL. But those answers usually state that OP was running the app under gdb, but I'm not. So my app on OpenWrt MIPS router actually crashes when using OpenSSL, whenever I make a call to OpenSSL library. The crash is illegal instruction. I actually don't have a backtrace, though my app is a debug build. It works fine on Ubuntu and MacOS.
I made sure that both my executable and ssl libs are of the same cpu architecture.
Result of cat /proc/cpuinfo:
system type             : Atheros AR9330 rev 1
machine                 : 8devices Carambola2 board
processor               : 0
cpu model               : MIPS 24Kc V7.4
BogoMIPS                : 265.42
wait instruction        : yes
microsecond timers      : yes
tlb_entries             : 16
extra interrupt vector  : yes
hardware watchpoint     : yes, count: 4, address/irw mask: [0x0ffc, 0x0ffc, 0x0ffb, 0x0ffb]
isa                     : mips1 mips2 mips32r1 mips32r2
ASEs implemented        : mips16
shadow register sets    : 1
kscratch registers      : 0
package                 : 0
core                    : 0
VCED exceptions         : not available
VCEI exceptions         : not available

What worries me is that toolchain toolchain-mips_34kc_gcc-5.2.0_musl-1.1.11 mentions 34kc in its name. I wonder if it's ok to build with this toolchain for 24 Kc cpu. Though everything else except for openssl works fine.
So could you please answer what are my options to fix it?

A: I don't know what the problem was, but the app didn't work with the openssl library provided in the toolchain and copied to target board. When libopenssl was installed via opkg from official carambola2 repos, the problem is gone. So it must have been some incompatibility.


text:
Q: Formatting Strings Given Place Holders I have to replace certain placeholders with variables from a list, however I am unsure about how to reformat the placeholders.
warning = 'I don\'t recognize the name {0}. Did you mean {1}?'

The above line of code is what I need to reformat. Any help would be appreciated.

A: This is a default Python formatting string, it can be used with format.
>>> warning = 'I don\'t recognize the name {0}. Did you mean {1}?'
>>> warning.format("Meliodus123", "format")
"I don't recognize the name Meliodus123. Did you mean format?"

The number in {0} represent the argument position passed to format.


text:
Q: Ajax function working without refreshing the page Data is being deleted but I can't see the ajax function working without refreshing the page.
I use thymeleaf. I have to refresh the page to see the data is deleted. What am I doing wrong in the code?

function deleteUser(userId) {
    var id = userId;
    var token = $("meta[name='_csrf']").attr("content");
    $.ajax({
        type : "DELETE",
        url : "/deleteUser/" + userId,
        contentType: "application/json",
        dataType : 'json',
        headers:
           'X-CSRF-TOKEN': token
        },
        success: function (data) {
        console.log(data);
        },
        error: function (e) {
            console.log(e);
        }
    });
    }

            Value1
            Value2
            Value3


text:
Q: Google Analytics Funnel reports differ from pageviews I've created goal funnels with a required first step, /cancel. When I look at my pageviews reports, the unique pageviews for the /cancel page differ from the value reported in the funnel visualization for the required step 1. Why?

A: In the funnel report the number is sessions and not pageviews.
Here are the definitions:
Sessions: total number of Sessions within the date range. A session is the period time a user is actively engaged with your website, app, etc. All usage data (Screen Views, Events, Ecommerce, etc.) is associated with a session.
Pageviews: is the total number of pages viewed. Repeated views of a single page are counted.
Unique Pageviews: is the number of sessions during which the specified page was viewed at least once. A unique pageview is counted for each page URL + page Title combination.
It is important to know that the unique page metric does not closely match the deduplication of the number of times a page has been viewed in a session, as a unique pageview in Analytics is counted for each page URL + page Title combination.
So you can't consider page views because goals talk about sessions and you can't compare these metrics because they are different information with different scope.


text:
Q: How can I solve RangeError (index): Invalid value: Valid value range is empty: 1? When I navigate to a new screen, suddenly I get an error like this. What could be the reason?

I tried several ways but I was unable to solve.What can be reason? I have been looking for the solution of this problem, but there is not enough info.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../providers/question_fetch.dart';
import 'package:provider/provider.dart';
import '../widgets/choice_buttons.dart';
import '../widgets/asked_questions.dart';

class SurveyScreen extends StatefulWidget {
  int index = 1;
  static String route = '/survey';
  SurveyScreen({super.key});

  @override
  State<SurveyScreen> createState() => _SurveyScreenState();
}

class _SurveyScreenState extends State<SurveyScreen> {
  @override
  void initState() {
    Future.delayed(Duration.zero).then((value) async {
      showDialog(
        context: context,
        builder: (context) {
          return const Scaffold(
              backgroundColor: Colors.transparent,
              body: Center(
                  child: CircularProgressIndicator(
                color: Colors.red,
                backgroundColor: Colors.white,
              )));
        },
      );

      await Provider.of<QuestionFetch>(context, listen: false)
          .fetchAndSetQuestions()
          .then((_) => Navigator.of(context).pop());
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var surveyQuestions = Provider.of<QuestionFetch>(context).questions;
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          elevation: 0,
          leading: IconButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              icon: Icon(
                Icons.arrow_back,
                color: Theme.of(context).primaryColor,
              )),
          backgroundColor: Theme.of(context).canvasColor,
          title: Text(
            'Survey',
            style: TextStyle(color: Theme.of(context).primaryColor),
          ),
        ),
        body: Column(
          children: [
            const AskedQuestions(),
            ChoiceButtons(
                possibleAnswers:
                    surveyQuestions[widget.index].possibleAnswers,
                idQuestion: surveyQuestions[widget.index].id),
          ],
        ));
  }
}


text:
Q: Existence of a particular sequence of sets for a probability measure Let $\mu$ be a probability measure on $(\mathbb{R}, \mathcal{B}(\mathbb{R}))$ and let $A \in \mathcal{B}(\mathbb{R})$ be such that $\mu(A)>0$.

Under what conditions on $\mu$ will there exist a sequence of sets $B_n \in \mathcal{B}(\mathbb{R})$ such that $\mu(A \triangle B_n) >0$ for all $n \in \mathbb{N}$ and $\mu(A \triangle B_n) \rightarrow 0$ as $n \rightarrow \infty$.

It is not diffuclt to come with a particular $\mu$ and $A$ for which the requirement is fullfilled. For example, assume that $\mu$ has Lebesgue density and $A=[0, 1]$. Take $B_n = [1/n, 1]$. Then the sequence of sets $A \triangle B_n = [0, 1/n)$ decreases to $\{0\}$, which is a null set.
Can something similar be down for an arbitrary set $A$ which is not a null set?
What if $\mu$ does not have a Lebesgue density?

A: If you can do it with $A = \varnothing$, then you can do it in general.
Assume there exist $F_n$ with $\mu(F_n) \to 0$ and $\mu(F_n)>0$.  So, given $A$, let $B_n = A\triangle F_n$.  Then
$$
A\triangle B_n = A\triangle(A\triangle F_n) = (A\triangle A)\triangle F_n = F_n .
$$


text:
Q: Uniform integrability for a Martingale (defined via Poisson process) I'm trying to solve the following exercise:

Let us consider the martingale $M_t = (N_t - \theta t)^2 - \theta t$. where $(N_t)_t$ is a homogeneous Poisson process with parameter $\theta$.
  Decide if the family $(M_t)_t$ is uniformly integrable a

My attempt
I tried to use the definition  of uniform integrable familiy, but I got stuck, so I tried to show it's actually not a uniformly integrable family by showing that $$\sup_{t \geq 0}E[|M_t|] \rightarrow +\infty$$
Indeed: $$E[|M_t|]\geq|E[M_t]| = |E[N_t^2 - 2 \theta t N_t + \theta^2 t^2 - \theta t]| = |\theta t (\theta t -1) + t(t+1)- 2 \theta t^2| = |t^2(\theta - 1 )^2 + t(1-\theta)|$$
Where I used linearity of expectation and $E[N_t^2] = t(t+1)$ and $E[N_t] = t$ since $N_t$ is a Poisson process.
The supremum of that thing is $\infty$ so the family is not uniformly integrable.
Is it okay?

A: I can't really follow your computations. Since $N_t$ is Poisson distributed with parameter $\theta t$, we have
$$\mathbb{E}(N_t^2) = \theta^2 t^2 + \theta t$$
and $$\mathbb{E}(N_t) = \theta t.$$
This gives
\begin{align*} \mathbb{E}((N_t-\theta t)^2) &= \mathbb{E}(N_t^2) -2 \theta t \mathbb{E}(N_t)+\theta^2 t^2 \\ &= \theta^2 t^2 + \theta t - 2 \theta^2 t^2 + \theta^2 t^2 \\ &= \theta t \end{align*}
and so $$\mathbb{E}(M_t) = \mathbb{E}((N_t-\theta t)^2) - \theta t = 0.$$ In particular, your assertion that $\sup_t |\mathbb{E}(M_t)|=\infty$ is wrong.
To show that $(M_t)_{t \geq 0}$ is not uniformly integrable, we can argue as follows: By the central limit theorem, we have
$$\frac{N_t-\theta t}{\sqrt{\theta t}} \to U \sim N(0,1) \quad \text{in distribution}.$$
In particular,
$$\mathbb{P}(|N_t-\theta t| \geq 2 \sqrt{\theta t}) \to \mathbb{P}(|U| \geq 2)>0.$$
Hence,
\begin{align*} \mathbb{E}(|M_t|) &\geq \mathbb{E} \bigg( \big[ |N_t-\theta t|^2 - \theta t\big] 1_{\{|N_t-\theta t| \geq 2 \sqrt{\theta t}\}} \bigg)  \\ &\geq 3 \theta t \mathbb{P}(|N_t-\theta t| \geq 2 \sqrt{\theta t}) \\ &\xrightarrow[]{t \to \infty} \infty.\end{align*}
This shows that $\sup_{t \geq 0} \mathbb{E}(|M_t|)=\infty$, and so $(M_t)_{t \geq 0}$ is not uniformly integrable.


text:
Q: Asymptotic behavior of solution to differential equation I've just started my first class in ODE's and I'm kind of stuck with the idea of asymptotic behavior.
The problem as is follows:
Find the general solution and use it to determine the asymptotic behavior for different values of a. $y(0) = a$ as $t\rightarrow$ $+\infty$.
$$y' - \frac{1}{2}y = 2\cos(t)$$
I've solved for the general solution:
$$y = \frac{4}{5}(2\sin(t)+\cos(t)) + Ce^{-t/2}$$
Where do I go from here? Thank you for any guidance.

A: EDIT:
The general solution actually appears to be $y=\frac{4}{5}(2\sin{t}-\cos{t})+Ce^{t/2}$, which I used but then copied OP's general solution when typing my answer. Sorry!
From my reading of the question, you want to determine the behavior of $y(t)$ as $t \rightarrow +\infty$. Your general solution consists of two parts; the first:
$$
\frac{4}{5}(2\sin{t}-\cos{t})
$$
is periodic, and can be ignored in the long run once we consider the second:
$$
Ce^{t/2}
$$
which grows without bound. So, we can say that $y(t) \rightarrow +\infty$ when $C>0$, $y(t) \rightarrow -\infty$ when $C<0$, and its behavior is undefined when $C=0$. Now you just have to figure out what initial conditions $y(0)=a$ correspond to what values of $C$, which should be pretty simple. I hope I read your question correctly, and good luck in your ODE class!


text:
Q: Parsing with AngleSharp Writing programm to Parse some data from one website using AngleSharp. Unfortunately I didn't find any documentation and it makes understanding realy hard.

*

*How can I by using QuerySelectorAll get only link? I'm getting now just all things ... with Name of article.

1. Name of artucle
The method I'm using now:
var items = document.QuerySelectorAll("a").Where(item => item.ClassName != null && item.ClassName.Contains("object-title-a text-truncate"));

*In the previous example I also used  ClassName.Contains("object-name"), but if we deal with table cells, there are no any class. As I understand to parse right element maybee I must use some info about parent also. So here is the question, how can I get this '4' value from tabble cell?

....Room
4	....

A: Regarding your first question.
Here is an example that you can extract the link address.
This a Link of another Stackoveflow post that is related.
var source = @"1. Name of artucle";
var parser = new HtmlParser();
var doc = parser.Parse(source);

var selector = "a";

var menuItems = doc.QuerySelectorAll(selector).OfType<IHtmlAnchorElement>();

foreach (var i in menuItems)
{
    Console.WriteLine(i.Href);
}

For your Second question, you can check the example on the documention, here is the Link and below is the code sample:
// Setup the configuration to support document loading
var config = Configuration.Default.WithDefaultLoader();
// Load the names of all The Big Bang Theory episodes from Wikipedia
var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
// Asynchronously get the document in a new context using the configuration
var document = await BrowsingContext.New(config).OpenAsync(address);
// This CSS selector gets the desired content
var cellSelector = "tr.vevent td:nth-child(3)";
// Perform the query to get all cells with the content
var cells = document.QuerySelectorAll(cellSelector);
// We are only interested in the text - select it with LINQ
var titles = cells.Select(m => m.TextContent);


text:
Q: jQuery. Replacing text in a table is unformatting the entire table I'm using jQuery to replace two words "Final Cost" in a table and replace them with "Current Projected Cost". I've gotten the code to change the words but it takes away the formatting. (removes dynamically created bold (strong) and line returns - br/).
Here is the current code:
 $("document").ready(function(){

    $(".current-projects td:contains(Final Cost:)").text(function (i, old) {
 return old
      .replace('Final Cost', 'Current Projected Cost');

    });
});

Here is a link to see issue:
http://www.lampinc.net/projects/current-projects/cgh-medical-center-emergency-department-expansion-and-renovation/
How do I help to preserve the formatting? Thanks.

A: Use .html() to keep all the markup:
$(".current-projects td:contains(Final Cost:)").html(function (i, old) {
    return old.replace('Final Cost', 'Current Projected Cost');

});


text:
Q: Keep calling a rest API until server completes the task I am calling a REST API synchronously from a Spring boot app (in JAVA 11) to download a file.
This is how the REST API looks like:
@GetMapping("/download/{userId}/{fileName}")
public String download(final int userId, final String fileName) {
        if(requested file is available) {
             return {file location URL}
        } else {
             Begin generating a new file (takes 5 seconds to more than 5 minutes)
             return "file generation in progress"
        }
    }

The API returns two things, either it returns the status of the file if it is generating the file (which takes anywhere from 5 seconds to 5 minutes or more), or the file location URL itself if the file is generated.
The problem I am trying to solve is, I need to call this "/download" API every 5 seconds and check if the file is ready or not.
Something like this:

*

*First call the "/download" -> API returns "file generation in progress" status

*so, call it again after 5 seconds -> API returns the "file generation in progress" status again

*so, call it again after 5 seconds -> API returns the "file generation in progress" status again (But by this time assume that the file is generated)

*so, call it another time after 5 seconds -> API returns the file location URL

*Stop calling the API and do the next things

Is there a way I can achieve this? I tried looking CompletableFuture & @Scheduled but I am so new to both of these options and couldn't find any way to implement them in my code. Any help would be appreciated!

A: You can make use of the Java Failsafe Library. Refer the answer from [Retry a method based on result (instead of exception). I have modified the code from the answer to match your scenario.
private String downloadFileWithRetry() {
    final RetryPolicy<String> retryPolicy = new RetryPolicy<String>()
        .withMaxAttempts(-1)
        .handleResultIf("file generation in progress"::equalsIgnoreCase);

    return Failsafe
        .with(retryPolicy)
        .onSuccess(response -> System.out.println("Generated file Url is ".concat(response.getResult())))
        .get(this::downloadFile);
}

private String downloadFile() {
    return "file generation in progress";
}