text:
Q: HoverIntent jQuery and calling the jQuery script I'm working to integrate hoverintent jQuery into my site. I've plugged it into my code but I'm receiving an error from the Chrome debugger. The error reads Uncaught TypeError: Cannot use in operator to search for display in undefined. I'm not sure what is wrong. Here is my code.

</script>

Here is the html code

<form action="" id="form1" method="post">

<textarea id="inputbox1"  name="what_i_do" maxlength="160" value=""><?php echo

$profile_data['what_i_do']; ?></textarea>

<input type="submit" id="button1" value="Edit">

</form>

<form action="" id="form2" method="post">

<textarea id="inputbox2" name="fait_accompli"  maxlength="160" value=""><?php echo

$profile_data['fait_accompli']; ?></textarea>

<input type="submit" id="button2" value="Edit">

</form>

A: It's because you are missing the closing curly brace and parentheses for the document.ready function
$('#form1').hoverIntent(config);

$('#form2').hoverIntent(config_1);
}); // <-----  here to close the document.ready function

change your configurations to include function()
var config = {
  sensitivity: 3,
  interval: 200,
  over: function(){
         $(this).animate({opacity: 1}, 500)
  },
  timeout: 500,
  out: function(){
         $(this).animate({opacity: 0}, 500)
  }
};

Also if both configs are the same you can just remove one of them


text:
Q: Redis pub/sub limit Using Redis pub/sub, is there a way to limit the number of listeners that Redis will publish to?
http://redis.io/commands/publish
For example, using Node.js parlance:
var redis = require('redis');
var rcPub = redis.createClient();
var rcSub = redis.createClient();

rcPub.publish('channel','messageA',{limit:1}); //desired functionality/syntax

basically, when I send messageA to Redis, I want to tell Redis to publish the message to only one listener/subscriber. Seems possible, but can Redis do this?
In the Redis docs, the command is:
PUBLISH channel message

what I am looking for is:
PUBLISH channel message limit

where limit is an integer. Seems reasonable, and easy to implement from Redis' perspective.

A: You can add a channel per subscribed, and then publish to a single user's channel when you need to communicate with him.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Async methods in C# configuring splash screen controls I'm trying to show and manage a splashscreen over async methods but don't really know how to manage this. These are my methods:
    public async void OpenSplashScrn()
    {
        splash.Show();
    }

    public async void ChangeSplashScrnMessageText(string messageText)
    {
        splash.messageLabel.Content = messageText;
    }

    public void HideSplashScrn()
    {
        splash.Hide();
    }

I tried it with await but don't know how to invoke that correctly. Starting the splashscreen does work but the Labeltext does not Change when calling the other method. I also want to call the methods in an order like: open,change text (a couple of times), hide, open,change text(a couple of times), hide. I didn't find a solution for this concrete problem.
Thank you!
EDIT:
Seems that this is no Async problem. A Little bit more code when calling the functions:
        splash = new SplashScreen(this);
        OpenSplashScrn();
        ChangeSplashScrnMessageText("Searching Data...");

Xaml Code for the splashscreen:
 <Window x:Name="splashScrn" x:Class="Window1.SplashScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Bitte warten..." Height="127" Width="336" WindowStyle="None" WindowStartupLocation="CenterScreen" Topmost="True">
<Grid Margin="0,0,2,2" Background="#FF386C89">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="47*"/>
        <ColumnDefinition Width="254*"/>
        <ColumnDefinition Width="25*"/>
    </Grid.ColumnDefinitions>
    <Label x:Name="messageLabel" Content="Message" HorizontalAlignment="Left" Margin="73,45,0,0" VerticalAlignment="Top" FontWeight="Bold" Grid.Column="1"/>

</Grid>

A: If you only use splash.Show and not splash.ShowDialog your splash screen will be non-modal. If that is what you want, you don't need to use any async methods.
By using Show the control flow of your application is kept in the calling window.
So the methods shown should actually work (except that the async modifiers have no effect at all, since there is no await). As to why your label text does not change, you will need to debug this. Is the line
splash.messageLabel.Content = messageText;

really called with correct values?


text:
Q: Bash line breaks I am using Git Bash to recursively find all of the file extensions in our legacy web site. When I pipe it to a file I would like to add line-breaks and a period in front of the file extension.
find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{1,12}" | awk '{print tolower($0)}' | sort -u

A: You have different ways.
When you do not want to change your existing commands I am tempted to use
printf ".%s\n" $(find . -type f -name "*\.*" | grep -o -E "\.[^\.]+$" |
  grep -o -E "[[:alpha:]]{1,12}" | awk '{print tolower($0)}' | sort -u ) # Wrong

This is incorrect. When a file extension has a space (like example.with space), it will be split into different lines.
Your command already outputs everyring into different lines, so you can just put a dot before each line with | sed 's/^/./'
You can skip commands in the pipeline. You can let awk put a dot in front of a line with
find . -type f -name "*\.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{1,12}" | awk '{print "." tolower($0)}' | sort -u

Or you can let sed ad the dot, with GNU sed also convert in lowercase.
find . -type f -name "." | sed -r 's/..([^.])$/.\L\1/' | sort -u
In the last command I skipped the grep on 12 chars, I think it works different than you like:
echo test.qqqwwweeerrrtttyyyuuuiiioooppp | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{1,12}"

Adding a second line break for each line, can be done in different ways.
When you have the awk command, swith the awk and  sort and use
awk '{print "." tolower($0) "\n"}'

Or add newlines at the end of the pipeline: sed 's/$/\n/'.


text:
Q: What's a Django/Python solution for providing a one-time url for people to download files? I'm looking for a way to sell someone a card at an event that will have a unique code that they will be able to use later in order to download a file (mp3, pdf, etc.) only one time and mask the true file location so a savvy person downloading the file won't be able to download the file more than once. It would be nice to host the file on Amazon S3 to save on bandwidth where our server is co-located.
My thought for the codes would be to pre-generate the unique codes that will get printed on the cards and store those in a database that could also have a field that stores the number of times the file was downloaded. This way we could set how many attempts we would allow the user for downloading the file.
The part that I need direction on is how do I hide/mask the original file location so people can't steal that url and then download the file as many times as they want. I've done Google searches and I'm either not searching using the right keywords or there aren't very many libraries or snippets out there already for this type of thing.
I'm guessing that I might be able to rig something up using django.views.static.serve that acts as a sort of proxy between the actual file and the user downloading the file. The only drawback to this method I would think is that I would need to use the actual web server and wouldn't be able to store the file on Amazon S3.
Any suggestions or thoughts are greatly appreciated.

A: Neat idea. However, I would warn against the single-download method, because there is no guarantee that their first download attempt will be successful. Perhaps use a time-expiration method instead?
But it is certainly possible to do this with Django. Here is an outline of the basic approach:

*

*Set up a django url for serving these files

*Use a GET parameter which is a unique string to identify which file to get.

*Keep a database table which has a FileField for the file to download. This table maps the unique strings to the location of the file on the file system.

*To serve the file as a download, set the response headers in the view like this:

(path is the location of the file to serve)
with open(path, 'rb') as f:
    response = HttpResponse(f.read())
response['Content-Type'] = 'application/octet-stream';
response['Content-Disposition'] = 'attachment; filename="%s"' % 'insert_filename_here'
return response

Since we are using this Django page to serve the file, the user cannot find out the original file location.

A: You can just use something simple such as mod_xsendfile. This functionality is also available in other popular webservers such lighttpd or nginx.
It works like this: when enabled your application (e.g. a trivial PHP script) can send a special response header, causing the webserver to serve a static file.
If you want it to work with S3 you will need to handle each and every request this way, meaning the traffic will go through your site, from there to AWS, back to your site and back to the client. Does S3 support symbolic links / aliases? If so you might just redirect a valid user to one of the symbolic URLs and delete that symlink after a couple of hours.


text:
Q: Show modal for Android TV I'm trying to show a modal in an AndroidTV app. I tried following this guide in creating a subclass of a DialogFragment: https://developer.android.com/reference/android/app/DialogFragment.
I'm kind of confused because when I try to show the dialog, the example shows:
FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
    newFragment.show(ft, "dialog");

But when I try, to create the FragmentTransaction, Android Studio wants to use what is I think a different FragmentTransaction.
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        android.app.Fragment prev = getFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }

        ft.addToBackStack(null);
        DialogFragment newFragment = CartDialogFragment.newInstance(111);

so then when I try to do newFragment.show, it cannot resolve the method.
My CartDialogFragment imports look like:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

Is there a different import I need to add to my Gradle file? Is this type of DialogFragment compatible with the AndroidTV leanback library?

A: Try replaceing getFragmentManager() with getSupportFragmentManager(),like this:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
    ft.remove(prev);
}
ft.addToBackStack(null);

// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");

Because your fragment extends android.support.v4.app.DialogFragment,you should also use a compatible version of FragmentManager.
Also have a look at DialogFragment.


text:
Q: Android activity manager I guess, I have a generic logic problem. I want to logout a user after 15 if there is no activity. How do I find any "activity" in android. How should I go about it...
Experts please help...

A: You'll need to invest a little thought into exactly what your requirements are here, but from what I can tell, you want to keep track of the user interactions and if a time limit expires since the last interaction, perform some action, in your case logging them out of your application.
Firstly, you'll need some place that you can track when the last interaction occured, since you'll want this to be application wide you could use a singleton to hold this, or override the Application class, either way should do.
Next, you'll need to start tracking user interactions. From your activities, you can override the onUserInteraction method, this gets invoked anytime the user interacts with the application such as key event. Each time you hit this method, update your singleton and let it know something has happened, with a timestamp.
Finally, you'll need some kind of looping check to constantly check if anything has happened recently. Theres various was of doing this, you could have a continuous loop that compares current timestamp to the last recorded event, a bit of draft code :
while(true)
{
   if (timeLastEventRecorded < (now - 15))
   {
      //nothing has happened in 15 minutes, so take corrective action
   }
}

Presumably you'll already have some code in your application that takes care of logouts, such as when the user clicks "logout", you should just be able to invoke that in the sample above.
Hope this helps

A: You should have all activities inherit from a parent activity that overrides onUserInteraction(). In that callback you should reset a static app wide timer that will perform your logout code when the time reaches the end.


text:
Q: Dynamic footer height based on UITableView Frame and ContentSize I'm trying to create a tableView in which has multiple states, some of them with footerViews that MUST fill out the remaining space the tableView.
I've been trying it using the TableView frame, and as well as the ContentSize. But turns out the ContentSize isn't right, and the footers are actually either smaller or larger than what I need them to be:
EstimatedSize for row:
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            if myProperty != 0 { return 108 }
        case 1:
            if myProperty != 0, hiredRealtor { return 80 }
        default:
            break
        }
        return 0
    }

Height for Footer in Section:
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            if myProperty == 0 { return UITableView.automaticDimension }
        case 1:
            if selectedRealtors == 0 {
                return tableView.frame.size.height - tableView.contentSize.height
            }
        default:
            break
        }
        return 0
    }

A wireframe of what I'm trying to achieve follows:

And then in my ViewForFooterInSection I use the same calculations in order to have the sameHeight, and it does. But it's not the correct height, because of ContentSize. What can I do to fix this issue?


text:
Q: AssertionFlowClient depreceated, trying to use ServiceAccountCredential, but it won't work I've tried creating a DriveService using service account acting on behalf of another user.
I've copied this code from google documentation found here https://developers.google.com/drive/delegation
    static DriveService BuildService() {
            X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
        var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)

        {
            ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
            Scope = DriveService.Scopes.Drive.GetStringValue(),
        };
        var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
        return new DriveService(auth);
    }

but I get this warning when trying to build the project:
Warning 4   'Google.Apis.Authentication.OAuth2.DotNetOpenAuth.AssertionFlowClient' is obsolete: 'AssertionFlowClient is not supported any more and it's going to be removed in 1.7.0-beta. Consider using ServiceAccountCredential from the new Google.Apis.Auth NuGet package.'
and I also get this error:
Error   11  Argument 1: cannot convert from 'Google.Apis.Authentication.OAuth2.OAuth2Authenticator' to 'Google.Apis.Services.BaseClientService.Initializer'
Then I googled ServiceAccountCredential and ended up with this code (derived from this page:  https://code.google.com/p/google-api-dotnet-client/wiki/OAuth2#Service_Accounts)
static DriveService BuildService() {
            X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
            {
                User = "someone@mydomain.mygbiz.com",
                Scopes = new[] { DriveService.Scope.DriveFile }
            }.FromCertificate(certificate));

        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Drive API Sample",
        });

        return service;
    }

When I try to build this code it seems all fine, but when I run it I get the following error.
A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Det går inte att hitta det begärda objektet.
(Translated : The requested object cannot be found)
If there is a handler for this exception, the program may be safely continued.
The error occurs on this line:
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);

Anyone have any ideas?
Update 2013 Oct 31
I have tried this code:
{
        Console.WriteLine("Drive API - Service Account");
        Console.WriteLine("==========================");

        String serviceAccountEmail = "<some email>@developer.gserviceaccount.com";

        var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
               User = "<someuser>@<mydomain>.mygbiz.com",
               Scopes = new[] { DriveService.Scope.Drive }
           }.FromCertificate(certificate));

        // Create the service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "DrvMgr",
        });

        Console.WriteLine("Executing listing");
        FileList UserFiles = service.Files.List().Execute();

I get this error message:
An unhandled exception of type 'Google.Apis.Auth.OAuth2.Responses.TokenResponseException' occurred in Google.Apis.dll
Additional information: Error:"access_denied", Description:"", Uri:""

A: It looks like the path to your p12 file is incorrect. See the Plus.ServiceAccount sample for a working solution.
I think that in this sample, the key.p12 was added to the project as a content file which is always copied to the output directory. Then mentioning "key.p12" file path from the code  will result in grabbing this file from the output folder.


text:
Q: vaadin form float field I have a vaadin application that has a form,and i use a beanitem as a data source.
Inside the beanitem i have a float value that defaults to 0.0..
If i enter a high value like 123123123 and commit(it saves to a db),when i try to edit that field inside the form i get 1.23123123E9 as a value,why?
When i edit i still pass the beanitem with the data in it,why doesn't it show my value correctly inside the textfield?
I know if i must display the value i can use decimal format but this is inside the form,and vaadin knows it is a float,so it should handle it accordingly right?
Or must i format it inside the form field factory myself?
PS:How can you set a display mode for the values inside the form?I have read you could implement the get of the field inside the bean and have it return a string too,is that the right way to do it?

A: Actually Vaadin behaves correctly, but it follows the magnitude rules (already mentioned by Yogendra Singh) please see an example

Please also check the following:
    float value1 = 12.0f;
    float value2 = 123123123;

    BeanItem<Float> item1 = new BeanItem<Float>(value1);
    BeanItem<Float> item2 = new BeanItem<Float>(value2);

    System.out.println(" result 1: " + item1.getBean());
    System.out.println(" result 2: " + item2.getBean());

Result:
result 1: 12.0
result 2: 1.2312312E8

So the correct solution (as I can see it) looks like the following:

*

*Define your own Bean. There is no reason to have a BeanItem wrapping a float value.

*Define your PropertyFormatter (example)

*Important to note, the one should not return a String instead of the correct data type. It will affect editing, validation, etc.

PropertyFormatter example:
/** Integer formatter that accepts empty values. */
public class LenientIntegerFormatter extends PropertyFormatter {

    public LenientIntegerFormatter(Property propertyDataSource) {
        setPropertyDataSource(propertyDataSource);
    }

    @Override
    public Object parse(String formattedValue) throws Exception {
        if ("".equals(formattedValue))
            return null;
        else
        return Integer.valueOf(formattedValue);
    }

    @Override
    public String format(Object value) {
        if (value == null)
            return "";

        return ((Integer) value).toString();
    }

    @Override
    public Class<?> getType() {
        return String.class;
    }
}

It may look a little bit scary, but this is the cost of flexibility. Custom Bean allows to use table view, forms, etc without any significant changes. Basically, this is the data model behind Vaadin UI.

Chapter 9. Binding Components to Data
Custom Bean example:
public class Bean implements Serializable {
    String name;
    float value;

    public Bean(String name, float newValue) {
        this.name   = name;
        this.value = newValue;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getValue() {
        return value;
    }

    public void setValue(float newValue) {
        this.value = newValue;
    }
}

Just to provide all required insights:
 Bean bean = new Bean("Test", value1);
    BeanItem<Bean> beanItem = new BeanItem<Bean>(bean);
    for(Object propertyId: beanItem.getItemPropertyIds()) {
        System.out.println(" Property: '" + propertyId +
                           "' value: " + beanItem.getItemProperty(propertyId));
    }

Will print:
Property: 'name' value: Test
Property: 'value' value: 12.0

A: toString() internally calls toString(float) This is what the documentation says for toString(float)

Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('\u002D'); if the sign is positive, no sign character appears in the result. As for the magnitude m:

*

*If m is greater than or equal to 10-3 but less than 107, then it is represented as the integer part of m, in decimal form with no leading zeroes, followed by '.' ('\u002E'), followed by one or more decimal digits representing the fractional part of m.

*If m is less than 10-3 or greater than or equal to 107, ** Let n be the unique integer such that 10n ≤ m < 10n+1; then let a be the mathematically exact quotient of m and 10n so that 1 ≤ a < 10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' ('\u002E'), followed by decimal digits representing the fractional part of a, followed by the letter 'E' ('\u0045'), followed by a representation of n as a decimal integer, as produced by the method Integer.toString(int).
To create localized string representations of a floating-point value, use subclasses of NumberFormat.

Hope this helps you understand WHY and HOW to fix it i.e. use DecimalFormat as you have mentioned inside your field factory and return as string representation for display purpose.


text:
Q: PHP connect to FTP server hello I have my code that connects to my ftp server
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
//ftp_mkdir($conn_id, $dir);
$contents = ftp_nlist($conn_id, $dir);
//var_dump($contents);
echo "<select name=\"file\">\n";
// Now loop through the files, echoing out a new select option for each one
if (($contents != '.')  && ($contents != '..') )
{

foreach( $contents as $fname )

{
   echo "<option>{$fname}</option>\n";
}
echo "</select>\n";

}
}

but the page is still echoing back the directories as . & .. despite the $contents != bit; what is missing?
changed to this ->
if (($fname != '.')  && ($fname != '..') )
{

foreach( $contents as $fname )

{
   echo "<option>{$fname}</option>\n";
}
echo "</select>\n";

}
}

but still same result

A: You might want to compare $fname inside the loop against being . or ... This is probably more what you want.


text:
Q: Mailchimp error 400 request, can't send users to list I'm working with Mailchimp and I want to send an email address to my list, I have done this so far with Volley:
public void suscribeMailChamp(){
    String listid = "listID";
    String url = "https://us16.api.mailchimp.com/3.0/lists/" + listid + "/members/";
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //
            Toast.makeText(MainActivity.this , "success" , Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this , error.toString() , Toast.LENGTH_SHORT).show();
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("email_address","testmailchimp@gmail.com");
            params.put("status","unsubscribed");
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            params.put("Authorization" , "apikey <here my api key>");
            return params;
        }
    };
    queue.add(sr);
}

but I get error 400:

Unexpected response code 400 for
  https://us16.api.mailchimp.com/3.0/lists/b9a5943047/members/

Here is a link for troubleshooting but I can't get the error:
http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/

A: Did you check the error in the link? It says
{
   "type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
   "title":"API Key Missing",
   "status":401,
   "detail":"Your request did not include an API key.",
   "instance":"924c81cc-90e9-498d-b0fd-c7b54cba207f"
}

which means you are not (or correctly) sending the API key for mail chimp in the request. Just add the mailChimp API key in the params for Volley request

So the way you would send your API key is this
params.put("Authorization", "Basic "+Base64.encodeToString(("apikey:"+apiKey).getBytes("UTF-8"),Base64.DEFAULT))

A: I got stuck at this too. Mailchimp documentation is very poor.
I found the solution from github
Just send 'Authorization': 'apikey myapikey' in your header


text:
Q: Cannot bypass Omniauth initializer in test mode I am trying to test my graphql schema without any need for authentication.
I have added skip_before_action :verify_authenticity_token to the GraphqlController, and when using postman (copied by a curl request from graphiql), and I am seeing a successful query in development mode.
In postman I have the query in the body {"query":"{\n  user(id: 1) {\n    id\n    created_at\n    updated_at\n    jwt\n}\n}\n","variables":null,"operationName":null}, and Content-Type application/json in the header and this works fine.
Now in test mode, I am hitting the auth initializer for Omniauth:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider(
    :auth0,
    Auth0::Config["app_client_id"],
    Auth0::Config["app_client_secret"],
    Auth0::Config["domain"],
    callback_path: "/auth/auth0/callback"
  )
end

Although I don't want to since I don't want any headers required in this post request.
Here is my rspec request:
require 'graphlient'

RSpec.shared_context "GraphQL Client", shared_context: :metadata do
  let(:client) do
    Graphlient::Client.new('https://api.example.org/graphql') do |client|
      client.http do |h|
        h.connection do |c|
          c.use Faraday::Adapter::Rack, app
        end
      end
    end
  end
end

and here's the actual test
it 'retrieves schema' do
  expect(client.schema).to be_a GraphQL::Schema
end

with the error:
 Failure/Error:
   expect { client.schema.status }
     .to raise_error(Graphlient::Errors::ServerError)

   expected Graphlient::Errors::ServerError, got #<ArgumentError: Received wrong number of arguments. [nil, nil, nil, {:callback_path=>"/auth/auth0/callback"}]> with backtrace:
     # /usr/local/bundle/gems/omniauth-auth0-1.4.2/lib/omniauth/strategies/auth0.rb:41:in `initialize'

A: I think I got it! I forgot to add keys for test in config/auth0.yml.
It was a hidden file.


text:
Q: How to represent a check valve in simulink? i am a new simulink user, how to represent a check valve in simulink?I am using version 2012b.
Thank you

A: If you have access to the SimHydraulics toolbox then it is as simple as making use of the Check Valve block.
If you are not already familiar with this toolbox, SimHydraulics is an extension of the Simscape toolbox.  Simscape can be useful when you are doing physical modeling such as this, as it provides a library of physical components that can be connected in the same structure as whatever the real-life system is.  This differs somewhat from a "standard" Simulink model which is more of a block diagram that typically represents the actual mathematical equations that describe the underlying dynamics of your system.
With that said, if you don't have Simscape and need to model this using base Simulink blocks, then you will need to first figure out what is the underlying logic/equations that would describe your check valve.


text:
Q: How to add custom header on spring soap client Hi I would like to add header to spring soap client and I have a ClientAppConfig class which is like below;
@Configuration
public class ClientAppConfig {

    @Bean
    public Wss4jSecurityInterceptor wss4jSecurityInterceptor() {
        Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
        interceptor.setSecurementActions("Timestamp");
        interceptor.setSecurementUsername("user");
        interceptor.setSecurementPassword("*******");
        return interceptor;
    }

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setPackagesToScan("com");

        return marshaller;
    }

    @Bean
    public SomeClient someClient(Jaxb2Marshaller marshaller) {
        SomeClient client = new SomeClient();
        client.setDefaultUri("http://test");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);

        return client;
    }
}

Example Client:
@Component
public class SomeClient extends WebServiceGatewaySupport {

    public SomeResponse someMethod(ArrayOfLong arrayOfLong) {
        SomeRequest request = new SomeRequest();
        request.setsomeId(arrayOfLong);
        SomeResponse response = (SomeResponse) getWebServiceTemplate()
                .marshalSendAndReceive(request, new SoapActionCallback(
                        "http://soapaction"));
        return response;
    }
}

And I have wsdl request like this;
<soapenv:Envelope xmlns:soapenv="http://envelope" xmlns:v1="http://Service">
   <soapenv:Header xmlns:as="http://Schema">
        <wsse:Security xmlns:wsse="http://wss-wssecurity-secext-1.0.xsd">
            <wsse:UsernameToken>
                <wsse:Username>user</wsse:Username>
                <wsse:Password>********</wsse:Password>
            </wsse:UsernameToken>
        </wsse:Security>
        <as:consumerContext xsi:type="as:IntWebAppContextType" xmlns:as="http://Schema" xmlns:xsi="http://XMLSchema-instance">

            <consumerCode>someCode</consumerCode>
        </as:consumerContext>
    </soapenv:Header>
   <soapenv:Body>
      <v1:someReceived xmlns:ns3="http://Service" xmlns:ns2="http://Schema">
         <v1:parameters>
            <!--Optional:-->
            <v1:someId>
               <!--Zero or more repetitions:-->
               <v1:long>111111111</v1:long>
            </v1:someId>
         </v1:parameters>
      </v1:someReceived>
   </soapenv:Body>
</soapenv:Envelope>

I have added username and password but I have to add as:consumerContext section, I need to get consumerCode for getting response other wise Im getting error. How Can I get consumerCode with spring ws

A: If you generate JAVA classes using wsimport in windows, as:
wsimport -keep -verbose http://compA.com/ws/server?wsdl

You will get ConsumerContext.java generated which you can populate with valid data, set it in Header.java using setConsumerContext(ConsumerContext obj) and fire the request.
Similar implementation you can find here - writing-and-consuming-soap-webservice-with-spring with source code on GitHub.


text:
Q: Remove content within square curly brackets with linebreak from textarea I have the following textarea on a create forum post page.
There is some text here in front:

[confidential]
{sitedetails}

Site URL: aaa
Site Username: bbb
Site Password: cc

FTP URL: ddd
FTP Username: eee
FTP Password: ffff

Optional Information: gggg

{/sitedetails}
[/confidential]

There is some text in the middle.

[confidential]
User added some confidential details. This should not be removed!!!
[/confidential]

And there is some text at the end.

The confidential information is automatically pasted into the textarea when the user fills in the form. But now I want to add a button that allows posting without site details. But still allows for confidential information.
Personally, I am terrible at regular expressions. When looking at those it is like magic for me. But I am pretty sure that it is exactly what I need.
So I am now trying with the code below but this is deleting everything but randomly.
var $editor = $(".markItUpEditor");
var curValue = $editor.val();
val = curValue;
val = val.replace(/'[confidential]'([\s\S]*)[\/confidential]/gm, "");
val = val.replace(/[[\]]/g,'')
$editor.val(val);
console.log(val);

I was really hoping if someone could help me with removing this part from the textarea but keep everything else:
Needs to be removed
[confidential]
{sitedetails}

Site URL: aaa
Site Username: bbb
Site Password: cc

FTP URL: ddd
FTP Username: eee
FTP Password: ffff

Optional Information: gggg

{/sitedetails}
[/confidential]

So the result is like this
There is some text here in front:

There is some text in the middle.

[confidential]
User added some confidential details. This should not be removed!!!
[/confidential]

And there is some text at the end.

These parts are the start and end of what needs to be removed. Please keep in mind that there are linebreaks(enters) in the textarea
Start
[confidential]
{sitedetails}

End
{/sitedetails}
[/confidential]

A: The regex you want is /\s*\[confidential\]\s*\{sitedetails\}(\s|\S)*{\/sitedetails\}\s*\[\/confidential\]\s*/g.
It's a bit verbose, but hover over each part in regex101 to understand what's going on: https://regex101.com/r/R5Oece/1

But I am pretty sure that it [regex] is exactly what I need.

Regex is rarely necessary, it's a convenience tool, but you could just as easily split your text by new lines, spliced out the sub-array, and rejoined into a string.

    const str = `There is some text here in front:

[confidential]
{sitedetails}

Site URL: aaa
Site Username: bbb
Site Password: cc

FTP URL: ddd
FTP Username: eee
FTP Password: ffff

Optional Information: gggg

{/sitedetails}
[/confidential]

There is some text in the middle.

[confidential]
User added some confidential details. This should not be removed!!!
[/confidential]

And there is some text at the end.`;

    let out = str.replace(/\s*\[confidential\]\s*\{sitedetails\}(\s|\S)*{\/sitedetails\}\s*\[\/confidential\]\s*/g, '\n\n');

    console.log(out);


text:
Q: How would I put ValueError as a procedure and use it to check the age and firstname? How would I use that errorcheck procedure throughout my program so I can check whether or not the user has inputted the correct data type?
def errorcheck():
    valid=False
    while valid==False:
        try:
            ()=True
        except ValueError:
            print("Please enter an appropriate value")
            valid=False

errorcheckage=int(input("How old are you?"))
forename=str(input("What is your firstname?"))
username=forename[0:3]+age
print(username)

A: You can write a wrapper that implements your loop controls, but it's rather detailed and may not save you much time.
def validator_loop(f: "function to run",
                   *args: "arguments to function",
                   validator=lambda _: True,
                   **kwargs: "kwargs for function"):
    while True:
        try:
            result = f(*args, **kwargs)
        except Exception as e:
            continue  # repeat if it throws any exception
        else:
            if validator(result):
                return result

# note that an entry of "zero" will fail this validation, even though
# 0 is a valid age for some purposes! I'll leave this edge case for you
checkage = validator_loop(input, "How old are you?",
                          validator=lambda s: int(s))


text:
Q: unable to see state names in dropdown box using bootstrap formhelpers I am using  bootstrap-formhelpers.min.js to list down all state names into dropdown box.
Here is my _layout files references.

Here is my _InsuranceForm.cshtml partial view on which I have state dropdown box.

          State

        <select class="form-control bfh-states" name="State" data-country="US" id="cboInsuranceState"></select>

_InsuranceForm.cshtml partial view is being called into another partial view called: _Insurance.cshtml
Here is _Insurance.cshtml
@{Html.RenderPartial("_InsuranceSummary");}
@{Html.RenderPartial("_InsuranceForm");}

Now if I am adding following reference into _InsuranceForm.cshtml then it is working as expected

but since above reference is already exist into _Layout.cshtml file, so I want to add it into single place instead of two places because there are many other pages into my project which are using this reference to display state names into dropdown box.
Can someone please help me how to resolve this issue?


text:
Q: How to define if else statement whereby the else statement can remove unwanted \t I have a function, where one part reads as follows:
conefor.input <- function(conefor.file, onlyoverall, probmin, index)
{
for(i in 1:l00)
{
cat(paste(conefor.file,
        if(onlyoverall=="TRUE")
                {onlyoverall<-"onlyoverall"},
distance,
        if(probmin=="TRUE")
            {probmin<-paste("-pcHeur", min)},
 index, sep="\t"),file="conef_command.txt", sep="\n")}
return("conef_command.txt")
}

My objective is to generate 100 lines where each input is divided by a tab.
There is no problem when the two 'if' statements above are true. With the resulting being:
conefor.file\tonlyoverall\tdistance\tpcHeur min\tindex

However, when the two 'if' statements above are false, I am left with two tabs where 'onlyoverall' and 'pcHeur' would have been, whereas, what I really want is no action at all, and only one tab separating each argument.
Example when 'if' statements are false:
conefor.file\t\tdistance\t\tindex

What I want when 'if' statements are false:
conefor.file\tdistance\tindex

Many thanks in advance

A: it's hard to suggest any form of vectorization or similar for your for loop, since it's not clear (to me at least)
what differences there are between iterations.
However, as for the paste statement inside of cat, you can use the following instead
paste(ifelse(onlyoverall,
          paste(conefor.file, onlyoverall<-"onlyoverall", sep="\t"),
          conefor.file),
      ifelse(probmin,
            paste(distance, probmin<-paste("-pcHeur", min), sep="\t"),
            distance),
      index,
      sep="\t")

Notice, this grabs the output prior to the if statement and includes in an ifelse output, where it is given for both TRUE and FALSE
eg:
x1 <- x2 <- TRUE
paste(ifelse(x1, paste("A", "B" , sep="#"), "A"), ifelse(x2, paste("C", "D", sep="#"), "C"), "E", sep="#")
# [1] "A#B#C#D#E"

x1 <- x2 <- FALSE
paste(ifelse(x1, paste("A", "B" , sep="#"), "A"), ifelse(x2, paste("C", "D", sep="#"), "C"), "E", sep="#")
#  [1] "A#C#E"

x2 <- TRUE
paste(ifelse(x1, paste("A", "B" , sep="#"), "A"), ifelse(x2, paste("C", "D", sep="#"), "C"), "E", sep="#")
#  [1] "A#C#D#E"


text:
Q: Not getting the css and js effect on view page in laravel i have created a small nav bar which i downloaded from a website. i have pasted the html in welcome.blade.php and i have put the css in public folder
<!doctype html>

   <meta charset='utf-8'>
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="public/css/styles.css">

   <title>CSS MenuMaker</title>

Home

Products

Company

Contact

this is my css code
@import url(http://fonts.googleapis.com/css?family=Raleway);
#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
  margin: 0;
  padding: 0;
  border: 0;
  list-style: none;
  line-height: 1;
  display: block;
  position: relative;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}
#cssmenu {
  width: auto;
  border-bottom: 3px solid #47c9af;
  font-family: Raleway, sans-serif;
  line-height: 1;
}
#cssmenu ul {
  background: #ffffff;
}
#cssmenu > ul > li {
  float: left;
}
#cssmenu.align-center > ul {
  font-size: 0;
  text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu.align-right > ul > li > a {
  margin-right: 0;
  margin-left: -4px;
}
#cssmenu > ul > li > a {
  z-index: 2;
  padding: 18px 25px 12px 25px;
  font-size: 15px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all .2s ease;
  -moz-transition: all .2s ease;
  -ms-transition: all .2s ease;
  -o-transition: all .2s ease;
  transition: all .2s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all .2s ease;
  -o-transition: all .2s ease;
  transition: all .2s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}
#cssmenu > ul > li.active > a:after,
#cssmenu > ul > li:hover > a:after,
#cssmenu > ul > li > a:hover:after {
  background: #47c9af;
}

but when i run the page the page doesn't show any effect,just a white page menu listed in normal font.
i know it is a simple thing but as am new to laravel please help me

A: Use laravel's asset() helper for js and css files and it's better to include your scripts after body tag. Try this:
    <!doctype html>

       <meta charset='utf-8'>
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="stylesheet" href="{{asset('css/styles.css')}}">
       <title>CSS MenuMaker</title>

Home

Products

Company

Contact


text:
Q: How to avoid ANR From an app when it is not in the foreground? I am trying to find a solution for Application Not Responding (ANR) error when my app is in background. I want any ANR not to occur when my app is not in foreground.
How this can be achieved?
Thanks in advance.

A: From Google docs:
Android will display the ANR dialog for a particular application when it detects one of the following conditions:

*

*No response to an input event (such as key press or screen touch events) within 5 seconds.

*A BroadcastReceiver hasn't finished executing within 10 seconds.

After that be sure to not do blocking/long operations on the UiThread/MainThread even if the App is in background.


text:
Q: How to Minimise Data Loss When Migrating a High-Traffic DynamoDB Table In Order to Redefine Its Schema (Introducing a Sort Key)? Preface: I am aware that the direct answer to "Can A Sort Key be Retroactively Added to An Existing DynamoDB Table?" is a no, as indicated by Add range key to DynamoDB table without destroying the table and How to add primary sort key to an already existing table in AWS dynamo db?
As it will become more evident, the intention of this post is to explore the necessary actions/considerations that should be acknowledged beyond the immediate answer to the aforementioned question.

Context
I have a legacy DynamoDB table that sits along a data pipeline with millions of records that have flown through and stored in the table over the course of its existence.
This DynamoDB table primarily acts as a KV store, with its simplified schema represented as:
{
 id: "bfk1r3sdvx5937df",
 record_data: {
   key_0: value_0,
   key_1: value_1,
   key_2: value_2,
   ...
 },
}

The table's partition key, id, is a unique hash created when individual records are ingested and saved into DynamoDB, and id persists within these records as they flow through the remaining stages of the data pipeline beyond the table.
Additionally, the record_data nested KV object, represented in the above schema, is not always a unique value. In fact, there are multiple instances within this table whereby a particular set of records have record_data values that are 1:1 matches with one another.
Given that the two above-mentioned components make up the entire  table schema (simplified for this context), the aforementioned id partition key is the only reference with which to query the table.
Now, the limitation that comes with solely being able to query the table via its id partition key is that it only serves to be useful when querying the table with a specific known id value for a particular record.
For other purposes, there are no further sortable/discernible patterns within the current schema that allows for a more granular and intuitive query.
With all this said, I'm thinking of ways to add an appropriate sort key to this table so that querying its millions of records is more feasible.
In other parts of the data pipeline, notably where the same records are stored, the records are stored with date timestamps attached.
Therefore, it would make a lot of sense to add a UTC timestamp (eg. createdAt) to future records in this DynamoDB table as its new sort_key and, hence, improve querying capabilities and data consistency as the table scales.
Blockers
However, there are several technical blockers with the above approach:
One, DynamoDB prohibits retroactive redefinition of the table schema beyond the table's initial provisioning:

You need to add the sort key at the initial table creation state as you can not add a sort key for an already existing table.

Two, DynamoDB prohibits the presence of empty values that correspond to sort key attributes, thereby creating the need to backfill existing records with non-empty values:

Partition key and sort key attributes of base tables continue to require non-empty values for all data types, including String and Binary.
Similarly, String and Binary key attributes of local secondary indexes or global secondary indexes also require non-empty values.

Solution
With both considered, the only viable way (outside of abandoning DynamoDB as the datastore for these particular records) would be to:

*

*Create a new table with a redefined schema; the schema would be identical to that of the old table, with the exception of the sort_key

*Migrate the millions of stored records of the old table into the new table, backfilling the empty sort_key values of old records during their migration
TLDR
That being said, my question is: as the old table is currently live in production, with new data dynamically stored every second, what would be the safest way to perform the migration of this existing DynamoDB table to a new table, in a way that minimises the risk of data loss?

Further Considerations

*

*Data saved in this table is initially collected and streamed via various client-side applications (earlier in the data pipeline) that are internationalised and collect data across various timezones.

*

*Given the internationalised nature of data traffic, it would be challenging to define the table's 'low traffic period': the time period in which it would otherwise make the most sense to undergo its migration.

*It would be ideal to preserve (and not leave behind) the millions of records saved in the old table, given the continued value of these records.

*When the new table is created, the old table needs to be retired so as to preserve the single source of truth and avoid data duplication.

*It would also be ideal to explore approaches that will not involve provisioning additional services to the current architecture where this DynamoDB table sits.

*The new DynamoDB table will be deployed via Terraform, as was the old table.

*No further restrictions.

A: You're making this leap of faith that adding a createdAt sort key would be beneficial to you. What would your partition key be? You don't say, and in fact there's no good answer. I'm guessing you're planning for it to be id still but if so then you haven't improved your situation. You can't directly retrieve "last 10 items" if each item has a different partition key.
What you should do is keep this table and add a GSI. It'll auto backfill, simplifying all your transition questions. In that GSI you can have the sort key be a timestamp. For the partition key have it be some sharded value. Pick as many shards as you think you need write capacity. Each shard can accept 1,000 write units per second. So if you're needing to handle max 10,000 items per second then have at least 10 shards. Name the attributes GSI1PK and GSI1SK. Into GSI1PK put a value "1" through "10". Into GSI1SK put the timestamp. When you want to run a time-oriented query you'll have to make as many queries as you have shards and merge the results together.
Thus you can retrieve by ID from the base table and retrieve by timestamp from the GSI and handle arbitrary load rates.


text:
Q: NSSortDescriptor Please give me suggestion, How can I solve solve this problem..

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Weight" ascending:NO selector:@selector(localizedStandardCompare:)];
  NSArray *sortedArray = [arrayToSort sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

I am getting output :
-[__NSCFNumber length]: unrecognized selector sent to instance 0x6a81cf0
2012-05-16 09:54:21.480 MedzioSearch[2188:f803] *** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSInvalidArgumentException> -[__NSCFNumber length]: unrecognized selector sent to instance 0x6a81cf0

A: What kind of objects are in arrayToSort? What is the type of their "Weight" property?
At a guess, some of the objects have a Weight property which is an NSString while some have a Weight property which is an NSNumber.  As a consequence, the sort is trying to do something like [someString localizedStandardCompare:someNumber].  Internal to -[NSString localizedStandardCompare:], it's invoking -length on the argument which is an NSNumber and doesn't recognize that selector.
By the way, property names should begin with a lowercase letter unless they begin with an acronym or initialism (like "URL" or "TIFF").  So, your property should be named "weight", not "Weight".


text:
Q: Hook in the loop after the first post I am trying to hook content in my wordpress loop. I'd like to insert a div after the first post.
I've found this code, that works pretty well except that it repeats the hook every 4 posts :
add_action( 'loop_start', 'wpse_141253_loop_start' );

function wpse_141253_loop_start( $query )
{
    if( $query->is_main_query() )
    {
        add_action( 'the_post', 'wpse_141253_the_post' );
        add_action( 'loop_end', 'wpse_141253_loop_end' );
    }
}

function wpse_141253_the_post()
{
    static $nr = 0;

    if( 0 === ++$nr % 4 )
        echo '<div> -------- CONTENT ------- </div>';
}

function wpse_141253_loop_end()
{
    remove_action( 'the_post', 'wpse_141253_the_post' );
}

It seems I have to amend the function wpse_141253_the_post but not sure what to do here...


text:
Q: When searching, Prolog gives correct answers but repeats them N times before searching another Ok So i've got this Prolog code that represents an evolving world of blocks, and there's a robotic arm that can move 1 block at the time, and 2 little robots "rob and bor" that can paint blocks of their assigned color when the blocks are on top of a tower or on the bottom of a tower (See code for the conditions). function clear(X) is true when block X is on top of a tower, and ontable(X) is true when X is on the table (at the bottom of a tower). Single block towers return both clear and ontable as true.
The code aims to give all the solutions, step by step, when asked for a particular state (Like all 4 blocks on a single tower and red painted).
For that, there's a set of actions and facts defined, their conditioning effects (When action A is done under conditions C, what happens to the fact F) and a possibility/reality check with functions poss(returns true if some action is possible to do) and holds(returns true if some fact is true) that work on every state S. legal is the mix of these 2(Something is legal if everything in it holds and is possible).
%% Object Declaration (problem-specific)
block(B) :- member(B,[a,b,c,d]).

% colors available for rob and bor
color(rob,B) :- member(B,[blue]).
color(bor,B) :- member(B,[red]).

%% Initial Situation (problem-specific)
holds(F,s0) :- member(F,[on(a,b),on(b,c),ontable(c), ontable(d), clear(a), clear(d)]).
holds(color(B,white),s0) :- block(B).

%% Blocks World Preconditions (domain-specific)
%% action move_to_block(X,Z) moves block X on top of block Z
% poss is true when its possible to do the action.
poss(move_to_block(X,Z),S) :-
    holds(clear(X),S), holds(clear(Z),S), Z\=X, \+ holds(on(X,Z),S).

poss(move_to_table(X),S) :-
    holds(clear(X),S), \+ holds(ontable(X),S).

%% Robot R paints block B of color C

poss(paint(rob,B,C),S) :-
     color(rob,C),holds(clear(B),S), \+ holds(color(B,C),S).

poss(paint(bor,B,C),S) :-
    color(bor,C), holds(ontable(B),S), \+ holds(color(B,C),S).

%% Blocks World Effects (domain-specific)
% is_conditional_negative_effect(Act,Cond,Fact)
% when Act is peformed and Cond holds, Fact becomes false

is_conditional_negative_effect(move_to_block(X,_),on(X,Y),on(X,Y)).
is_conditional_negative_effect(move_to_block(X,_),ontable(X),ontable(X))
is_conditional_negative_effect(move_to_block(X,Z),true,clear(Z)).
is_conditional_negative_effect(move_to_table(X),on(X,_),on(X,_)).
is_conditional_negative_effect(paint(R,B,C),color(B,D),color(B,D)).
% is_conditional_positive_effect(Act,Cond,Fact)
% when Act is peformed and Cond holds, Fact becomes true
is_conditional_positive_effect(move_to_block(X,_),on(X,Y),clear(Y)).
is_conditional_positive_effect(move_to_block(X,Z),true ,on(X,Z)).
is_conditional_positive_effect(move_to_block(X,_),true,clear(X)).
is_conditional_positive_effect(move_to_table(X),true ,ontable(X)).
is_conditional_positive_effect(move_to_table(X),on(X,Y),clear(Y)).
is_conditional_positive_effect(move_to_table(X),true,clear(X)).
is_conditional_positive_effect(paint(R,B,C),color(B,_),color(B,C)).

holds(true,s0). % "true" always holds

holds(F,do(A,S)) :-
         holds(F,S),
         \+ (is_conditional_negative_effect(A,C,F), holds(C,S)).

holds(F,do(A,S)) :-
    is_conditional_positive_effect(A,C,F),holds(C,S).

% S is legal if it is the result of performing executable actions
legal(s0).
legal(do(A,S)) :-
    legal(S),
    poss(A,S).

So thing is, when a consult done like follows ( time() only makes that the given answer returns the process time, for optimization sake... that's another problem i'll check later):
time((legal(S), holds(on(b,d),S), holds(on(c,b),S), holds(on(a,c),S), holds(color(b,blue),S), holds(color(a,red),S))).

SO far I get correct answers, but repeated like 10 times before it gives another, (correct too), so if I want all the answers, I've got to smash the ; like ten thousand times. I've been approximately 3 hours trying to solve this issue, since it doesn't let me check if I get all the correct answers or something is missing. Do you guys figure out what's going on?.
Tried to make everything as clear as possible, but comment if you need me to clarify something!

A: Finally, with a friend, we managed to fix it, the problem was on the positive conditional effects, specifically those related to clear. These affirmations were obvious, since a block must already return true to clear before being moved:
is_conditional_positive_effect(move_to_block(X,_),true,clear(X)).
is_conditional_positive_effect(move_to_table(X),true,clear(X)).

Also I changed some conditionals to be more specific, these greately improved the performance of the search:
is_conditional_negative_effect(move_to_table(X),on(X,_),on(X,_)).

was replaced by
is_conditional_negative_effect(move_to_table(X),on(X,Y),on(X,Y)).

and
is_conditional_positive_effect(paint(R,B,C),color(B,_),color(B,C)).

was replaced by
is_conditional_positive_effect(paint(R,B,C),true,color(B,C)).

Credits to my mate Pablo.


text:
Q: Given a few points and circles, how can I tell which point lies in which circles? Given a small number of points and circles (say under 100), how do I tell which point lies in which circles? The circles can intersect, so one point can lie in multiple circles.
If it's of any relevance, both points and circle centers are aligned on a hexagonal grid, and the radii of the circles are also aligned to the grid.
With a bit of thought, it seems the worse case scenario would always be quadratic (when each point lies in all circles) ... but there might be some way to make this faster for the average case when there aren't that many intersections?
I'm doing this for an AI simulation and the circle/point locations change all the time, so I can't really pre-compute anything ahead of time.

A: If the number of points and circles is that small, you probably will get away with brute-forcing it. Circle-point intersections are pretty cheap, and 100 * 100 checks a frame shouldn't harm performance at all.
If you are completely sure that this routine is the bottleneck and needs to be optimized, read on.
You can try using a variation of Bounding Volume Hierarchies.
A bounding volume hierarchy is a tree in which each node covers the entire volume of both (or more if you decide to use a tree with higher degree) of its children. The volumes/objects that have to be tested for intersections are always the leaf nodes of the tree.
Insertion, removal and intersection queries have an amortized average run-time of O(log n). You will however have to update the tree, as your objects are dynamic, which is done by removing and reinserting invalid nodes (nodes which do not contain their leaf nodes fully any more). Updating the full tree takes a worst case time of O(n log n).
Care should be taken that while insertion, a node should be inserted into that sub-tree that increases the sub-tree's volume by the least amount.
Here is a good blog post by Randy Gaul which explains dynamic bounding hierarchies well.
You'll have to use circles as the bounding volumes, unless you can find a way to use AABBs in all nodes except leaf nodes, and circles as leaf nodes. AABBs are more accurate and should give you a slightly better constructed tree.

A: You can build a kd-tree of the points. And then for each circle center you retrieve all the points of the kd-tree with distance bounded by the circle radius. Given M points and N circles the complexity should be M log M + N log M = max(M,N) log M (if points and circles are "well distributed").
Whether you can gain anything compared to a brute-force pair-wise check depends on the geometric structure of your points and circles. If, for instance, the radii of the circles are big in relation to the distances of the points or the distances of the cirlce centers then there is not much to expect, I think.

A: Rather than going to a full 2D-tree, there is an intermediate possibility based on sorting.
Sort the P points on the abscissas. With a good sorting algorithm (say Heapsort), the cost can be modeled as S.P.Lg(P) (S is the cost of comparisons/moves).
Then, for every circle (C of them), locate its leftmost point (Xc-R) in the sorted list by dichotomy, with a cost D.Lg(P) (D is the cost of a dichotomy step). Then step to the rightmost point (Xc+R) and perform the point/circle test every time.
Doing this, you will spare the comparisons with the points to the left and to the right of the circle. Let F denote the average fraction of the points which fall in the range [Xc-R, Xc+R] for all circles.
Denoting K the cost of a point/circle comparison, the total can be estimated as
S.P.Lg(P) + D.Lg(P).C + F.K.P.C
to be compared to K.P.C.
The ratio is
S/K.Lg(P)/C + D/K.Lg(P)/P + F.
With the unfavorable hypothesis that S=D=K, for P=C=100 we get 6.6% + 6.6% + F. These three terms respectively correspond to the preprocessing time, an acceleration overhead and the reduced workload.
Assuming resonably small circles, let F = 10%, and you can hope a speedup x4.

If you are using a bounding box test before the exact point/circle comparison (which is not necessarily an improvement), you can simplify the bounding box test to two Y comparisons, as the X overlap is implicit.


text:
Q: why am I seeing unknown dataframes in my python script? and how to avoid letting the script saving them? at the end of my python script on jupyter notebook, I check to see all available dataframes that were saved. I use the following code:
# list of all DFs in memory
All_DFs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
All_DFs

other than the dataframes I've created myself I see the following dataframes that are unknown to me.
['_14',
 '_24',
 '_38',
 '_39',
 '_40',
 '_41',
 '_8',
 '__',
 '___']

I wonder why theses are created, and I would like to know how to avoid having them created.
thank you,

A: Those are cell numbers where you've run code and gotten output you could show again, for example by putting _14 in a Jupyter cell. (Specifically, created as part of IPython/Jupyter's Output caching system.) Without seeing examples of what you ran in the pertinent cells, I'd be totally guessing as to why they are in that list.
I can say one way that I was able to reproduce the phenomena was to put something like this on the final line of a cell:
pd.read_table(StringIO(input), header=0, index_col=None,  delim_whitespace=True)

Where I basically had defined a dataframe but not assigned it to a variable. I'm not saying that is what you did, but it was one way I could get something like you saw and then test getting rid of such cases. Maybe there's mixed output in the cases you have and your evaluation code senses a dataframe in there? You'd have to provide much more information to give specifics. (And because collecting dataframes like this after-the-fact is not advised [see below], I don't have experience encountering it myself.)
If everything else is fine with your notebook, I would suggest you don't bother to avoid making them. You can filter them out to accomplish your goal of avoiding having the Python code in your notebook save them. You can do that by specifying removing those that have an underscore as the first character. (That assumes you have some cases where you assigned dataframes to variables that you just left off what you've shown.)
Illustrative Example of the Suggestion
I'm going to build on my example code here to set up the problem and how it can be remedied after-the-fact. Let's put the following code in a cell and execute it:
import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
input ='''
River_Level Rainfall
0.876       0.0
0.877       0.8
0.882       0.0
0.816       0.0
0.826       0.0
0.836       0.0
0.817       0.8
0.812       0.0
0.816       0.0
0.826       0.0
0.836       0.0
0.807       0.8
0.802       0.0
'''
df_name_one = pd.read_table(StringIO(input), header=0, index_col=None,  delim_whitespace=True)
input ='''
River_Level Rainfall
0.976       0.1
0.977       0.5
0.982       0.0
0.916       0.3
0.926       0.0
0.996       9.0
0.917       0.8
0.912       0.0
0.916       0.0
0.926       0.1
0.836       0.0
0.907       0.6
0.902       0.0
'''
df_name_two = pd.read_table(StringIO(input), header=0, index_col=None,  delim_whitespace=True)
pd.read_table(StringIO(input), header=0, index_col=None,  delim_whitespace=True)

And then in the next Jupyter cell, I run a variation on your code:
All_DFs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
All_DFs = [obj_name for obj_name in All_DFs if not obj_name.startswith("_")]
All_DFs

I'll just see the following output:
['df_name_one', 'df_name_two']

If instead I ran your original code, I'd see:
['_1', 'df_name_one', 'df_name_two']

That '_1' is similar to examples you see among your list. You don't see those if you add in the filter of removing those that start with an underscore.
(If you were doing the collecting from dir() in a for loop like I do in my example code here, incorporating the filter could be simply be done by adding the line if not obj_name.startswith("_"): before the append line.)

Note collecting dataframes this way is a bad idea as was touched on in the comment by matszwecja here. The issue you stumbled upon in your notebook is a good example of why avoiding doing it this way is sage advice. Sure, with some hindsight and understanding you can filter it out; however, you could probably have easily designed in collecting what you need as you went along in order to have clearer, more robust code that was more easily debugged in the development process.
An aside for writing better questions and searching for answers yourself... The fact you are running Python code in a Jupyter notebook was important here yet you say in title only 'Python script' and only have 'Python' and 'Pandas' as categories.


text:
Q: How to pass exception from Server to Client side in GWT RPC I am creating a RPC call using Async method in GWT. I have to check if there is any error on my Server side. Can I catch the exceptions of the server side on the Client side in GWT RPC?

A: The exceptions have to be declared in a throws clause in your RemoteService interface's methods, and have to be serializable by GWT-RPC under the same conditions as any other transported class.
You'll receive the exception in your AsyncCallback's onFailure. See also the javadoc for AsyncCallback.

EDIT: actually, it happens that I just said the same thing that the doc already says: http://www.gwtproject.org/doc/latest/DevGuideServerCommunication.html#DevGuideHandlingExceptions

A: Yes, you can. Just make sure that your exception implements Serializable:
public class LoginException extends Exception implements Serializable {

    public LoginException() {
    }
}


text:
Q: if : $-10if :
$$-10<x<+10\\-70<y<+50\\x+y=40$$
then : What is the range $xy$?
my try :
$$|x|<10\\|y|<70\\x^2<(10^2)\\y^2<(70)^2\\x^2+y^2<(10)^2+(70)^2\\(x+y)^2-2xy<(10)^2+(70)^2\\ \frac{(40)^2-(10)^2-(70)^2}{2}<xy$$
is it right ?

A: To have $xy$ maximal with a given sum you want $x=y$.  Here we can't have that because of the restriction on $x$, so the greatest product we can get is $x=10,y=30,xy=300$.  The most negative product we can get is $x=-10,y=50, xy=-500$, so $$-500 \le xy \le 300$$
You can plot a graph of $xy=x(40-x)$ over the range allowed.


text:
Q: Proof of an inequality involving complex analysis I'm trying to prove : $$\left|\frac{1-\exp\{2\pi i(b-a)\lambda\}}{1-\exp(2\pi i\lambda)}\right|\le \frac{1}{|\sin (\pi \lambda)|}.$$
Expanding the exponentials I'm unable to prove ! Any way to prove this inequality ?

A: Observe
\begin{align}
|1-\exp(2\pi i(b-a)\lambda)| =&\ 2\left|\frac{\exp(\pi i(b-a)\lambda)-\exp(-\pi i(b-a)\lambda)}{2}\right|\\
=&\ 2|\sin(\pi \lambda(b-a))|
\end{align}
then we see that
\begin{align}
\left| \frac{1-\exp(2\pi i(b-a)\lambda)}{1-\exp(2\pi i\lambda)}\right| = \frac{|\sin(\pi\lambda(b-a))|}{|\sin\pi\lambda|} \leq \frac{1}{|\sin\pi \lambda|}.
\end{align}


text:
Q: How to make subpage with new URL for every post automaticly [NodeJS] I have an infinitely scrolling home page that gets posts from a MySQL database with fetch requests and inserts them with javascript.
for(var a = 0; a < reslength; a++){
        html += `<div class="post">`;
            html += `<div class="meta">`;
                html += `<div class="op">` + results[a].username + `</div>`;
                html += `<div class="date">` + results[a].time + `</div>`;
            html += `</div>`;
        html += `<h2 class="post-title">` + results[a].title + `</h2>`;
        html += `<div class="content">`;
            html += `<p class="post-content">` + results[a].content + `</p>`;
        html += `</div>`;

        html += `<div class="attachment-container">...</div></div>`;
        };
        document.querySelector('.container').insertAdjacentHTML('beforeend', JSON.parse(JSON.stringify(html)));
    }

How would I make it so that if you click on the posts it would serve a dedicated page for the post with its own custom URL (the plan is to have replies and stats there).
I'm guessing I need to already have an URL prepared to have it wrapped around the JS? How do you do this automatically for every post?

A: With whatever you are using to host the site, you would handle requests in one function and read the post ID from information passed in the request. You didn't mention the backend web framework you were using, other than that it was NodeJS-based, but this article will explain how you could do it with params and queries in ExpressJS:
https://coursework.vschool.io/express-params-and-query/
Then, to customize the served content, you can use a templating engine like Pug to customize the returned content based on the given post.


text:
Q: Getting Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) I'm trying to follow the react tutorial here: https://www.bezkoder.com/react-hooks-jwt-auth/ and I am getting the Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) error when accessing the Login Page.
Here is my code for the Login Page
import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import Form from "react-validation/build/form";
import Input from "react-validation/build/input";
import CheckButton from "react-validation/build/button";

import AuthService from "../service/auth.service";

const required = (value) => {
  if (!value) {
    return (

        This field is required!

    );
  }
};

const Login = () => {
  let navigate = useNavigate();

  const form = useRef();
  const checkBtn = useRef();

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  const onChangeUsername = (e) => {
    const username = e.target.value;
    setUsername(username);
  };

  const onChangePassword = (e) => {
    const password = e.target.value;
    setPassword(password);
  };

  const handleLogin = (e) => {
    e.preventDefault();

    setMessage("");
    setLoading(true);

    form.current.validateAll();

    if (checkBtn.current.context._errors.length === 0) {
      AuthService.login(username, password).then(
        () => {
          navigate("/profile");
          window.location.reload();
        },
        (error) => {
          const resMessage =
            (error.response &&
              error.response.data &&
              error.response.data.message) ||
            error.message ||
            error.toString();

          setLoading(false);
          setMessage(resMessage);
        }
      );
    } else {
      setLoading(false);
    }
  };

  return (

        <Form onSubmit={handleLogin} ref={form}>

             Username {" "}
            <Input
              type="text"
              className="form-control"
              name="username"
              value={username}
              onChange={onChangeUsername}
              validations={[required]}
            />{" "}

             Password {" "}
            <Input
              type="password"
              className="form-control"
              name="password"
              value={password}
              onChange={onChangePassword}
              validations={[required]}
            />{" "}

            <button className="btn btn-primary btn-block" disabled={loading}>
              {" "}
              {loading && (

              )}{" "}
               Login {" "}
            </button>{" "}

          {message && (

                {" "}
                {message}{" "}

{" "}

          )}{" "}
          <CheckButton style={{ display: "none" }} ref={checkBtn} />{" "}
        </Form>{" "}

{" "}

  );
};

export default Login;

Any idea on how to fix it? Thanks.
enter image description here

A: you can change the part in the screenshot into the code below:

Just change the [] into {}
const {username, setUsername} = useState("");
const {password, setPassword} = useState("");
const [loading, setLoading] = useState(false);
const {message, setMessage} = useState("");

hopefully it works!


text:
Q: check date for variable value I have a variable in my Java class that needs to be set based on whether today is before or after 7/1.  If today is before 7/1 then we are in fiscal year that is the current year (so today we are in FY10).  If today is after 7/1 our new fiscal year has started and the variable needs to be the next year (so FY11).
psuedo code:
if today < 7/1/anyyear then
  BudgetCode = "1" + thisYear(YY)  //variable will be 110
else
  BudgetCode = "1" + nextYear(YY)  //variable will be 111

thanks!

A: Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, Calendar.JULY);
cal.set(Calendar.DATE, 1);

if (cal.after(someDate)) {
  fy = cal.get(Calendar.YEAR) + 1;
}
else {
  fy = cal.get(Calendar.YEAR);
}

A: I think the if statement would be like this to get the 2 digit year with the "1" digit on the front end of it.
if (cal.after(someDate)) {
  BudgetCode = "1".concat(new Integer(cal.get(Calendar.YEAR)%100).toString());
}
else {
  BudgetCode = "1".concat(new Integer(cal.get(Calendar.YEAR)%100).toString());
}


text:
Q: Backbone.js adding to Collection In Backbone, I have a collection which is populated with some JSON data which looks like below.
[
{
    "test1": {
        "fistName": "test",
        "lastName": "example"
    },
    "test2": {
        "fistName": "test",
        "lastName": "example"
    }
},
{
    "test1": {
        "fistName": "test",
        "fistName": "example"
    },
    "test2": {
        "fistName": "test",
        "fistName": "example"
    }
},

]
Currently im trying to add a new model to the collection holding data like the above.
This is the model.
Test = Backbone.Model.extend({
defaults : {
        test1: {
            firstName: null,
            lastName: null
        },
        test2: {
            firstName: null,
            lastName: null
        }
    },

});
Below is what I am trying
var test = new Test({test1: {firstName: $("#test1 option:selected").val(), score: $("#test1lastName").val()}}, {test2: {firstName: $("#test2 option:selected").val(), score: $("#test2lastName").val()}});

myCollection.add(test);

However doing this only populates test1 data and not test2 data. What would be the correct way to add both test1 and test2 data into the model, which could then be added to the collection.
Thanks
UPDATE
Just to clarify, test 1 and 2 are not separate objects, they are relevant to each other and need to be in the same model

A: Edit, depending on how your model is defined, if you format it as below you might able to debug a little better.
var test = new TFS.Test({
    test1: {
        firstName: $("#test1 option:selected").val(),,
        lastName: '', // code for last name?
        score: $("#test1lastName").val()
    },
    test2: {
        firstName: $("#test2 option:selected").val(),
        lastName: '',
        score: $("#test2lastName").val()
    }
});

myCollection.add(test);

I might be able to offer you a little more help if you give a better view of the entire action/process - i.e. what is triggering the creation of these models? Could there be a problem with jQuery, and your document not being ready?


text:
Q: POSTman - Test with custom function throws an assertion error I am doing some test with Postman analysing JSON files. I realised that most of the time I end up making the same test over a bunch of properties, so I decided to make a custom function and add it to the test as a parameter.
Once I do that, whenever an assertion fails it will throw an assertion error instead of failing the test itself. The test won't appear in the Tests Results window.
It works when the assertion is successful though. The test passes and shows in the Test Results window.
It works without a custom function, but in that case, every test will have its own function, with the same line of code, and that's what I wanted to avoid.
function myFunction(propertyName,testData) {
    {
            return pm.expect(testData).to.have.property(propertyName);
    }
}

var data = JSON.parse(responseBody);

var testData = data.entries;
/*TESTS USING CUSTOM FUNCTION*/
for (var i = 0; i < 5; i++) {
    try{
    //This test PASSES and shows in the Test Results window.
        pm.test("test1", myFunction('summonerId',testData[i]));
    }catch(error){
        console.log(error);
    }
    try{
    //This test PRODUCES AN ERROR and DOESN'T shows in the Test Results window.
        pm.test("test2", myFunction('somethingElse',testData[i]));

    }catch(error){
        console.log(error);
    }
 }
/*TESTS USING ONE FUNCTION PER TEST*/
for (var i = 0; i < 5; i++) {

    try{
    //This test PASSES and shows in the Test Results window.
        pm.test("test1", function(){
           pm.expect(testData).to.have.property('summonerId');
        });

    }catch(error){
        console.log(error);
    }
    try{
    //This test FAILS and shows in the Test Results window, without errors
        pm.test("test2", function(){
            pm.expect(testData).to.have.property('somethingElse');
        });
    }catch(error){
        console.log(error);
    }
 }

So when using a custom function, if an assertion is successfull everything is fine and the test is shown as PASSED, BUT if an assertion fails, it throws an error instead of failing the test, and the test is not shown as 'FAILED'.
ASSERTION ERROR:
message: "expected { Object (summonerId, summonerName, ...) } to have property 'somethingElse'"
name: "AssertionError"
showDiff: false
stack: "AssertionError: expected { Object (summonerId, summonerName, ...) } to have property 'somethingElse'
    at myFunction (eval at exec (evalmachine.<anonymous>:13040:2548), <anonymous>:9:52)
    at Object.eval (eval at exec (evalmachine.<anonymous>:13040:2548), <anonymous>:24:30)
    at Uniscope.exec (evalmachine.<anonymous>:13040:2583)
    at module.exports (evalmachine.<anonymous>:69:538)
    at Object.<anonymous> (evalmachine.<anonymous>:72:1871)
    at evalmachine.<anonymous>:16:26
    at Array.forEach (<anonymous>)
    at Object.emit (evalmachine.<anonymous>:15:54)
    at evalmachine.<anonymous>:52:24
    at evalmachine.<anonymous>:5:21"

Total test shows 15 test. 10 PASSED 5 FAILED.
5 test are missing (Those that should FAIL, while using the custom function).
{
    "tier": "CHALLENGER",
    "leagueId": "65ebcd4f-368c-30f6-a635-976beb0e1a8c",
    "queue": "RANKED_SOLO_5x5",
    "name": "Varus's Outriders",
    "entries": [
        {
            "summonerId": "bPZhuLrFtF8ntu6a3JfnYNFX-NfG0LFX7aelPDd2Xegav-MM",
            "summonerName": "dang qiu qian",
            "leaguePoints": 739,
            "rank": "I",
            "wins": 162,
            "losses": 130,
            "veteran": true,
            "inactive": false,
            "freshBlood": false,
            "hotStreak": false
        },
        {
            "summonerId": "gk0lUIs1j9pMAWxa723hurPSDXAGbaXFJRdfek9WfQvWURA",
            "summonerName": "DV1 Matislaww",
            "leaguePoints": 795,
            "rank": "I",
            "wins": 757,
            "losses": 680,
            "veteran": false,
            "inactive": false,
            "freshBlood": false,
            "hotStreak": false
        }
]}

A: I figured it out thanks to @prateeksarda in this post Postman AssertionError when testing using a defined function.
Indeed, the way of calling the function makes a difference.
If instead of calling the function explicitly, we call it in the callback, the result will be correct.
for (var i = 0; i < 5; i++) {

        pm.test("test1", function(){
            myFunction('summonerId',testData[i])
        }); //This test PASSES and shows in the Test Results window.

        pm.test("test2", function(){
            myFunction('somethingElse',testData[i])
        }); //This test FAILS and shows in the Test Results window. :)

 }

This works like a charm.


text:
Q: Reshape 5-dimensional tiled image to 3-dimensional normal image I'm creating a program that takes use of an RGB image that is tiled of the shape (n, n, 3, l, l). n is the number of each tile on each side of the image, and l is the length of each tile in pixels. I am trying to reshape this into a (3, l * n, l * n) shape. An example would be shape (7, 7, 3, 224, 224) to (3, 224, 224).
I want to keep the positions of the pixels in the new matrix, so I can visualise this image later. If I start with an image of a checkerboard pattern (every other tile has all pixel values set to 1, see example below), and use .reshape((3, 224, 224)) the result is the following:

Checkerboard (wanted result)

Wrong way of reshaping
I have made this for loop method of merging the tiles, which works, but is quite slow:
# l: the pixel length of each tile
img_reshaped = torch.zeros((3, 224, 224))
for i in range(len(img)):
    for j in range(len(img[i])):
        img_reshaped[:, i * l:(i + 1) * l, j * 32:(j + 1) * l] = noise[i, j]

I've also tried using .fold(), but this only works with 3D matrices, and not 5D.
Any tips on how to solve this? I feel it should be relatively simple, but just can't wrap my head around it just now.
PS: The code I used to generate the checkerboard:
noise = torch.zeros((7, 7, 3, 32, 32))

for i in range(len(noise)):
    for j in range(len(noise[i])):
        if (i % 2 == 0 and j % 2 != 0) or (i % 2 != 0 and j % 2 == 0):
            noise[i][j] = torch.ones((3, 32, 32))

A: I think you need to transpose before reshape:
n,l=2,3
arr=np.zeros((n,n,3,l,l))

for i in range(n):
    for j in range(n):
        arr[i,j] = (i+j)%2

out= arr.transpose(2,0,3,1,4).reshape(3,n*l,-1)

Output:


text:
Q: Informix Turbo or Online 5.0 for MS-DOS Does anyone recall if there ever was a Turbo or Online 5.0 version for MS-DOS, or was 4.10 the last released DOS version?.. I do know that the 4.10 client  was able to link to Online 5.01 and 6.0 severs on Unix, via I-NET, but unable to leverage SP's and triggers.
I'm trying to locate an Online DOS version, if one exists, so I can leverage VARCHAR's, BLOB's and other Online features not available in SE.

A: There was never an Informix OnLine 5.0 for MS-DOS, AFAICR, nor any later version of Informix products.  Development for MS-DOS stopped before that.
You would not be able to obtain it very easily even if I'm wrong and it once existed (25 years or so ago).  It would only be obtainable on the second-hand market.


text:
Q: How do I match a string with an array element? I have the following:
titles = []
url = []

titles.each do |link|
  if link[:href] =~ 'http://www.google.com'
    url.push(link[:href])
  end
end

But I keep getting a TypeError:
TypeError: type mismatch: String given

P.S. I am trying to use Nokogiri to parse the links returned from a particular URL. If anyone has any links, aside from the Nokogiri tutorial/wiki, about how to best do that, please let me know.

A:
I am trying to use Nokogiri to parse the links returned from a particular URL.

Though Nokogiri makes it easy, there are even easier ways. Ruby's built-in URI has the URI.extract method. From the docs:

Extracts URIs from a string. If block given, iterates through all matched URIs. Returns nil if block given or array with matches.
  Usage

require "uri"

URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
# => ["http://foo.example.com/bla", "mailto:test@example.com"]

You can tell it what schemes to use, so it will only retrieve HTTP or HTTPS or whatever you are looking for.

A: The =~ operator is used for matching Regexp, not strings.

Match—If obj is a Regexp, use it as a pattern to match against str,and
  returns the position the match starts, or nil if there is no match.
  Otherwise, invokes obj.=~, passing str as an argument. The default =~
  in Object returns nil.

http://ruby-doc.org/core-1.9.3/String.html#method-i-3D-7E
This would work, assuming you want to check if http://www.google.com is included in the string :
titles = []
url = []

titles.each do |link|
    if link[:href] =~ /http:\/\/www.google.com/
       url.push(link[:href])
    end
end

A: Seeing from follow-up comments that you really want to search the text portion of all the links, that's definitely something that can be done with Nokogiri. In fact, it can be done with a single XPath expression!
urls = doc.xpath("//a[contains(text(), '#{search_term}')]/@href")

where search_term contains the string you are looking for.
This can be modified to make it case-insensitive. Unfortunately, Nokogiri uses XPath 1.0 so the convenient XPath 2.0 function lower-case() is not available. There is a workaround: the use of translate().
upper = ("A".."Z").to_a.join
lower = ("a".."z").to_a.join
urls = doc.xpath("//a[contains(translate(.,'#{upper}','#{lower}'), '#{search_term.downcase}')]/@href")

A: =~ is used to find if there is regular expression match against a string. If there is a match it returns the index of the match, otherwise returns nil object.
In your following statement both are strings, hence the error.
link[:href] =~ 'http://www.google.com'

It should be something like this
link[:href] =~ /http:\/\/www.google.com/


text:
Q: remove() function is working rudely with animate css I am working with a piece of code that is fixed positioned but the problem is when it's on close, it doesn't animate . The code also uses remove(). But, if I only use animate css it works smooth.
Code block
$(".full-screen-search").addClass('animated zoomOut').delay(1000).remove();

Is there a problem with this code? I can't tell.
The full function is
function searchClose(){
   $(".full-screen-search").addClass('animated zoomOut').delay(1000).remove();
};

I have added delayed function so that it is removed after 1 second after the class has been added.

A: You can't use .remove() chained with other methods.  Try separating them with setTimeout instead:

$(".full-screen-search").addClass('animated zoomOut');
setTimeout(function($(".full-screen-search").remove();), 1000)

A: If you use a javascript callback, it will wait on the function to complete before running said callback. Here is an example:
$(".full-screen-search").hide(1000, function() {
        $(".full-screen-search").remove();
});


text:
Q: OMSDroid - Doesn't load the map. Error: java.io.IOException: Unable to find default handler for protocol: https I have a problem with the OSMDroid libraries. In my application I have a Fragment which should contain a map (OpenStreetMap) and and when I load the page, the map is not displayed.
I went to debug on the library and I discovered that the instruction that goes in error is the following:
if (Configuration.getInstance().getHttpProxy() != null) {
     c = (HttpURLConnection) new URL(tileURLString).openConnection(Configuration.getInstance().getHttpProxy());
} else {
    c = (HttpURLConnection) new URL(tileURLString).openConnection();
}

File: TileDownloard.java - Row: 104
In the row: new URL(tileURLString).openConnection(); - generates the error:
java.io.IOException: Unable to find default handler for protocol: https
The value of tileURLString is: https://b.tile.openstreetmap.org/11/1062/730.png
I tried to follow the instructions on the official OSMDroid page (https://github.com/osmdroid/osmdroid) and I put the instructions in the network_security_config.xml file, but it still doesn't work.
I also tried installing the sample OSMDroid application and it works fine. My Android version is 9.0, but the same problem occurs on a device running Android 7.1. The impression is that my application cannot open the connection using the HTTPS protocol.
Has anyone had a similar mistake? How did he manage to fix it?
Thank you all.
Michele


text:
Q: python, closing loop and slack client I'm listening to the slack channel via slack's RTM API, but when I try to stop listening to it, I get
Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\aiohttp\client_ws.py", line 227, in receive
    msg = await self._reader.read()
  File "C:\Python36\lib\site-packages\aiohttp\streams.py", line 631, in read
    return await super().read()
  File "C:\Python36\lib\site-packages\aiohttp\streams.py", line 591, in read
    await self._waiter
concurrent.futures._base.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\slack\rtm\client.py", line 372, in _read_messages
    message = await self._websocket.receive(timeout=1)
  File "C:\Python36\lib\site-packages\aiohttp\client_ws.py", line 227, in receive
    msg = await self._reader.read()
  File "C:\Python36\lib\site-packages\async_timeout\__init__.py", line 45, in __exit__
    self._do_exit(exc_type)

  File "c:\Users\she jong shon\.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\lib\python\old_ptvsd\ptvsd\_vendored\pydevd\_pydev_bundle\pydev_monkey.py", line 667, in __call__
    ret = self.original_func(*self.args, **self.kwargs)
  File "C:\Python36\lib\threading.py", line 884, in _bootstrap
    self._bootstrap_inner()
  File "C:\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Python36\lib\site-packages\fbs_runtime\excepthook\__init__.py", line 84, in run_with_except_hook
    run_original(*args2, **kwargs2)
  File "C:\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\she jong shon\Desktop\RTC36\src\main\python\main.py", line 303, in start_loop
    self.rtm_client.start()
  File "C:\Python36\lib\site-packages\slack\rtm\client.py", line 198, in start
    return self._event_loop.run_until_complete(future)
  File "C:\Python36\lib\asyncio\base_events.py", line 484, in run_until_complete
    return future.result()
  File "C:\Python36\lib\site-packages\slack\rtm\client.py", line 340, in _connect_and_read
    await self._read_messages()
  File "C:\Python36\lib\site-packages\slack\rtm\client.py", line 374, in _read_messages
    if not self._websocket.closed:
AttributeError: 'NoneType' object has no attribute 'closed'

Basically, I have a button that calls stop() which should stop the rtm_client and exit the thread.
Am I getting errors because I did not properly exit the loop?
import sys
import threading
import asyncio

from slack import RTMClient

from PyQt5 import QtCore, QtWidgets
from main_UI import Ui_ApplicationWindow

class SlackClient(QtCore.QObject):
    textChanged = QtCore.pyqtSignal(str)
    terminated = pyqtSignal()

    def start(self):
        threading.Thread(target=self._start_loop, daemon=True).start()

    def _start_loop(self):
        RTMClient.on(event="message", callback=self.say_hello)
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        slack_token = "xoxb-...."
        self.rtm_client = RTMClient(token=slack_token)
        self.rtm_client.start()

    def say_hello(self, **payload):
        data = payload["data"]
        if data:
            if "text" in data:
                text = data["text"]
                self.textChanged.emit(text)

    def stop(self):
        self.rtm_client.stop()
        self.terminated.emit()

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_ApplicationWindow()
        self.ui.setupUi(self)

        self.client = SlackClient()
        # connections
        self.ui.pushButton.clicked.connect(self.client.start)
        self.ui.stopButton.clicked.connect(self.client.stop)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    myWindow = ApplicationWindow()
    myWindow.show()
    sys.exit(app.exec_())


text:
Q: Ruby HERE-DOC method parameter passing I am trying to use a custom method with here-doc and want to pass parameter (there is no business case, I am merely trying to learn ruby). Is there a way to pass parameter in this case?  This is what I have so far.
Simple method, just works fine.
def meth1
  self.upcase
end

str1 = <<MY.meth1
  i am a small case string
MY

# "I AM A SMALL CASE STRING\n"

Now, I thought let us drop some parameters and tried different variations and irb gives me a blank stare.
#variation 1

def meth2( <<EOF1, <<EOF2 )
  EOF1.upcase + "..." + EOF2.downcase
end

str2 = <<MY.meth2
 some string
EOF1
 ANOTHER STRING
EOF2
MY

A: try something along the lines of
something = "bananas"

str = <<EOF
  this has some #{something} in!
EOF

A: Try something like this:
def meth2( item1, item2 )
  item1.upcase + "..." + item2.downcase
end

str2 = meth2 <<EOF1, <<EOF2
 some string
EOF1
 ANOTHER STRING
EOF2

The problem you are having is due to not fully understanding how heredoc-style string literals work. The <<DELIMITER part just is telling the parser to get it's string data from the lines that follow it. If there is more than one <<DELIMITER on a line, then they stack, and are read in in sequence. So, in this case, the code above is exactly equivalent to:
def meth2( item1, item2 )
  item1.upcase + "..." + item2.downcase
end

str2 = meth2 " some string\n", " ANOTHER STRING\n"

Most importantly, there is no way to build a heredoc into a function like you were trying to do there... They can only be used in the same places and manner that other String literals, such as "double quoted" or 'single quoted' literals, can be used.

A: My guess is that this is what you are trying to do:
def meth2(str1, str2)
  str1.upcase + "..." + str2.downcase
end

str2 = meth2(<<EOF1, <<EOF2)
 some string
EOF1
 ANOTHER STRING
EOF2

str2 # => " SOME STRING\n... another string\n"

If you don't intent to indent, see here. ← See my play with words here?