text:
Q: Android Tablayout and statemanagement I have a tablayout setup with viewpagers that have a RecyleView adapter.
When the user clicks a list item , new activity opens. When back button is pressed the Recycleview resets to the first tab and list items.
How do i store the state of the mainactivity from where the list item was clicked?

A: Don't worry you just have to use finish() in your onBackPressed() method in the Activity. finish() method just finishes off the activity and make the user to come to the same place from where he started the transition.
Do like this and get your job done :
public class YuorActivity extends AppCombatActivity{
   onCreate(){
     //nothing to do here
   }

  @Override
  public void onBackPressed() {
       //finishes the activity and let you come to the same fragment
       super.onBackPressed();
       this.finish();
  }
}

Hope that helps!

A: I am using google sign in for this app. So when ever I return back from the intent activity the function onConnected() was called and my adapter was reset. I used some logic and stopped the execution when returned back and it works.
Thank you for your help


text:
Q: Add OpenLayers map on map canvas with PyQGIS I have map canvas with two shapesfiles, and I want to add OSM map behind. My code for this is:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QHBoxLayout, QDockWidget, QWidget
from osgeo import gdal
from qgis.core import *
from qgis.gui import *

layerInput = QgsVectorLayer('path to shape file1', "file 1", "ogr")
layerInputShape = QgsVectorLayer('path to shape file2', "file 2", "ogr")

# canvas settings
canvas = QgsMapCanvas()
canvas.setCanvasColor(Qt.white)
canvas.enableAntiAliasing(True)

#defining OSM
xml = """<GDAL_WMS>
<Service name="TMS">
<ServerUrl>http://tile.openstreetmap.org/${z}/${x}/${y}.png</
ServerUrl>
</Service>
<DataWindow>
<TileLevel>18</TileLevel>
<TileCountX>1</TileCountX>
<TileCountY>1</TileCountY>
<YOrigin>top</YOrigin>
</DataWindow>
<Projection>EPSG:4326</Projection>
<BlockSizeX>256</BlockSizeX>
<BlockSizeY>256</BlockSizeY>
<BandsCount>3</BandsCount>
<Cache />
</GDAL_WMS>"""
vfn = "/vsimem/osm.xml"
gdal.FileFromMemBuffer(vfn, xml)
rasterLyr = QgsRasterLayer(vfn, "OSM")

# puting both vector layers on canvas
extent = QgsRectangle()
layers = []
QgsProject.instance().addMapLayer(layerInput)
extent.combineExtentWith(layerInput.extent())
layers.append(layerInput)
QgsProject.instance().addMapLayer(layerInputShape)
extent.combineExtentWith(layerInputShape.extent())
layers.append(layerInputShape)

#puting osm on canvas
QgsProject.instance().addMapLayer(rasterLyr)
extent.combineExtentWith(rasterLyr.extent())
layers.append(rasterLyr)

extent.scale(1.1)
canvas.setExtent(extent)
canvas.setLayers(layers)

# for legend
root = QgsProject.instance().layerTreeRoot()
bridge = QgsLayerTreeMapCanvasBridge(root, canvas)
model = QgsLayerTreeModel(root)
model.setFlag(QgsLayerTreeModel.AllowNodeReorder)
model.setFlag(QgsLayerTreeModel.AllowNodeRename)
model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility)
model.setFlag(QgsLayerTreeModel.ShowLegend)
view = QgsLayerTreeView()
view.setModel(model)
view.show()

# embed the view and canvas into dock widget
layout = QHBoxLayout()
layout.addWidget(view)
layout.addWidget(canvas)
docked = QDockWidget()
docked.setContentsMargins(9, 9, 9, 9)
dockedWidget = QWidget()
docked.setWidget(dockedWidget)
docked.setWindowTitle('title')
dockedWidget.setLayout(layout)
docked.show()

# canvas properties
QgsProject.instance().addMapLayer(layerInput)
canvas.setExtent(layerInput.extent())
canvas.setLayers([layerInput])

canvas.refresh()
canvas.show()
app.exec_()

But on the map canvas, I just get shapefiles, without OSM map.

redpajama_set_name: RedPajamaStackExchange


text:
Q: checking if column is zero before updating How do i insert into a database checking if the column is zero before inserting into it
this is what i have tried but after updating it still insert a new row with the last inserted ID but rather i just want it to update without inserting
    $lastID = mysqli_insert_id($DBcon);
    $query2=$DBcon->query("SELECT * FROM mergeing");
    $compare_value = "0";
    if($row = $query2->fetch_array()) {
        $merger = "INSERT into mergeing(donator_1) VALUES ('$lastID')";
        if($row['donator_2'] !== "$compare_value") {
            if ($DBcon->query($merger)) {
                echo "success second";
            }
        }
    }
    while ($row = $query2->fetch_array()) {
        $idd= $row["_id"];
        $merg2 = "UPDATE mergeing SET donator_2='".$lastID."'  WHERE _id=$idd";
        if($row['donator_2'] === "$compare_value") {
            if ($DBcon->query($merg2)) {
                echo "success";
            }
        }
    }

A: It seems you want to check if there is a record that has a specific donator_2 value, and if so, you want it updated. If no such value is present, you want to insert a new record.
Then your code could look like this:
$lastID = mysqli_insert_id($DBcon);
$compare_value = 0;
$DBcon->query("UPDATE mergeing SET donator_2 = $lastID WHERE donator_2 = $compare_value");
if ($DBcon->affected_rows) {
    echo "success: updated";
} else {
    $DBcon->query("INSERT into mergeing(donator_1) VALUES ($lastID)");
    echo "success: inserted";
}

Depending on your actual use case, but you might want to also set the donator_2 value when you insert the new record.
Please note that if the $compare_value is determined by user input or some other source that you cannot predict, then you should use prepared statements, as otherwise the code is open to SQL injection.


text:
Q: App functionality to create read or delete phone contatcts I am asked to create functionality so that all app user contacts will transfer to phone contacts. It is business management system so they have many contact persons in the app (clients, workers suppliers etc.). To get contacts list, add or edit them is simple i found:
https://developer.android.com/guide/topics/providers/contacts-provider
It should help with getting contacts list, adding new or editing. But I need delete functionality. I couldn't find it anywhere. Anyone has suggestions how I could do that? Maybe there are some libraries that could help me with this functionality?

A: Assuming you have a contact-id, here's how to delete a contact:
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
ContentResolver cr = getContentResolver();
cr.delete(contactUri, null, null);


text:
Q: Since running out of battery on my Mac, fonts are missing and apps don't open properly This first happened when I ran out of battery on my Mac. When I charged it, it was acting very weirdly. My desktop background is black and when I login the background is black. When I open Hamachi it says "Failed to connect to engine", Stuff is missing such as desktop pictures and letters that I used to see are now a box with a question mark "[?]".

A: I would try resetting your SMC
System Management Controller (SMC), a circuit that deals with power management, temperature monitoring and fan control, status lights, keyboard backlights, and a few other components. If your SMC becomes confused, you could experience problems like excessive fan noise, slow performance even though Activity Monitor doesn't show the CPU being overtaxed, apps that take forever to launch, batteries that don't charge correctly, problems with sleep or wake, and so on.

Before you can reset your SMC, you must shut down your Mac. After that, the procedure varies depending on the type of Mac you have.

*

*Desktop Macs: Disconnect the power cord (either from the Mac or from
the AC outlet). Wait 15 seconds and plug it back in. Then wait
another 5 seconds and turn the Mac back on.

*Portable Macs with non-removable batteries: Make sure the Mac is
plugged in to AC power. On the built-in keyboard, press and hold the
Shift, Option, and Control keys on the left side and press the power
button. Release all the keys at once, and then turn the Mac on
normally.

*Portable Macs with removable batteries: Disconnect the AC power cord
and remove the battery. Press the power button, hold it for 5
seconds, and then let go. Put the battery back in, reconnect the
power cord, and turn the Mac on normally.

You can also try starting up in safe mode
Follow these steps to start up into safe mode.

*

*Start or restart your Mac.

*Immediately after you hear the startup sound, press and hold the
Shift key.

*Release the Shift key when you see the Apple logo appear on the
screen.

After the Apple logo appears, it might take longer than usual to reach the login screen or your desktop. This is because your Mac performs a directory check of your startup disk as part of safe mode.
To leave safe mode, restart your computer without pressing any keys during startup.
If you don't hear a startup chime after pressing the power key, see what to do if your Mac won't turn on.
If you're using FileVault
If your startup disk is encrypted with FileVault, you can still hold down the Shift key immediately after powering on your Mac to start up in safe mode. You might be prompted to log in twice as part of this process – first to unlock the startup disk, and a second time to log into the Finder. You can let go of the Shift key after you see the first login screen.
If an issue doesn't happen in safe mode
If an issue doesn't happen when your Mac is started in safe mode, try restarting again without pressing any keys at startup. If the issue appears to be resolved when you start up normally, it was possibly caused by a cache or a directory issue with your startup disk that safe mode fixed.
If you restart your Mac normally and an issue comes back when you reach your desktop, try disabling any login items that automatically open when you log in.
If your Mac restarts or shuts down in safe mode
If your Mac automatically restarts in safe mode, OS X might have found an issue that it's trying to fix.
Safe mode performs a directory check of your startup disk, similar to what happens when you choose to verify or repair a disk using Disk Utility. If OS X finds an issue, the directory on your startup disk is repaired and your Mac restarts.
If your Mac turns itself off when you start up in safe mode, check the power connection on your Mac to make sure it's plugged in securely at both your Mac and the power outlet. If you're using a MagSafe power adapter, make sure the LED on your power adapter is yellow or green. Then, try starting up in safe mode again.


text:
Q: Strip HTML from a directory containing .txt files with PERL I'm a complete n00b.  I've read many of the other posts on this site and I haven't been able to figure out a solution to this relatively simple problem.  Basically, I have a directory of text files that are marked up with HTML.  I want to strip the HTML from each of the files in this directory and then export each individual file to a new text files (preferably with the _out.txt extention).  Here is what I've tried so far:
use strict;
use warnings;
use File::Find;
use HTML::FormatText;

my $root_path=qq{C:\\Filings\\test}; #Declare your input path
# Recursively it process all the sub directories in $root_path
find(\&process_multiple_dir, $root_path);
sub process_multiple_dir
{
    if (-f && $File::Find::name =~ m{\.txt$}) # It process .txt format files only
    {
          undef $/; # Input Record separator
          # Files Handling process
          open (FIN, "<$File::Find::name") || die "Cannot Open the Input file";
          my $file=<FIN>; # Assign the file handler to scalar variable
          #print $file;

          my $string = HTML::FormatText->format_file($file,leftmargin => 0, rightmargin => 50);
          #print $string;
          close (FIN);
          # Change the file name for the output file creation purpose
          $File::Find::name=~ s{\.txt}{_Out.txt};

          # Print the $file contents to new file
          open (FOUT, ">$File::Find::name") || die "Cannot Create the Output file";
          print FOUT $string;
          close (FOUT);
      }
}

This code will output a file with the new file name (the _out.txt extention tagged on), but the newly created file has no text in it...
Thanks!

A: I don't use HTML::FormatText myself, but i think the correct syntax is:
my $string = HTML::FormatText->format_file($File::Find::name,leftmargin => 0, rightmargin => 50);

So no need to open the file and slurp it into $file.
(PS: use some indentation in your code; it makes it much more readable :) )


text:
Q: Error to get the access token in facebook using php sdk The code that I'm using :
$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.6',
  ]);

$helper = $fb->getCanvasHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  echo 'No OAuth data could be obtained from the signed request. A user has not authorized your app yet.';
  exit;
}

// Logged in
echo '
Signed Request
';
var_dump($helper->getSignedRequest());

echo '
Access Token
';
var_dump($accessToken->getValue());

Output:
This only shows that:  No OAuth data could be obtained from the signed request. A user has not authorized your app yet
I am using my page's app_id and app_secret.

A: The example you are using "(...) covers obtaining an access token and signed request FROM WITHIN THE CONTEXT OF AN APP CANVAS (...)".
https://developers.facebook.com/docs/php/howto/example_access_token_from_canvas
Context of an app canvas means that your app is embeded on Facebook (iframe).
https://stackoverflow.com/a/41669757/2911960
I assume you want to use the API on your website. Then you are looking for this:
https://developers.facebook.com/docs/php/howto/example_facebook_login


text:
Q: Difference between "run everyday" and "running everyday" after "One thing you can do is." "One thing you can do is running every day" and "One thing you can do is run everyday"
Any difference? Both correct or one is wrong?

A: I think it should be either "One thing you can do is go running every day" or "One thing you can do is run every day", because one can't "running", but you can run or go running. I hope this helps!


text:
Q: Get compilation errors in gradle I wanted to ask how to get Compilation errors after running compileJava Task in gradle.
The gradle script throws number of compilation errors because some of the classes refers  java classes which resides in other modules. Now I'm writing script whose job is to move classes to modules which it is referring to.
So what i wanted to do is get compilation errors in script in TaskExecutionlistener which has afterExecute method.
This afterexecute method provides state object which has failure but it doesnt give compilation errors.
How do I achieve this in gradle?
I have achieved this by writing compileJava output to log file and reading errors from log file but is there something which is better than my approach


text:
Q: Will my app be rejected if the icon has rounded corners? The guidelines specify that I "should provide an image that has 90° corners (it's important to avoid cropping the corners of your icon—iOS does that for you when it applies the corner-rounding mask)"
I see lots of apps that disobey this recommendation. How big is the risk that Apple will reject my app based on the app icon's rounded corners?

A: I've done this before and haven't been rejected for it. Just make sure that your icons corners align properly with the corners applied by iOS. (could look pretty strange if they didn't) As long as the fact that you're manually setting the corners isn't obvious to the user you should be fine.


text:
Q: What opt in rate can be achieved with Apple's iOS14 ATT prompt? As of iOS14 Apple require a permission prompt to use IDFA for advertising.
Can anyone who has implemented the App Tracking Transparency (ATT) framework already share rough percentages of users who tap Allow vs. Don't Allow?
Some articles have suggested around 20% but I wanted to find actual feedback from live iOS apps.
It can obviously be anonymous but any ballpark figures and industry/genre would be very much appreciated, so app developers can get an idea of what impact this will have on advertising revenue.
Thanks

A: "Developers forecast that as little as 10 to 13 per cent of Facebook users will opt-in to tracking if given the choice."
Source: https://www.the-sun.com/lifestyle/tech/2253930/facebook-notification-iphone-ad-tracking-apple-privacy-update/


text:
Q: sql slect подсчитать результатирующую выборку за определенный период подскажите пож-та как правильно можно подкорректировать уже выбранные данные в select выборки
есть уже результатирующие данные

задача такая что мне нужно из результатирующей выборки на текущий день посчитать по формуле за общее к-во за предыдущие 3 дней
SUM(HighCount) - SUM(LowCount) / SUM(AllCount) -- только сумма за предыдущиме 3 дня
в результате я должен получить
все даты и к ним расчет к примеру на
15.04 , (15+34+31) - (0+2+0) / (17+37+32) * 100 = 90.6 %
14,04 , (34+31+11) - (2+0+1) / (37+32+12) * 100 = 90.12 %
и т.д

буду очень признателен за помощь в данном расчете
mysql = 5.6

A: SELECT t1.data,
100*( t1.HighCount+t2.HighCount+t3.HighCount
     -t1.LowCount -t2.LowCount -t3.LowCount)
   /(t1.AllCount  +t2.AllCount  +t3.AllCount) percent
FROM table t1, table t2, table t3
WHERE t1.data = t2.data + INTERVAL 1 day
  AND t1.data = t3.data + INTERVAL 2 day

Само собой первые две даты выпадут, ибо у них нет двух "ранних" соседей. Также будет дыра, если отсутствует какая-то промежуточная дата. Ну и как бы предполагается, что поле даты уникально.


text:
Q: Update service MongoDB failed I'm trying to update my mongodb-2 service with
cf update-service $serviceInstance -p $newPlan
But I get :

FAILED
Server error, status code: 400, error code: 110004, message: The service does not support changing plans.

Does that mean that mongodb-2 plan can never be changed ? Or am I supposed to unbind applications before changing plan ?

A: cf update-service is not supported by any of Swisscom services. You need to do this manually at the moment. Swisscom is working on cf update-service feature. Please subscribe to the newsletter to know when the feature is in production.

*

*dump data mongodump of old service instance

*create new service instance with other plan

*restore mongorestore data to new service instance

*delete old service instance

Detailed guide with cf sshtunnel here.


text:
Q: Let $(A)_{4 \times 7}$ and $(B)_{7 \times 4}$ be two matrices then is the following claim true? Let $(A)_{4 \times 7}$ and $(B)_{7 \times 4}$ Be two matrices such that $AB =  I$
then I need to prove that $\lambda =0$ is an eigenvalue of $BA$ with arithmetic multiplicity $3$
Now, $\operatorname{Rank}(BA) \le  \operatorname{Rank} A  \le 4$
So,
Nullity Of $\text{(BA)} \ge 3$, Since we know that
$\gamma(0) \le \alpha(0)$ ,
($\gamma(0)$ is the geometric multiplicity and $\alpha(0)$ is arithmetic multiplicity)
Using this $\alpha(0) \ge 3$
After this I am stuck, I don't know how to continue after this.
Can anyone please help me here ?
Thank you.

A: Hint: For any $x$ in the image (AKA column space, AKA range) of $B$, $BAx = x$.  Use this fact to conclude that $\gamma(1) \geq 4$.


text:
Q: Substring matching for product search I have a product database (for soccer) which contains about 5k products. The Lucene index for product search currently contains Name, Category, Color and Numbers (ArtNo and EANs).
Relevant table example for the problem:

| Name                   | Color            |
--------------------------------------------
| Nike Training football | red black        |
| Nike Match football    | black white      |
--------------------------------------------

For the index I have created a custom Analyzer, so I can extend a StandardAnalyzer with additional behavior. The creation of the stream looks like this at the moment:
TokenStream result = new StandardTokenizer(Util.Version.LUCENE_29, reader );
result = new StandardFilter(result);
result = new LowerCaseFilter(result);
result = new StopFilter(true, result, stoptable );
return result;

The Analyzer is used both for the Indexer and the Searcher.
This is the current search logic:
BooleanQuery booleanQuery = new BooleanQuery(true);
string[] terms = query.Split(' ');

foreach (string s in terms)
{
  BooleanQuery subQuery = new BooleanQuery(true);

  var nameQuery = new FuzzyQuery(new Term("Name", s), 0.9f);
  nameQuery.SetBoost(6);
  subQuery.Add(nameQuery, BooleanClause.Occur.SHOULD);

  var colorQuery = new TermQuery(new Term("Color", s));
  subQuery.Add(colorQuery, BooleanClause.Occur.SHOULD);

  var categoryQuery = new FuzzyQuery(new Term("Category", s), 0.9f);
  categoryQuery.SetBoost(2);
  subQuery.Add(categoryQuery, BooleanClause.Occur.SHOULD);

  var numbersQuery = new TermQuery(new Term("Numbers", s));
  numbersQuery.SetBoost(10);
  subQuery.Add(numbersQuery, BooleanClause.Occur.SHOULD);

  booleanQuery.Add(subQuery, BooleanClause.Occur.MUST);
}

It works somehow already.
The problem:
A lot of products have names or categories with words a user just won't search.
In the example I have used "Nike Match football".
(Note: I have only translated it for use on SO, as most of the terms are German in the database)
If I search for "Nike football red" I do get the result. But if a search for "Nike ball red" I don't get it, although this is how users will search for it.
Afaik Lucene can't search for substrings (except for wildcards), as it only compares tokens - I do need something like this.
I have made Name and Category fuzzy and gave every column an appropriate boost according to it's relevance.
I have already read about Ngrams, but I really don't know how to use it correctly. The indexer works when I add the NGramTokenFilter to my custom analyzer. The problems here are, that I don't want it for every column (just name and category) and the results are completely weird when activating it.
If I add result = new NGramTokenFilter(result, 3, 4); to my analyzer and search for "nike ball" it just returns nothing.
Is Ngrams the solution here? What am I doing wrong?
And do you have any other suggestions on how to improve a product search?

A: I' not familiar with Ngrams but as i see there are two approaches in your case:
1. Work with wildcards in searches
use Prefix or Fuzzy Queries on the fields you like to search. Important is that you use TextField (
Javadoc) because this fields are going to be analyzed (StringField don't) and are used for fulltext searches. Based on this it should be possible to search with multiple not exact matching terms.
2. Work with different analyzers for different fields
You can analyze different fields with different analyzers with the PerFieldAnalyzerWrapper Javadoc). Define which field should be analyzed with which analyzer and you're good to go.
But be aware that you use the same analyzer for indexing and searching (it's lucene best practices)
Additional Informations
If you use Wildcards and Umlauts (German yaaaay) you have to know that Wildcard queries are not going to be analyzed like normal queries.
i faced the same problem and solved it with two kind of field:

*

*"normalized" (saved without Umlaut -> convert to basic latin
characters with analyzer)

*"non-normalized" (saved with Umlaut)

And while searching a BooleanQuery over this two fields.


text:
Q: How do I find the name of my development database? (PostgreSQL/Rails) I am tweaking a bash script I found somewhere for downloading the contents of your database on Heroku and the importing them into your development environment.
#!/bin/bash
heroku pgbackups:capture --expire --app testivate
file_path="db_$(date +%Y_%m_%d-%H_%M_%S).dump"
curl `heroku pgbackups:url --app testivate` > $file_path
pg_restore --verbose --clean --no-acl --no-owner -h localhost -U steven -d DATABASENAME $file_path

My question is, is there a command I can run to find the name of my development database?
In /config/database.yml I have:
development:
  adapter: postgresql
  database: db/testivate_development
  pool: 5
  username: steven
  password: <redacted>
  host: localhost

So as my name I've tried "steven", "db/testivate_development" and "testivate_development", but all give "database does not exist" errors.

A: Might I suggest you use the pg:transfer heroku client plugin. https://github.com/ddollar/heroku-pg-transfer
This lets you do:
heroku pg:transfer --from VIOLET

In your project folder you have a .env file which contains
DATABASE_URL=postgres://127.0.0.1/development_db_name

it wraps up the capture, restore for you. VIOLET is the name of the DB url on Heroku (From heroku config. The rest should be self explanatory.

A: https://devcenter.heroku.com/articles/heroku-postgresql
There's documentation on this page that shows how to find out this information.  Heroku doesn't use your db name from the config file, it creates its own name and password which is basically random strings.


text:
Q: how to play video downloaded from terminal I have downloaded a youtube video using the terminal but now I don't know how to play it.
I have checked the download folder but I didn't find anything.
So, how can I play this file?

A: The simplest approach is to just download the file to your current directory and play it from there. This can be done with the following command:
totem "$(youtube-dl youtube.com/watch?v=ES6OyV-RfHU |& grep -oP 'Destination:\s\K.*')"

The command above will both download the video, and extract the file name from the output and automatically launch the default video player to play the file.
Note that the player will not open until the file has finished downloading.


text:
Q: Why doesn't this django url run on Mac? I'd like to apply pose estimation Python code in url below to the Django view.
But it works well on Windows, but not on Mac.
127.0.0:8000/pose_feed doesn't work without any error messages.
I installed requirement.txt in venv, and Python version is 3.7 for both venv.
https://www.analyticsvidhya.com/blog/2021/05/pose-estimation-using-opencv/
urls.py
urlpatterns = [
    path('pose_feed', views.pose_feed, name='pose_feed'),
    ]

views.py
def index(request):
    return render(request, 'streamapp/home.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
def pose_feed(request):
    return StreamingHttpResponse(gen(PoseWebCam()),
                    content_type='multipart/x-mixed-replace; boundary=frame')

cameras.py
class PoseWebCam(object):
    def __init__(self):
        # self.vs = VideoStream(src=0).start()
        self.cap = cv2.VideoCapture(0)
        # self.mpPose = mp.solutions.pose
        self.mpPose = mp.solutions.mediapipe.python.solutions.pose
        self.pose = self.mpPose.Pose()
        self.mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils
        self.pTime = 0

    def __del__(self):
        cv2.destroyAllWindows()

    def get_frame(self):
        success, img = self.cap.read()
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        results = self.pose.process(imgRGB)

        if results.pose_landmarks:
            self.mpDraw.draw_landmarks(img, results.pose_landmarks, self.mpPose.POSE_CONNECTIONS)
            for id, lm in enumerate(results.pose_landmarks.landmark):
                h, w,c = img.shape

                cx, cy = int(lm.x*w), int(lm.y*h)
                cv2.circle(img, (cx, cy), 5, (255,0,0), cv2.FILLED)

        cTime = time.time()
        fps = 1/(cTime-self.pTime)
        self.pTime = cTime

        cv2.putText(img, str(int(fps)), (50,50), cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0), 3)
        # cv2.imshow("Image", img)
        # cv2.waitKey(1)
        frame_flip = cv2.flip(img,1)
        ret, jpeg = cv2.imencode('.jpg', frame_flip)
        return jpeg.tobytes()

home.html

    <title>Video Live Stream</title>

Video Live Stream


text:
Q: Combine data from 2 "strange" tables Having the following Schema
(ER of DataBase)
I am trying to create a query that

*

*will show the title(Movies.Title) along with each movie's genre(movie_Genres.movie_genre) for each movie that..

*that have been seen in (a) a  specific time period (lets say 2-3 days for ex. We can take those days from the Tickets.ticket_date) (b) by Male Customers(Customer.customer_sec) and (c) got rated more than 4 (rated_customerRation) by those customers.
I can get as close as the following query:
    SELECT
       `movie_title`, `movie_Genres`.`movie_genre`
    FROM
       `Movies`
    INNER JOIN
       `movie_Genres` ON `mg_movie` = `movie_ID`
    INNER JOIN
       `Rated` ON `rated_movie_ID` = `movie_ID`
    WHERE `rated_customerRatio` > 4 AND
    UNION
       (SELECT
            `customer_sex`, `rated_customerRatio`
                 FROM
                    `Customer`
                    /* INNER JOIN
                    `cinema`.`Rated` ON `Rated`.`rated_customer_tabID` = `Customer`.`customer_tabID`
                    */
                    INNER JOIN
                   `cinema`.`Tickets` ON `Tickets`.`ticket_customer_tabID`=`Customer`.`customer_tabID`
                WHERE
           `customer_sex` LIKE 'Male'
           /* AND rated_customerRatio > 4 */
            AND `Tickets`.`ticket_date` > '2016-02-16')
    GROUP BY `movie_title`;

Also I am thinking that I will have trouble, cause one movie can have more than one Genre, and I don't want double lines, for the same movie, in my outcome.
Any help will be taken into serious regards!

A: use a WHERE movie.ID IN (Select movie.id...) query to have unusual query relationships. i.e. if movie.id can be related to tickets
WHERE MovieID IN
(
SELECT
    MovieID
FROM
    MovieTable
LEFT JOIN TICKETS ON MovieID = TICKETS.movieID
LEFT JOIN CUSTOMER ON TICKETS.ID = CUSTOMER.ID
WHERE
CUSTOMER.customer_sex LIKE 'Male'
AND Tickets.ticket_date > '2016-02-16')
)

I dont know your DB schema but that should give you a rough idea on one way of sorting based on viewership of moves from tickets? 1 ticket should have 1 movie ID and 1 customer, so the relationship is pretty easy to figure out


text:
Q: discord.py 1.5.0: NameError: name 'client' is not defined I'm new to discord.py and following the tutorials on cogs. I followed everything the tutorial told me, but I got a name error when I run a command.
Here's the code:
./bot.py
import os
import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game('Under Development'))
    print('Bot Online')

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

client.run(os.environ['TOKEN'])

./cogs.commands.py
import discord
from discord.ext import commands

class Commands(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f'Network Delay: **{round(client.latency * 1000)} ms**')

def setup(client):
    client.add_cog(Commands(client))

when I type /ping in discord message box, I got this traceback

Traceback (most recent call last):
File "C:\Users\bryan\source\repos\discord_music_bot\env\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\bryan\source\repos\discord_music_bot\env\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\bryan\source\repos\discord_music_bot\env\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'client' is not defined

A: thanks to @Brian, i finally fixed the error. I write client.latency instead of self.client.latency
async def ping(self, ctx):
        await ctx.send(f'Network Delay: **{round(self.client.latency * 1000)} ms**')


text:
Q: web api throwing HttpResponseException and how to receive on wpf client from my wpf client I'm sending async request to the web api which should return HttpResponseException in this scenario, so I tried
HttpResponseMessage response = new HttpResponseMessage();
response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
   ...
} else {
    MessageBox.Show("Not active" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}

WebApi side
private void GetData()
{
   try {
      data = RavenSession.Query<myobj>().Take(1024).ToList();
   } catch (WebException) {
         throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.ServiceUnavailable, "Database is not online!"));
   }
}

again on wpf client I want to fetch HttpResponseException so I wrapped first block of code into try catch block
try{
    HttpResponseMessage response = new HttpResponseMessage();
    response = client.GetAsync(url).Result;
    if (response.IsSuccessStatusCode)
    {
       ...
    } else {
        MessageBox.Show("Not active" + response.StatusCode + " : Message - " + response.ReasonPhrase);
    }
}
catch(HttpResponseException e){
     MessageBox.Show(e.Message);
}
catch(Exception e){
     MessageBox.Show(e.Message);
}

but catch block is not hit at all. I can only access to response.IsSuccessStatusCode but this way I cannot return detailed message exception from webservice to the client (I want to display detailed message).

A: Read the error message from the Content property.
if (response.IsSuccessStatusCode)
{
   ...
} else {
    var errorMessage = response.Content.ReadAsStringAsync().Result;
}

And format the string as you want.
Reference: (search for "De-serialize the Response Content" in the article).
ASP.NET Web Api: Unwrapping HTTP Error Results and Model State Dictionaries Client-Side


text:
Q: How to derive Maclaurin series for ln(1+x) without calculus? How can we show $\ln(1+x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \dots$ for $-1 < x \leq 1$ without using calculus?

A: Without almost no calculus, perform the long division $$\frac{1}{1+x}=1-x+x^2-x^3+x^4+\cdots$$ and integrate both sides.

A: The power series for binomials $\displaystyle{(1+b)^x=\sum_{n=0}^{\infty}\frac{x(x-1)\dots(x-n+1)}{n!}b^n}$ and for exponent $\displaystyle{e^x=\sum_{n=0}^{\infty}\frac{x^n}{n!}}$ can be derived without Calculus.
Now, for a general $a=1+b$, you have $a^x=e^{(\ln a)x}=\sum_{n=0}^{\infty}\frac{(\ln a )^n (x)^n}{n!}$.
So $\ln a=\ln (1+b)$ is the coefficient of $x$ in the expantion of $a^x=(1+b)^x$, i.e. $$\displaystyle{\ln (1+b)=\sum_{n=1}^{\infty}(-1)^{n+1}\frac{b^n}{n}}.$$


text:
Q: Acumatica: Issue inserting POLine from another Graph I have a custom graph based on a custom DAC, and in a fieldUpdated event on this graph I am inserting a POLine.  The insert works fine and the line appears on the PO, but the PO Header Line Total does not update and no PlanID is assigned to the PO Line.  When a PO Line is manually entered on the PO Order Entry screen, the PlanID and Header Line Total value is assigned/updated by the graph.
My (summarized) code is as follows:
public SelectFrom<POOrder>.View POView;
public SelectFrom<POLine>
      .Where<POLine.pONbr.IsEqual<
     POOrder.orderNbr.FromCurrent>>
     .View POLineView;

protected virtual void _(Events.FieldUpdated<PSCHOrder, PSCHOrder.pOOrderNbr> e)
        {

            if (e.NewValue != null && !string.IsNullOrEmpty((string)e.NewValue))
            {

                var sorder = PXSelect<POOrder, Where<POOrder.orderNbr, Equal<Required<POOrder.orderNbr>>>>.Select(this, e.NewValue);
                POView.Current = sorder;

                var line = new POLine();
                line.OrderNbr = e.NewValue;
                line.OrderQty = 1;
                line.TranDesc = "my desc";
                line.InventoryID = id; //code to lookup id not shown
                //Assign Some Custom Fields
                PXCache<POLine>.GetExtension<POLineExt>(line).UsrDoorCD = "xxx";
                PXCache<POLine>.GetExtension<POLineExt>(line).UsrDoorPoNbr = "yyy"
                PXCache<POLine>.GetExtension<POLineExt>(line).UsrJobName = "abc";
                //Insert Line
                savedLine = this.POLineView.Insert(line);

            }
}

Is this an incorrect design or am I missing something?

A: Neither of these fields (lineTotal or PlanID) calculate automatically.  You will need to update.  Otherwise, the best way to do this would be to create a graph instance of POOrderEntry and insert the line through that graph's view.  It is not considered good practice to create a graph instance in an event handler however.
POOrderEntry graph = PXGraph.CreateInstance<POOrderEntry>();


text:
Q: Master volume missing on 16.04 upgrade I just upgraded from 14.04 to 16.04 and I am having issues with sound. First, every time I log in my headphones are on mute so I have to manually unmute them from alsamixer. Also my master volume control which used to be under the sound icon in the top right is no longer there and can only be changed via alsamixer. Also there is nothing under 'output' in sound settings. I don't know if this has any repercussions on anything, but i'm sure there used to be a few things under there...
Anyone know any fixes for these?
Thanks

A: To change master volume you must click on the sound icon in the top right. The reason why nothing appears in the output section could be a defect in the speakers, the motherboard, or Ubuntu itself.


text:
Q: Difference between Object() and Object{} C# will allow to create an object using either Object() or Object{}. What is the difference with Object() and Object{}
public item getitem()
{

return new item()

}

public item getitem()
{

return new item {}

}

A: This syntax:
new SomeType{}

is an object initializer expression which happens to set no properties. It calls the parameterless constructor implicitly. You can add property assignments within the braces:
new SomeType { Name = "Jon" }

This syntax:
new SomeType()

is just a call to the parameterless constructor, with no opportunities to set properties.
Note that you can explicitly call a constructor (paramterized or not) with an object initializer too:
// Explicit parameterless constructor call
new SomeType() { Name = "Jon" }

// Call to constructor with parameters
new SomeType("Jon") { Age = 36 }

See section 7.6.10.2 of the C# 4 specification for more details about object initializers.
I would highly recommend that if you aren't setting any properties, you just use new SomeType() for clarity. It's odd to use an object initializer without setting any properties.

A: item() calls default constructor, whereas item {} calls default constructor and allows to use (empty in this case) object initializer.

A: new item {} uses an object initializer.  In your example, there is no difference, but normally you would just call new item() if you don't wish to actually utilize the object initializer.


text:
Q: Multiple React Admin Lists with filters on one screen We've built an administration UI based on React Admin and in a couple of occasions we want to use multiple lists on a single screen for convenience. E.g. on a user detail view, we want to show the multiple addresses the user has on file, and the purchases the user has made. User, address and purchase are all "resources" in RA terminology.
It roughly looks like this:
/* file <...>/resources/users/UserShow.js */

import AddressList from '../addresses/AddressList';
import PurchaseList from '../purchases/PurchaseList';

const UserShow = ({ id, classes, translate, ...props }) => (
    <Fragment>
        <Show id={id} {...props}>
            ...render user details here...
        </Show>
        <AddressList {...props} basePath={'/addresses'} resource={'addresses'} filter={{ userId: id }} />
        <PurchaseList {...props} basePath={'/purchases'} resource={'purchases'} filter={{ userId: id }} />
    </Fragment>
);

Most of it seems to work nicely but the filters give us some headache. Everything around it seems to be built for exactly one filter at a time, without any means to customize (like e.g. specifying a property to use for the filter in the redux and react-router stores, instead of using a hardcoded one)
Has anyone ever made two filterable lists on the same screen work and has some more pointers?

A: I eventually came up with a workaround that I would like to share.
The problem is that RA propagates the filter/page/sort values into the query, and it maintains a "signature" of the filter object (a string representation of the corresponding JSON) to detect changes in the current filter in case of URL changes. With this approach, filter and pagination values remain active when the user navigates back and forth, and it's only updated if an actual field value changes.
That's a good thing if there's one list per screen, but in our case a filter update of one list leads to a back-propagation of the values into every other list on the screen.
First, I tried to keep all filters by modifying the query so that every filter uses their resource name as a key. Unfortunately, this caused a huge list of changes including copying entire RA components due to tinkering with RAs internals.
NB: RA already keeps filter values per resource in its Redux store, so it's beyond me why they're not using a similar syntax/approach for the query.
Another option is to cut off the propagation into the query entirely. The tradeoff is that you can't bookmark specific searches, and you need to reactivate filters when you navigate, but this seems to be a small and acceptable disadvantage.
Here's the relevant code in RA 3 which updates the query: https://github.com/marmelab/react-admin/blob/master/packages/ra-core/src/controller/useListParams.ts#L164
history.push({
    search: `?${stringify({
        ...newParams,
        filter: JSON.stringify(newParams.filter),
        displayedFilters: JSON.stringify(newParams.displayedFilters),
    })}`,
});

There's no way to directly modify this behavior, but we can supply our own history implementation to RA and override the search parameter. The corresponding monkey patch looks like that:
const history = createBrowserHistory({
    basename: process.env.PUBLIC_URL
});

const oldPush = history.push;
history.push = state => {
    oldPush({
        ...state,
        search: null,
    });
};

It could then be used like this:
const App = () => (
    <Admin
        history={history}
        ...
    >
        ...
    </Admin>
);


text:
Q: sort arrays of double in C if I have an array
double i[5] = {1.023, 1.22, 1.56, 2, 5, 3.331};

how do i sort the values so that they look like this:
double i[5] = {1.023, 1.22, 1.56, 2, 3.331, 5};

i've tried qsort() with no luck, after trying some examples, i came up with:
qsort(i, 5, sizeof(double), sort);

int sort(const void *x, const void *y)
{
return (*(double*)x - *(double*)y);
}

with => error: incompatible type for argument 1
not sorting the array.....

A: The first argument to qsort is the pointer to the start of the array to be sorted. Instead of
qsort(i[5], 5, sizeof(double), sort);

it should read
qsort(i, 5, sizeof(double), sort);

Some further observations:

*

*The length of i's initializer is incorrect (i has five elements, yet the initializer has six).

*Hard-coding the 5 into the qsort call is asking for trouble later on.

*The name "i" is most commonly used for loop counters and the like.

*Calling the comparison function sort is confusing.

*Your comparison function is wrong. Consider how it would compare the numbers 1.1 and 1.2. Also think about what would happen if the difference between the two values doesn't fit in an int.

I would rewrite your entire example like so:
double arr[] = {1.023, 1.22, 1.56, 2, 5, 3.331};

int cmp(const void *x, const void *y)
{
  double xx = *(double*)x, yy = *(double*)y;
  if (xx < yy) return -1;
  if (xx > yy) return  1;
  return 0;
}

int main() {
  qsort(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0]), cmp);
}

Note that the above comparison function still doesn't correctly handle NaNs; I leave it as an exercise for the reader to fix that.


text:
Q: R dplyr filtering data with values greater than +N and lesser than -N : abs() function? I am using the dplyr package in R for filtering my data of gene expressions. I have calculated fold changes and would like to filter the genes (rows) in which at least one sample (columns) has a value greater than +0.584963 OR less than -0.584963.An example data:
       X SAMPLE_1_FC SAMPLE_2_FC SAMPLE_3_FC SAMPLE_4_FC SAMPLE_5_FC
GENE_1      0.6780      0.4050      0.8870      0.3300      0.2230
GENE_2      0.2340     -0.6670      0.0020      0.1240      0.3560
GENE_3      0.0170      0.1560      0.1120      0.0080     -0.1230
GENE_4     -0.0944     -0.1372     -0.1800     -0.2228     -0.2656
GENE_5     -0.8080     -0.7800     -0.5560      0.0340      0.4450
GENE_6      0.2091      0.1106      0.0121     -0.0864     -0.1849
GENE_7      0.5980      0.7680      0.9970      0.4670     -0.7760

I am currently using the following script
det.cols<- colnames(my.data)[which(grepl("fc",tolower(colnames(my.data))))]
filt <- gsub(","," | ",toString(paste("`",det.cols,"`",">abs(0.584963)", sep = "")))
my.datasub<- my.data %>% filter_(filt)

but this returns only the genes greater than +0.584963 and not the negative ones. In the case of the example, what I want is a subsetted list with Genes 1, 2, 5 and 7. But instead it gives me only Genes 1 and 7. How can I change this?
I am expecting the answer to be in this format:
 X SAMPLE_1_FC SAMPLE_2_FC SAMPLE_3_FC SAMPLE_4_FC SAMPLE_5_FC
GENE_1      0.6780      0.4050      0.8870      0.3300      0.2230
GENE_2      0.2340     -0.6670      0.0020      0.1240      0.3560
GENE_5     -0.8080     -0.7800     -0.5560      0.0340      0.4450
GENE_7      0.5980      0.7680      0.9970      0.4670     -0.7760

Thanks.

A: Here's a solution that is flexible to the number of samples and data rows. It involves transforming the data into long format and then filters for the gene and specific sample. I tested it on 50k genes and 35 samples, and it ran in < 1 second.
library(tidyverse)

# set up sample data with 50000 rows
mydata <- data.frame(stringsAsFactors=FALSE,
                     X = c("GENE_1", "GENE_2", "GENE_3", "GENE_4", "GENE_5", "GENE_6", "GENE_7", 1:50000),
                     SAMPLE_1_FC = c(0.678, 0.234, 0.017, -0.0944, -0.808, 0.2091, 0.598, rnorm(50000, 0, 1)),
                     SAMPLE_2_FC = c(0.405, -0.667, 0.156, -0.1372, -0.78, 0.1106, 0.768, rnorm(50000, 0, 1)),
                     SAMPLE_3_FC = c(0.887, 0.002, 0.112, -0.18, -0.556, 0.0121, 0.997, rnorm(50000, 0, 1)),
                     SAMPLE_4_FC = c(0.33, 0.124, 0.008, -0.2228, 0.034, -0.0864, 0.467, rnorm(50000, 0, 1)),
                     SAMPLE_5_FC = c(0.223, 0.356, -0.123, -0.2656, 0.445, -0.1849, -0.776, rnorm(50000, 0, 1)))

# duplicate 30 more columns
mydata2 <- bind_cols(mydata, mydata[2:6], mydata[2:6], mydata[2:6], mydata[2:6], mydata[2:6], mydata[2:6])

(mydata3 <- mydata2 %>% gather(key = "sample_num", value = "fc", 2:length(mydata)) %>%
  filter(fc > 0.584963 | fc < -0.584963) %>%
  select(X) %>%
  arrange(desc(X)) %>%
  unique() %>%
  head())
#>         X
#> 1  GENE_7
#> 5  GENE_5
#> 7  GENE_2
#> 8  GENE_1
#> 10   9999
#> 14   9998

Created on 2019-03-01 by the reprex package (v0.2.1)

A: Long story short, you had the abs() in the wrong place in your code.
I fixed it here:
det.cols<- colnames(my.data)[which(grepl("fc",tolower(colnames(my.data))))]
filt <- gsub(","," | ",toString(paste("abs(`",det.cols,"`)",">0.584963", sep = "")))
my.datasub<- my.data %>% filter_(filt)

For further flexibility, @ha_pu provided a great filter_at solution building off my previous solution (before I identified the error in your code).

A: Using filter_at from dplyr might be an even more flexible approach...
# set up sample data with 50000 rows [as proposed by Arthur Yip above]
mydata <- tibble(X = c("GENE_1", "GENE_2", "GENE_3", "GENE_4", "GENE_5", "GENE_6", "GENE_7", 1:50000),
                     SAMPLE_1_FC = c(0.678, 0.234, 0.017, -0.0944, -0.808, 0.2091, 0.598, rnorm(50000, 0, 1)),
                     SAMPLE_2_FC = c(0.405, -0.667, 0.156, -0.1372, -0.78, 0.1106, 0.768, rnorm(50000, 0, 1)),
                     SAMPLE_3_FC = c(0.887, 0.002, 0.112, -0.18, -0.556, 0.0121, 0.997, rnorm(50000, 0, 1)),
                     SAMPLE_4_FC = c(0.33, 0.124, 0.008, -0.2228, 0.034, -0.0864, 0.467, rnorm(50000, 0, 1)),
                     SAMPLE_5_FC = c(0.223, 0.356, -0.123, -0.2656, 0.445, -0.1849, -0.776, rnorm(50000, 0, 1)))

# duplicate 30 more columns [as proposed by Arthur Yip above]
mydata2 <- bind_cols(mydata, mydata[2:6], mydata[2:6], mydata[2:6], mydata[2:6], mydata[2:6], mydata[2:6])

mydata2 %>%
  filter_at(vars(contains("fc")), .vars_predicate =  any_vars(abs(.) > 0.584963))

In the vars() you can define your list of variables to which you want to apply the filtering. Following .vars_predicate you can define the filter criterion (any_vars is equal to |, all_vars is equal to &).


text:
Q: Github API authentication with OAuth (and MFA) I am working with a Github Enterprise server. I am using Postman in an attempt to hit the API. No matter what I've tried, I get a "Sign in via LDAP" HTML page returned with a 200 status code. Not exactly what I was hoping for.
Important background:

*

*MFA is enabled

*OAuth token is a personal access token with all the scopes

I have attempted passing in the token as a URL parameter:
https://api.github.mycompany.com/repos/MyOrg/myrepo?access_token=MY_OAUTH_TOKEN

I have attempted passing in the token as an Authorization header 3 different ways:

*

*Authorization: MY_OAUTH_TOKEN

*Authorization: token MY_OAUTH_TOKEN

*Authorization: Bearer MY_OAUTH_TOKEN

From what I glean from the docs, my OAuth token should be sufficient, meaning that I don't need to send any sort of MFA code. Am I wrong? What do I need to do to get real results, rather than the LDAP login page?


text:
Q: How can I hide a search button and show a spinner while my AJAX partial loads in rails 3.1? I have a partial which returns results from the Amazon-ecs API (searches for books). It takes about 2.5 seconds to return values, so I want to add a spinner (and ideally hide the search button) but I've had a tough time getting it to work.
I already have javascript refreshing the partial with the results. I'd just like the button to give me a spinner (and hide the search button) until the partial finishes reloading.
Here is my main view (index.html.erb) which renders a partial of search results, each of which is added temporarily as an object in AmazonItems:
<%= form_tag amazon_items_path, :method => :get, :remote => true do %>

  <%= text_field_tag :query, params[:query] %>

    <%= image_tag 'ajax-loader.gif' %>

    <%= submit_tag "Search" %>

<% end %>

Searching Amazon

  <%= render 'amazon_returned' %>

My only JS code is in the update.js.erb file, which looks like:
$("#amazon_returned").html("<%=j render 'amazon_returned' %>");

I'm sure this is easy, but I can't get it work. Thanks!
EDIT: my partial "_amazon_returned.html.erb" looks like

<% for amazon_item in @amazon_items %>
   amazon_item.title
  ...ETC...
<% end %>

A: You can hook into the before event to do this:
$(function() {
  $("form").on("ajax:before", function() {
    $("#spinner, #search_button").toggle();
  });
});

Then, in your update.js.erb, add this again to toggle them back:
$("#spinner, #search_button").toggle();

A: Went with Dylan's answer, added the toggle to the update.js.erb and inserted the following into the view:

Very cool! Thanks again for the help.


text:
Q: How to rearrange a pandas table where data is split between multiple columns I have a pandas dataframe that contains table data taken from online, where there are pairs of data split into multiple columns like this every 2 columns:
| name   | price | name.1 | price.1| name.2 | price.2|
|--------|-------|--------|--------|--------|--------|
| orange | 2.2   | banana | 3.1    | grapes | 1.8    |
| apple  | 2.5   | mango  | 4.2    | kiwi   | 2.4    |

is there a way to rearrange the table to end up with this?:
| name   | price |
|--------|-------|
| orange | 2.2   |
| apple  | 2.5   |
| banana | 3.1   |
| mango  | 4.2   |
| grapes | 1.8   |
| kiwi   | 2.4   |

A: An alternative with np.reshape (as this DataFrame is so conveniently structured):
pd.DataFrame(
    df.values.reshape(-1, 2),
    columns=['name', 'price'])

Output:
     name price
0  orange   2.2
1  banana   3.1
2  grapes   1.8
3   apple   2.5
4   mango   4.2
5    kiwi   2.4

A: Try pd.wide_to_long:
new_df = pd.wide_to_long(df.rename(columns={'name': 'name.0',
                                            'price': 'price.0'})
                         .reset_index(),
                         stubnames=['name', 'price'],
                         sep='.',
                         i='index',
                         j='level_1').reset_index(drop=True)

new_df:
     name  price
0  orange    2.2
1   apple    2.5
2  banana    3.1
3   mango    4.2
4  grapes    1.8
5    kiwi    2.4

df constructor:
import pandas as pd

df = pd.DataFrame({
    'name': ['orange', 'apple'],
    'price': [2.2, 2.5],
    'name.1': ['banana', 'mango'],
    'price.1': [3.1, 4.2],
    'name.2': ['grapes', 'kiwi'],
    'price.2': [1.8, 2.4]
})

A: You could also try the pivot_longer function from pyjanitor:
# pip install pyjanitor
import janitor
import pandas as pd
df.pivot_longer(names_to = ('name', 'price'),
                names_pattern = ('name', 'price')
                )

     name  price
0  orange    2.2
1   apple    2.5
2  banana    3.1
3   mango    4.2
4  grapes    1.8
5    kiwi    2.4

Your columns have a pattern (some start with name, others with price), so you pass that pattern to names_pattern, and pass the new column names to names_to.


text:
Q: Why is setx path not working? Can someone explain this result?
After setting path, it did not change. This was run in an Administrator command-line:
C:\Windows\system32>setx path "C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin"

SUCCESS: Specified value was saved.

C:\Windows\system32>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin;D:\Program Files (x86)\metapad36;D:\Program Files (x86)\metapad36" /M

I've read that %PATH% = PATH variable for machine + PATH variable for user. Am I seeing the machine path + Admin's path?
Have looked at other articles on the topic, but still confused.
Should I clear the user paths, so there's no duplication?
update: Re the tip that "variables created or modified by this tool will be available in future command windows" i open a non-admin window and enter:
>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin;;D:\Program Files (x86)\metapad36;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin

The path is repeated twice. Ok, then at same prompt I setx the path without the repeat, and without /M:
>setx path "C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin"

SUCCESS: Specified value was saved.

Apparently saved in current user environment.
Then i open a new non-admin command window, and:
>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin;;D:\Program Files (x86)\metapad36;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin`

It has not changed. Why?

A: In Windows, each process gets a copy of the environment which is essentially a snapshot of the global environment at the time the process was started. Changes to the global environment while the process is running are not propagated back to the process' own copy of the environment.
To answer the actual question, setx does modify the user environment (or the system one if run with /M), but the changes are not immediately visible in the process that executed setx, in this case cmd.exe. If you open a new command prompt after running setx, you'll see the changes in that instance of cmd.exe.
This is explicitly noted in the setx /? help:

On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.

To effect the same changes in both the global environment, and the one of the current process, you need to run both setx andset.

A: Just an FYI for anyone finding this old post...
SETX (and most other programmatic methods via PowerShell, .Net, C#, etc.) only take immediate affect for new processes run by the user who runs SETX.  If SETX is run by a different user or by the System account (as most corp deployment products would), a reboot would still be required for any other user to receive the update.  Even closing Explorer.exe and re-running under the affected user won't refresh.
Microsoft is doing some programmatic magic to the shell environment(s) when you modify environment variables via the standard Windows GUI.

A: At first, open your cmd as administrator user then runs setx command


text:
Q: How do I do a correct micro-benchmark in Julia? The Julia 1.0.0 documentation provides general tips.
It also suggests that instead of using the @time macro:

For more serious benchmarking, consider the BenchmarkTools.jl package which among other things evaluates the function multiple times in order to reduce noise.

How do they compare in use and is it worth the trouble to use something not in "base" Julia?

A: From a statistical point of view, @benchmark is much better than @time
TL;DR The BenchmarkTools @benchmark macro is a great micro-benchmark tool.
Use the @time macro with caution and don't take the first run seriously.
This simple example illustrates use and differences:
julia> # Fresh Julia 1.0.0 REPL

julia> # Add BenchmarkTools package using ] key package manager

(v1.0) pkg> add BenchmarkTools
julia> # Press backspace key to get back to Julia REPL

# Load BenchmarkTools package into current REPL
julia> using BenchmarkTools

julia> # Definine a function with a known elapsed time
julia> f(n) = sleep(n)  # n is in seconds
f (generic function with 1 method)

# Expect just over 500 ms for elapsed time
julia> @benchmark f(0.5)
BenchmarkTools.Trial:
  memory estimate:  192 bytes
  allocs estimate:  5
  --------------
  minimum time:     501.825 ms (0.00% GC)
  median time:      507.386 ms (0.00% GC)
  mean time:        508.069 ms (0.00% GC)
  maximum time:     514.496 ms (0.00% GC)
  --------------
  samples:          10
  evals/sample:     1

julia> # Try second run to compare consistency
julia> # Note the very close consistency in ms for both median and mean times

julia> @benchmark f(0.5)
BenchmarkTools.Trial:
  memory estimate:  192 bytes
  allocs estimate:  5
  --------------
  minimum time:     502.603 ms (0.00% GC)
  median time:      508.716 ms (0.00% GC)
  mean time:        508.619 ms (0.00% GC)
  maximum time:     515.602 ms (0.00% GC)
  --------------
  samples:          10
  evals/sample:     1

julia> # Define the same function with new name for @time macro tests
julia> g(n) = sleep(n)
g (generic function with 1 method)

# First run suffers from compilation time, so 518 ms
julia> @time sleep(0.5)
  0.517897 seconds (83 allocations: 5.813 KiB)

# Second run drops to 502 ms, 16 ms drop
julia> @time sleep(0.5)
  0.502038 seconds (9 allocations: 352 bytes)

# Third run similar to second
julia> @time sleep(0.5)
  0.503606 seconds (9 allocations: 352 bytes)

# Fourth run increases over second by about 13 ms
julia> @time sleep(0.5)
  0.514629 seconds (9 allocations: 352 bytes)

This simple example illustrates how easy it is to use the @benchmark macro and the caution with which the @time macro results should be taken.
Yes, it is worth the trouble to use the @benchmark macro.


text:
Q: MariaDB connection refuse docker compose I'm gonna try to explain what my recently found headache is. First of all I'm using Gitlab CI so docker and docker in docker is involved.
The structure of the CI is basically this and all running dind:

*

*Stand UP 3 services for 3 different databases using docker-compose up -d

*Once the services are up, run a test service with
docker-compose run test from another docker compose file in a different directory and all the services there are using the same network

Previously this entire pipeline was working using docker in docker but until recently i'm talking in the last 3 weeks it broke, I tried to do the same locally and the databases connect just fine. But when running inside the CI I get:
ERROR 2003 (HY000): Can't connect to MySQL server on 'dbtest' (111 "Connection refused")

I'm using the latest mariadb docker, I've tried to override the bind-address to listen to all interfaces with no luck, and I still get connection refused, I've tried the alias and the container name but I still get the same error.
This is the compose file for the database services
version: '2'

volumes:
    logs:
        driver: local

services:

    dbtest:
        image: mariadb:latest
        container_name: core-dbtest
        volumes:
        - ./db/schema/:/docker-entrypoint-initdb.d
        environment:
            MYSQL_ROOT_PASSWORD: <some_pass>
            MYSQL_DATABASE: <some_db>
            MYSQL_USER: <some_user>
            MYSQL_PASSWORD: <some_password>
        networks:
            - test

networks:
    test:

Questions:

*

*Could it be that the server is still listening on localhost regardless of my changes? or what other things can I check?


text: Q: Sharepoint can not find back to the document library when saving file When I click "New document" button on my document library and then click on save to save back the file to the library it has chosen my document folder on my computer instead of the document library on the SharePoint Site. What is the problem and how can I fix it? thanks for your advice. The Document library uses my content type which is inherited from Document Content Type.


text:
Q: unit test to verify that a repository loads an entity from the database correctly I have a simple standard repository that loads a composite entity from the database. It injects all dependencies it need to read the complete entity tree from a database through IDbConnection (wich gives the repository access to IDbCommand, IDbTransaction, IDataReader) that I could mock.
public class SomeCompositionRootEntityRepository :
    IRepository<SomeCompositionRoot>
{
    public RecipeRepository(IDbConnection connection) { ... }
    public void Add(SomeCompositionRootEntity item) { ... }
    public bool Remove(SomeCompositionRootEntity item) { ... }
    public void Update(SomeCompositionRootEntity item) { ... }
    public SomeCompositionRootEntity GetById(object id) { ... }
    public bool Contains(object id) { ... }
}

The question is how would I write unit test for this in a good way? If I want to test that the reposity has read the whole tree of objects and it has read it correcty, I would need to write a hughe mock that records and verifies the read of each and every property of each and every object in the tree. Is this really the way to go?
Update:
I think I need to refactor my repository to break the repository functionality and unit test into smaller units. How could this be done?
I am sure I do not want to write unit test that involve reading and writing from and to an actual database.

A: The question is: What functionality do you want to test?

*

*Do you want to test that your repository actually loads something? In this case I would write a few (!) tests that go through the database.

*Or do you want to test the functionality inside the repository methods? In this case your mock approach would be appropriate.

*Or do you want to make sure that the (trivial) methods of your repository aren't broken? In this case mocks and one test per method might be sufficient.

Just ask yourself what the tests shall ensure and design them along this target!

A: I think I understand your question so correct me if I'm wrong...
This is a where you cross the line from unit to integration.  The test makes sense (I've written these myself), but you're not really testing your repository, rather you're testing that your entity (SomeCompositionRoot) maps correctly.  It isn't inserting/updating, but does involve a read to the database.
Depending on what ORM you use, you can do this a million different ways and typically its fairly easy.
::EDIT::
like this for linq for example ...
    [TestMethod]
    public void ShouldMapBlahBlahCorrectly()
    {
        CheckBasicMapping<BlahBlah>();
    }

    private T CheckBasicMapping<T>() where T : class
    {
        var target = _testContext.GetTable<T>().FirstOrDefault();
        target.ShouldNotBeNull();
        return target;
    }


text:
Q: Tell rsync to compress in parallel Is there a way to tell rsync to do compression in parallel, eg. with pbzip2?
I am trying to speed up our nightly backup.
Our Rsync with compression currently has a transfer rate of
sent 1705628134 bytes  received 19432 bytes  3076010.04 bytes/sec
total size is 8064769536  speedup is 4.73

while one CPU core is on 99% and the network allows 55-60 Mbit/s which is apparently more than the actual 8*3 Mbit/s.
We have Oracle Linux 6.5 with
rsync.x86_64                           3.0.6-9.el6_4.1


text:
Q: Can the effects of [[likely]] and [[unlikely]] be transitive/inferred? C++20 introduced the attributes [[likely]] and [[unlikely]] for signalling statements that may be either likely or unlikely executed to help with optimizations. Historically, such attributes were compiler-specific, and were hidden behind __likely and __unlikely macro function to help optimize branching statements; however C++20 takes this a step further by allowing them on any statements.
In theory, this should allow for [[likely]] and [[unlikely]] inference, based on context and visibility -- such as:
// Just an opaque function to call so we see it in the generated assembly
void something_expensive();

// Something we know to always be unlikely
[[gnu::always_inline]]
inline void unlikely_code_path() {
    [[unlikely]] something_expensive();
}

void test_unlikely(bool x) {
    if (x) /* [[unlikely]] inferred? */ { unlikely_code_path(); }
}

I use an inlined/visible function-call in this example since I can see this being useful for error-managing functions like assert, which are never meant to be tripped in practice and thus we don't want paths leading to these cases to be optimized for. However, I'm not seeing any compiler actually take advantage of this.
Live Example
Both GCC and Clang are generating identical assembly outputs, neither of which take advantage of the [[unlikely]] (or [[likely]]) knowledge:
test_unlikely(bool):
        test    dil, dil
        je      .L4
        jmp     something_expensive()
.L4:
        ret

My expectation is that test_unlikely would be aware of the [[unlikely]] branch and generate something similar to what would be generated if this were if (b) [[unlikely]] { ...}, which is:
test_unlikely(bool):
        test    dil, dil
        jne     .L6
        ret
.L6:
        jmp     something_expensive()

Is this a missed opportunity for compilers to label the "hot" and likely paths? Or is there something I am missing about the C++ language that may actually prevent such optimizations from being realistic using attributes alone in practice?
(Note: I know that attributes in C++ are effectively non-binding contracts, and thus the compiler does not need to honor them; but the compilers here clearly are honoring some cases which makes me think this is just a missed optimization)


text:
Q: Azure Cognitive Search - MergeOrUpdate to a only retrievable field What happens when "updating" a document, but only changing a retrievable field. Will the document be reindexed?
I'm trying to mesure the "cost" of updating a retrievable field to a lot of documents to decide if I should put this field on the index or getting from SQL Server after consulting the index.
Thanks in advance

A: MergeOrUpdate behavior is the same as Merge, if the document (document key specifically) already exists. It doesn't matter which are the properties of the field (retrievable, filterable, etc.). In other words, the whole document is not re-indexed, but the specified field values in the call are merged. For more information on the REST API behavior: Add, Update or Delete Documents (Azure Cognitive Search REST API).


text:
Q: Iterate over nested loops I am trying to iterate over level3 variable in Ansible. I've prepared a playbook like this:
---
- hosts: localhost
  gather_facts: no
  connection: local

  vars:
    level1:
      - abc
      - def

    level2:
      - { name: "app1", level3: ["aaaa","bbbb"]}
      - { name: "app2", level3: ["eeeee"]}

  tasks:

    - name: test
      debug: msg="{{ item.0 }} {{ item.1.name }} {{ item.2 }}"
      with_nested:
        - "{{ level1 }}"
        - "{{ level2 }}"
        - "{{ level2.level3 }}"

But I get error:
PLAY [localhost] ***************************************************************************************************************************************************

TASK [test] ********************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "'list object' has no attribute 'level3'"}

PLAY RECAP *********************************************************************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

What is bad with my config? I want to have on output each element.

A: level2.level3 does not exist. level2 is a list so e.g. level2.0.level3 exists.
I'm not entirely sure from your question but I think what you are looking for is:
    - debug:
        msg: "{{ item.0 }} {{ item.1.0.name }} {{ item.1.1 }}"
      loop: "{{ level1 | product(level2 | subelements('level3')) }}"

You can keep the older with_ syntax using the nested lookup if you wish. The produced result is a bit different so you have to adapt to the datastructure:
    - debug:
        msg: "{{ item.0 }} {{ item.1.name }} {{ item.2 }}"
      with_nested:
        - "{{ level1 }}"
        - "{{ level2 | subelements('level3') }}"

which can eventually be written back to a loop: syntax as follow:
    - debug:
        msg: "{{ item.0 }} {{ item.1.name }} {{ item.2 }}"
      loop: "{{ q('nested', level1, level2 | subelements('level3')) }}"

All examples give the same result (delta the spitted item for each iteration, example output with first proposition)
PLAY [localhost] *****************************************************************************************************************************************

TASK [debug] *********************************************************************************************************************************************
ok: [localhost] => (item=['abc', [{'name': 'app1', 'level3': ['aaaa', 'bbbb']}, 'aaaa']]) => {
    "msg": "abc app1 aaaa"
}
ok: [localhost] => (item=['abc', [{'name': 'app1', 'level3': ['aaaa', 'bbbb']}, 'bbbb']]) => {
    "msg": "abc app1 bbbb"
}
ok: [localhost] => (item=['abc', [{'name': 'app2', 'level3': ['eeeee']}, 'eeeee']]) => {
    "msg": "abc app2 eeeee"
}
ok: [localhost] => (item=['def', [{'name': 'app1', 'level3': ['aaaa', 'bbbb']}, 'aaaa']]) => {
    "msg": "def app1 aaaa"
}
ok: [localhost] => (item=['def', [{'name': 'app1', 'level3': ['aaaa', 'bbbb']}, 'bbbb']]) => {
    "msg": "def app1 bbbb"
}
ok: [localhost] => (item=['def', [{'name': 'app2', 'level3': ['eeeee']}, 'eeeee']]) => {
    "msg": "def app2 eeeee"
}

PLAY RECAP ***********************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


text:
Q: Venn diagram drawing! What would a Venn Diagram look like for $\bar{C}-D$?
I have drawn an outline of a rectangle for Universal Set, a circle for $C$ and a circle for $D$, the circles intersect.

A: Normally I like to give hints for such questions, but I am not sure I can without simply giving away the answer, so here it is.
Try to understand the answer by drawing two separate pictures: one for $\bar{C}$ and one for $D$. See if you can "combine" the two pictures to arrive at the answer.

A: In this particular case, you can imagine that $$\bar C \text{ is "everything but $C$}",$$and $$\bar C - D \text{ is "[everything but C] but D"},$$ and that is clearly "everything except [$C$ or $D$]".
That is, $$\bar C - D = \Omega - (C \cup D),$$ where $\Omega$ is the "Universal Set".

A: You can also think of it as $$\overline{C}-D=\overline{C\cup D}$$

A: If you want to use Maxima CAS, I have written a function vennplot for this,
For how it has been written, check this


text:
Q: The file 'xxxxx.asmx' has not been pre-compiled, and cannot be requested I have a asp.net 4.0 website which has been published using fixed naming and single page assemblies.
All of a sudden we are getting the file 'xxxxx.asmx' has not been pre-compiled, and cannot be requested on the webservice page, and only the webservice page.
Everything else works fine, I can see the file in the bin directory and it has the same name as a found in a previous (older) working bin folder.
Also works fine on Windows 7 dev server but not production (IIS 7 Server 2008). I have rebuilt and redeployed the application with no success, any suggestions?
Thanks

A: Sorted it, turns out just removed the Microsoft.mshtml reference.


text:
Q: Como obtener la url de los video de Fembed Estoy intentando obtener el link directo a los videos de fembed:
aqui les dejo un link de prueba:
https://www.fembed.com/v/g5q88c-8r5nrw-7
Lo que necesito conseguir es un link parecido a este
https://fvs.io/redirector?token=T0JENEhYL3kzNDN2TmRQOFlTaDcyMnZITmpCSmdMYTRCN2IrL2ZDNFQrN2xIVllxR2xlOUZFOHpnRXk1SzZyWFJTKzcvWmxvdE1ob2l1OVpsQkNFQ0xyOWdnMS8rSzNkYTcxalNUbk9Ga05rYmh0Y09IZzgxWWltTDZ1Z1VvQlNySm0xUmdCQTdqaERSY3o4OGNUV2l5bkJHZGdGUVhvZzpvT3ZRbFA4VXRkV3ZQNU1SVEFMRmtnPT0SLyK
para poder usarlo en una aplicacion de movil.
He probado con este link,
https://fapi.deta.dev/g5q88c-8r5nrw-7

pero este me genera los urls, pero me dan Error 404 o 403.
EDIT
Aquí esta el problema que estoy teniendo ahora

A: Si, te fijas cuando lo hace en un Server Local el toma la IP en formato Ipv4 porque toma el IP de tu server LOCAL, mientras que si lo haces en un SERVER remoto este usa Ipv6 del Server Remoto.


text:
Q: Loading javascript files automatically with sequential callbacks I have the following javascript list, each item in this list has a script file url and a callback function, what i want to do is to iterate through this list, load each script, then execute the callback function, and NOT moving to next item unless the current callback is done executing..

var data = {
    scripts: [
        {
            file    : 'some-script.js',
            callback: function() {
                // do some code here
            },
        },
        {
            file    : 'another-script.js',
            callback: function() {
                // do some code here
            },
        },
        ...
    ]
};

how can I do this automatically, if Possible ?

A: (I'm assuming that you are using JSONP to load your external scripts) The problem that you will face is that these scripts will not load all at the same time.
Below is some code that will call your callback function as soon as the associated script is loaded.
    function include_js(url, callback) {  // http://www.nczonline.net
        var script = document.createElement("script");
        script.type = "text/javascript";

        if (script.readyState) {  //IE
            script.onreadystatechange = function(){
                if (script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            script.onload = function(){
                callback();
            };
        }
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

//Edit

    for (var i = 0; i < data.scripts.length; i++) {
         include_js(data.scripts[i].file, data.scripts[i].callback);
    }

A: It's possible if there's a symbol you can test for in each script, or if each script can execute a function call when it's done loading.
Loading the script is easy, as I'm sure you know:
var script = document.createElement('script');
script.src = /* ... the source path ... */;
document.body.appendChild(script);

(You'll see people appending to head instead; doesn't matter, and body is easy to find.)
But the hard part is knowing when it has been downloaded and executed. The only real ways of doing that are by polling to see if a new global symbol defined by the script has been defined, or by having the script actively call you back when it's done loading (a'la JSONP).
Either way, once you've detected the symbol or gotten the callback, you then move on to loading the next script.
Here's a quick-and-dirty sketch of doing it on the basis of finding a global symbol (a property on the window object):
// The scripts to load
var scriptList = {
    scripts: [
        {
            file    : 'some-script.js',
            callback: function() {
                // do some code here
            },
            symbol  : "someSymbol",
            timeout : 30000 // We know this one is slow, give it 30 seconds
        },
        {
            file    : 'another-script.js',
            callback: function() {
                // do some code here
            },
            symbol  : "anotherSymbol"
        },
        // ...
    ]
};

// Triggering the load
loadScripts(scriptList);

// Library routines to do the load
function loadScripts(list)
{
    var index, timeout;

    // Start with the first one (loadNextScript starts with an increment)
    index = -1;
    loadNextScript();

    // This function loads the next script in the list; if there are no
    // more, it simply returns
    function loadNextScript()
    {
        var script;

        // Are there more?
        ++index;
        if (index < list.length)
        {
            // Yes, append a `script` element
            script = document.createElement('script');
            script.src = list.file;
            document.body.appendChild(script);

            // Determine when to time out
            timeout = new Date() + (list[index].timeout || 20000); // Time out in Xms, default 20 seconds

            // Start polling
            setTimeout(pollForScript, 0); // Async, but almost immediately (4-10ms on most browsers)
        }
    }

    // This function polls to see if the current script has loaded yet by
    // checking for a global symbol it defines.
    function pollForScript()
    {
        var result;

        // Has it been too long?
        if (new Date() > timeout)
        {
            // Yes
            result = "timeout";
        }
        else
        {
            // Has the symbol been defined?
            if (typeof window[list[index].symbol] !== "undefined")
            {
                // Yes
                result = "loaded";
            }
            else
            {
                // Nope, keep waiting
                setTimeout(pollForScript, 250); // Check every quarter-second
            }
        }

        // Did we get a result?
        if (result)
        {
            // Yes, do the callback telling it of the result
            try {
                list[index].callback(result);
            }
            catch (e) {
            }

            // Load the next script
            loadNextScript();
        }
    }
}

A: Let the callback call your loadTheNextScriptInList or whatever function. You can do this automatically by adding an anonymous function to the onLoad event. This anonymous function should first call the callback set in the list, and then call your loadTheNextScriptInList function.

A: this is just something quick I wrote up and HAVENT TESTED, but it should do what you are after in a recursive fashion. Hope this helps:
var data = {
    scripts: [
        {
            file    : 'some-script.js',
            callback: function() {
                // do some code here
            },
        },
        {
            file    : 'another-script.js',
            callback: function() {
                // do some code here
            },
        },
        ...
    ]
};

$(document).ready(function() {

    if(data.scripts.length > 0) {
        scriptLoader(0);
    }

});

function scriptLoader(i) {

    var currScript = data.scripts[i];

    $.getScript(currScript.file, function() {

      // execute your callback
      currScript.callback();

      // load next script
      if(i < data.scripts.length) {
        scriptLoader(i++);
      }

    });

}

Oh and btw this uses the JQuery javascript framework, just FYI.


text:
Q: Delete rows from a simplified CSV where some columns matching specific pattern I have the following simplified CSV file (no separators or newlines embedded in fields):
ID,PDBID,FirstResidue,FirstChain,SecondResidue,SecondChain,ThirdResidue,ThirdChain,FourthResidue,FourthChain,Pattern
RZ_AUTO_505,1hmh,A22L,C,A22L,A,G21L,A,A23L,A,AA/GA Naked ribose
RZ_AUTO_506,1hmh,A22L,C,A22L,A,G114,A,A23L,A,AA/GA Naked ribose
RZ_AUTO_507,1hmh,A130,E,A90,A,G80,A,A130,A,AA/GA Naked ribose
RZ_AUTO_508,1hmh,A140,E,A90,E,G120,A,A90,A,AA/GA Naked ribose
RZ_AUTO_509,1hmh,G102,A,C103,A,G102,E,A90,E,GC/GA Single ribose
RZ_AUTO_510,1hmh,G102,A,C103,A,G120,E,A90,E,GC/GA Single ribose
RZ_AUTO_511,1hmh,G113,C,C112,C,G21L,A,A23L,A,GC/GA Single ribose
RZ_AUTO_512,1hmh,G113,C,C112,C,G114,A,A23L,A,GC/GA Single ribose
RZ_AUTO_513,1hnw,C1496,A,G1497,A,A1518,A,A1519,A,CG/AA Canonical ribose
RZ_AUTO_514,1hnw,C1496,A,G1497,A,A1519,A,A1518,A,CG/AA Canonical ribose
RZ_AUTO_515,1hnw,C221,A,U222,A,A195,A,A196,A,CU/AA Canonical ribose
RZ_AUTO_516,1hnw,C221,A,U222,A,A196,A,A195,A,CU/AA Canonical ribose

I need to remove the CSV rows if the value of FirstResidue or SecondResidue or ThirdResidue or FourthResidue doesn't end with an integer.
The output should look something like below.
RZ_AUTO_507,1hmh,A130,E,A90,A,G80,A,A130,A,AA/GA Naked ribose
RZ_AUTO_508,1hmh,A140,E,A90,E,G120,A,A90,A,AA/GA Naked ribose
RZ_AUTO_509,1hmh,G102,A,C103,A,G102,E,A90,E,GC/GA Single ribose
RZ_AUTO_510,1hmh,G102,A,C103,A,G120,E,A90,E,GC/GA Single ribose
RZ_AUTO_513,1hnw,C1496,A,G1497,A,A1518,A,A1519,A,CG/AA Canonical ribose
RZ_AUTO_514,1hnw,C1496,A,G1497,A,A1519,A,A1518,A,CG/AA Canonical ribose
RZ_AUTO_515,1hnw,C221,A,U222,A,A195,A,A196,A,CU/AA Canonical ribose
RZ_AUTO_516,1hnw,C221,A,U222,A,A196,A,A195,A,CU/AA Canonical ribose

So I'm just wondering how to achieve this using awk. I'm using Mac OSX.

A: You want to print only lines for which the third, fifth, seventh, and ninth fields end with a digit.  In that case:
$ awk -F, '$3 ~/[[:digit:]]$/ && $5 ~/[[:digit:]]$/ && $7 ~/[[:digit:]]$/ && $9 ~ /[[:digit:]]$/' file
RZ_AUTO_507,1hmh,A130,E,A90,A,G80,A,A130,A,AA/GA Naked ribose
RZ_AUTO_508,1hmh,A140,E,A90,E,G120,A,A90,A,AA/GA Naked ribose
RZ_AUTO_509,1hmh,G102,A,C103,A,G102,E,A90,E,GC/GA Single ribose
RZ_AUTO_510,1hmh,G102,A,C103,A,G120,E,A90,E,GC/GA Single ribose
RZ_AUTO_513,1hnw,C1496,A,G1497,A,A1518,A,A1519,A,CG/AA Canonical ribose
RZ_AUTO_514,1hnw,C1496,A,G1497,A,A1519,A,A1518,A,CG/AA Canonical ribose
RZ_AUTO_515,1hnw,C221,A,U222,A,A195,A,A196,A,CU/AA Canonical ribose
RZ_AUTO_516,1hnw,C221,A,U222,A,A196,A,A195,A,CU/AA Canonical ribose

How it works
Typical awk commands consist of a condition and an action.  Here we have a condition that consists of four parts.  Because the action that we want is the default action (print the line), we don't actually need to specify it.  Each part of the condition looks like:
$3 ~/[[:digit:]]$/

This is true if field 3 ends in a digit.  This is "and"-ed with three others, one each for fields 5, 7, and 9.  If all are true, then the line is printed.

A: You can also try the following Python2 solution:
#!/usr/bin/env python2
import csv, re
with open('file.txt', 'rb') as f:
    for line in csv.reader(f):
        if re.search(r'[0-9]$', line[2]) and re.search(r'[0-9]$', line[4]) and re.search(r'[0-9]$', line[6]) and re.search(r'[0-9]$', line[8]):
            print ' '.join(line)

A: Using Miller (mlr) and testing the four named fields using a regular expression:
$ mlr --csvlite filter '$FirstResidue =~ "[0-9]$" && $SecondResidue =~ "[0-9]$" && $ThirdResidue =~ "[0-9]$" && $FourthResidue =~ "[0-9]$"' file
ID,PDBID,FirstResidue,FirstChain,SecondResidue,SecondChain,ThirdResidue,ThirdChain,FourthResidue,FourthChain,Pattern
RZ_AUTO_507,1hmh,A130,E,A90,A,G80,A,A130,A,AA/GA Naked ribose
RZ_AUTO_508,1hmh,A140,E,A90,E,G120,A,A90,A,AA/GA Naked ribose
RZ_AUTO_509,1hmh,G102,A,C103,A,G102,E,A90,E,GC/GA Single ribose
RZ_AUTO_510,1hmh,G102,A,C103,A,G120,E,A90,E,GC/GA Single ribose
RZ_AUTO_513,1hnw,C1496,A,G1497,A,A1518,A,A1519,A,CG/AA Canonical ribose
RZ_AUTO_514,1hnw,C1496,A,G1497,A,A1519,A,A1518,A,CG/AA Canonical ribose
RZ_AUTO_515,1hnw,C221,A,U222,A,A195,A,A196,A,CU/AA Canonical ribose
RZ_AUTO_516,1hnw,C221,A,U222,A,A196,A,A195,A,CU/AA Canonical ribose


text:
Q: Stream Audio to Bluetooth Device in C# I am trying to stream Audio to a bluetooth device in-code in C#. I've picked up the 32feet.net library to help with this. I am able to get a bluetooth speaker paired just fine, and then I use the code below to connect to the device.
    globalClient.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(BluetoothConnectedAsyncHandler), device);

Async Callback method:
    private void BluetoothConnectedAsyncHandler(IAsyncResult result)
    {
        BluetoothDeviceInfo connectedDevice = (BluetoothDeviceInfo)result.AsyncState;

        globalClient.EndConnect(result);

        if (result.IsCompleted)
        {
            NetworkStream btStream = globalClient.GetStream();
        }
    }

This all works well, but when I try to set the service from BluetoothService.SerialPort to BluetoothService.AudioSource, then I receive a SocketException on the "globalClient.EndConnect(result);" line saying "A socket operation failed because the destination host was down". See screenshot:

I've also tried to throw data at the speaker through the NetworkStream when it is setup with BluetoothService.SerialPort, but it doesn't play anything - no noise or static.
My running hypothesis is that this can't be done easily with 32feet.net, and I would have to code up the a2dp spec in code. I think the 32feet.net library is used so that I can tell the Operating System to use the speaker as an output device, rather than control audio output in-code as a supported feature.
Please help! Has anyone done this?
Would it even work if I sent an a2dp compliant stream to the device over the BluetoothService.SerialPort connection?
A2DP spec: https://www.bluetooth.org/docman/handlers/DownloadDoc.ashx?doc_id=8236
Thanks for any help!

A: Update:
This isn't possible within the 32feet.net library, you can only set the device up to talk the the Microsoft audio service using the setService method call in 32feet.net
www.nudoq.org/#!/Packages/32feet.NET/InTheHand.Net.Personal/MicrosoftSdpService/M/SetService
This MS service manages the A2DP output to the device. There is no way to directly output audio from code into the Bluetooth Device using this library in C#.


text:
Q: Modify state data for non-child react component I have two , mostly independent react classes
var User = React.createClass({
    ....
    updateGameScore: function(){ this.game1.score = .... }
    render: function(){ return (
{this.state.totalScore}
);
});

var Game = React.createClass({
    ....
    updateUserScore:function(){ how to access/modify parent here??? },
    render: function(){ return (
{this.state.score}
);
});

I need to be able to update the user totalScore when game score changes and vice versa based on some formula (irrelevant here). The components are such that game is nested in the user as a child component but cannot be vice versa. Change in user score can update game score by passing down the variable using this.state(..) , however when game score changes, what way can I use to update the correct parent User score (there can be more than one users at a time)

A: You can pass a handler function from User to Game via props:
var User = React.createClass({
    ...
    handleScoreChange: function(newScore) {
        this.setState({totalScore: newScore});
    }

    render: function () {
        return (
            <Game handleScoreChange={this.handleScoreChange.bind(this)} />
        )
    }
});

var Game = React.createClass({
    ...
    updateUserScore: function() {
        this.props.handleScoreChange(this.state.score);
    }
}

A: In a situation like yours where two components do not share a common parent that can sensibly be used to store the change in state then you should use a store. I was unfamiliar with the concept until recently but people who know much more than me about these things recommend using Reflux as it is a streamlined/simplified version of the Flux architecture. Its simply a place to store and manipulate data independent of any one component but accessible to those components as required.
EDIT: Both Flux and Reflux seem to have been superseded by the excellent Redux.

A: I did another hack while waiting for the answer which also works and interesting to share for those who want to be able to call all public functions at root level.

*

*Assuming you have Croot class
var Croot = React.createClass({
    ...
    anyPublicFunction(val){
       ...
    }
});

*assign the result of render to a variable.
var rootComponent = React.render(
    <Croot >..users & games here ...</Croot>,
    document.getElementById('lobbyArea')
);

*Use that variable in any child node to call any public function of Croot
rootComponent.anyPublicFunction(val);


text:
Q: The anchor tag in html is bugged or something So when I was trying to link to a page using the  tag and tried testing it and clicking on it, nothing happened like I literally mean nothing happened.
<button>Google</button>

So I tried making the anchor tag by it self and when I refreshed the page it just acted like a passage tag  and have just text and can't click on it and when I right click it it just shows the default context menu for text so how can I fix it because it shouldn't be doing this and it is showing now error or anything and tried it with multiple browsers and nothing is working. And I said I tried the  tag by itself so that means it has nothing to do with the css and I also tried the target attr as well and still nothing. I tried through localhost and file and still nothing so I am out of ideas now.


text:
Q: Inserting regular expression in PostgreSQL table I would like to know how I can insert regular expression in a table column in a PostgreSQl table.
For example I have column called "rule" in a table where I need to store the expression ^[0-9]+$. I tried:
insert into rule_master(rule)
values('^[0-9]+$') where rule_id='7'

But I am getting error syntax near where is wrong. I tried this with and with out single quotes. Please suggest me a solution.

A: It appears you want to UPDATE an existing record. In that case you should do:
UPDATE rule_master
SET rule = '^[0-9]+$'
WHERE rule_id = '7';

But if this is indeed a new record and you want to INSERT that regex with the value of "rule_id" then do:
INSERT INTO rule_master(rule_id, rule)
VALUES ('7', '^[0-9]+$');


text:
Q: Java Double Ended Queue toString Method overwriting left element I have created a double ended queue, and I want to print out the contents of my queue. I have created a toString method however when I add an element to the left it overwrites the current front(left) element.
For example
 System.out.println(myDeq);
 myDeq.addFront(7);
 myDeq.addRight(12);
 System.out.println(myDeq);
 myDeq.addFront(15);
 System.out.println(myDeq);

So my output would be
<>
<7,12>
<15,12>

But I want
<15,7,12>

My toString method is:
public String toString()
    { StringBuffer sb = new StringBuffer("<");
        QCell<T> l = frontCell;
        QCell<T> r = backCell;
        while (l != null && r != null)
        { sb.append(l.data +"," + r.data + ",");
            l = l.next;
            r = r.next;
        }
        return(sb+">");
    }

My add to the left code is:
    @Override
public void addFront(T x) {
    QCell<T> theCell= new QCell<T>(x);
    if (frontCell == null)
        frontCell = backCell = theCell;
    else {
        frontCell.next = theCell;
        frontCell = theCell;
    }
}

I'm unsure if it is my toString method that is overwriting it or if my addFront code is incorrect.

A: You addFront is wrong because you set frontCell's next to be theCell. But then reassigned frontCell to be theCell. So the original frontCell is no longer there. Save it in a tempCell first.
public void addFront(T x) {
    QCell<T> theCell= new QCell<T>(x);
    QCell<T> tempCell;
    if (frontCell == null)
        frontCell = backCell = theCell;
    else {
        tempCell = frontCell;
        frontCell = theCell;
        frontCell.next = tempCell;
    }
}

Also your backCell will be the lastCell so do not do r = r.next; as it should and will always be null; It should instead be r.previous.
Instead use a onesided loop traversing from front to back like this.
public String toString()
    { StringBuffer sb = new StringBuffer("<");
        QueueCell<T> l = frontCell;
        while (l != null)
        { sb.append(l.data +",");
            l = l.next;
        }

        return(sb+">");
    }

A: Shouldn't this:
frontCell.next = theCell;

be this instead?
theCell.next = frontCell;


text:
Q: How accurate is the getSpeed() I have found the acceleration of the device using accelerometer . There is a method called getSpeed() which gives the speed of the device during its motion. I wanted to know how accurate is the value returned by that method.
Thanks for the help.


text:
Q: CLion doesn't have CSV file support? I'm new to Clion, switching form Visual Studio and I'm trying to impliment a program that reads in data from a .csv file. However, after I put the file in the directory it doesn't seem to recognize the file. Any resources? I can't find anything on jetBrain about this either.
Thanks.

A: Just like Konafets, I am not quite sure about what your exact problem is, but have you tried installing the CSV Plugin for CLion?
Go to File | Settings | Plugins, type 'csv' in the search bar, click 'Search in repositories' until you land on the install page.


text:
Q: Get rid of CMake Rules folder Is there a way to get rid of the CMake Rules folders in targets in Visual Studio?

In this case the game target uses cotire for precompiled header support and the omg target has a custom command that parses the .mix file and outputs the ..._gen.h file.
Also would it be possible to remove the CMakeLists.txt file from there too? I know it's there for convenience but in my workflow it isn't that useful.
EDIT: Started a second bounty because I really need this - these "CMake Rules" folders are bloating my solution explorer because I have 100+ projects which all have them!
I would accept anything - a CMake way, a VS way (some "solution explorer view" or macro or whatever)...
EDIT 2:
here is sort-of the cmake for the omg target:
add_library(omg SHARED D:/omg.cpp D:/omg.mix)
add_custom_command(OUTPUT D:/omg_gen.h MAIN_DEPENDENCY D:/omg.mix COMMAND python D:/mixify.py D:/omg.mix D:/omg_gen.h)
add_custom_target(${target}_gen_${mix_name_only} DEPENDS ${gen_header})
add_dependencies(omg omg_gen)
target_sources(omg PUBLIC D:/omg_gen.h)

so omg_gen.h is generated from omg.mix and then included in omg.cpp

A: The .rule files are needed by CMake to attach the custom commands to some "dummy" self-generated file, if there are no input files given. You can see this when you look at the .rule file properties of your Visual Studio project in question (see Custom Build Tool/General/Command Line).
If you're not changing the CMake script code containing those target, you can't get rid of them.
You can only move them into the project's root source folder or any other folder you specify.
I've successfully tested the following example:
cmake_minimum_required(VERSION 2.8)
project(NoRulesSourceGroup NONE)

# Overwrite the rule for "CMake Rules" with do-not-match-anything (-> root)
source_group("CMake Rules" REGULAR_EXPRESSION "^$")

# Move ".rule" files somewhere else
source_group("Some Other Source Group" REGULAR_EXPRESSION "\\.rule$")

add_custom_target(
    ${PROJECT_NAME}
    COMMAND ${CMAKE_COMMAND} -E echo "Hello World"
)

Edit: You could also combine the above regular expression with a match for CMakeLists.txt:
source_group("Some Other Source Group" REGULAR_EXPRESSION "CMakeLists\\.txt|\\.rule$")

Edit: If you can modify your CMake script code, you should add to your add_custom_command() call:

MAIN_DEPENDENCY

Specify the primary input source file to the command. This is treated just like any value given to the DEPENDS option but also suggests to Visual Studio generators where to hang the custom command. At most one custom command may specify a given source file as its main dependency.

In your case you won't even need the additional custom target since you have a dependency through the header file. I've successfully tested the following derived from your question's example:
file(WRITE omg.cpp "")
file(WRITE omg.mix "")

add_library(omg SHARED omg.cpp omg.mix)
add_custom_command(
    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/omg_gen.h
    MAIN_DEPENDENCY omg.mix
    COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/omg.mix ${CMAKE_CURRENT_BINARY_DIR}/omg_gen.h
)
target_sources(omg PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/omg_gen.h)

References

*

*source_group()

*Source/cmMakefile.cxx