text:
Q: How to check if the last character in a string is a certain character and remove it from string? (C++) I have this function to return whether the specified directory exists:
double directory_exists(char *pathname)
{
    struct stat sb;
    return (stat(pathname,&sb) == 0 &&
            S_ISDIR(sb.st_mode));
}

However, if the last character the user typed is a slash ("\" on Windows or "/" on Mac / Linux) I'd like to remove that character from the pathname and store that value in a new variable and use that variable in stat() instead of pathname.
stat() will think the path doesn't exist if there just so happens to be a slash at the end, and since some people, (not everyone), do think to put a slash at the end of their pathname, I'd like to cater to that by detecting whether they used a slash at the end and then remove it.
I'm looking for a portable solution for Windows / Mac / Linux.
Thanks!

A: I found a solution. I think I should've searched more before asking here.
double directory_exists(char *pathname)
{
    std::string str(pathname);
    if (!str.empty())
    {
        while (*str.rbegin() == '\\' || *str.rbegin() == '/')
        {
            str.erase(str.size()-1);
        }
    }

    struct stat sb;
    return (stat((char *)str.c_str(),&sb) == 0 &&
            S_ISDIR(sb.st_mode));
}

What's nice about this approach is that it doesn't require C++11, unlike string::back() and string::pop_back().


text:
Q: Weird things happening when using ImageGrab.grab() I have some code:
from tkinter import *
from tkinter import *
from PIL import Image, ImageGrab

root = Tk()

def capture():
    x0 = canvas.winfo_rootx()
    y0 = canvas.winfo_rooty()
    x1 = x0 + canvas.winfo_width()
    y1 = y0 + canvas.winfo_height()

    im = ImageGrab.grab((x0, y0, x1, x2))
    im.save('mypic.png')  # Can also say im.show() to display it

canvas = Canvas(root, bg='red')
canvas.pack(padx=10, pady=10)

e = Entry(root)

canvas.create_window(canvas.canvasx(100), canvas.canvasy(100), window=e)

Button(root, text='Click a pic', command=capture).pack()

root.mainloop()

It makes mypic:

Which is part of my background
But i want it to make:
Which is a screenshot of my screen.
I tried changing other parameters like include_layeder_windows, but it didn't change anything.
My problem is that grab() returns my background instead of my screen.

A: It seems you're using Mac OS. In Mac, an application by default cannot grab contents of other application's window. When trying to do so, it will grab the desktop background only. This could perhaps be observed e.g. when sharing screen over e.g. Zoom, without giving Zoom proper permissions.
To fix that, you need to go to "System Preferences" > "Privacy" > "Privacy" > "Screen Recording" and add your application there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Web application cannot start. Ruby On rails I got an issue with starting Ruby application.
I got Ubuntu 14.04,  Apache/2.4.7, ruby 2.2.5p319 and some Web Apllication installed on.
When I try to go to application page, i see the exception and a trace in my browser.

      Web application could not be started

        cannot load such file -- bundler/setup (LoadError)
        /usr/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        /usr/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:245:in
        `block in run_load_path_setup_code'
        /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:348:in
        `running_bundler'
        /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:243:in
        `run_load_path_setup_code'
        /usr/share/passenger/helper-scripts/rack-preloader.rb:100:in `preload_app'
        /usr/share/passenger/helper-scripts/rack-preloader.rb:158:in `'
        /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in
        `'
        /usr/share/passenger/helper-scripts/rack-preloader.rb:28:in

Also environmet variables:

    APACHE_PID_FILE = /var/run/apache2/apache2.pid
    SHELL = /bin/bash
    APACHE_RUN_USER = www-data
    PASSENGER_DEBUG_DIR = /tmp/passenger.spawn-debug.XXXXybOMMs
    USER = appuser
    APACHE_LOG_DIR = /var/log/apache2
    PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    PWD = /var/app
    APACHE_RUN_GROUP = www-data
    LANG = C
    NODE_PATH = /usr/share/passenger/node
    SHLVL = 0
    HOME = /home/appuser
    LOGNAME = appuser
    APACHE_LOCK_DIR = /var/lock/apache2
    APACHE_RUN_DIR = /var/run/apache2
    IN_PASSENGER = 1
    PYTHONUNBUFFERED = 1
    RAILS_ENV = production
    RACK_ENV = production
    WSGI_ENV = production
    NODE_ENV = production
    PASSENGER_APP_ENV = production
    SERVER_PROTOCOL = HTTP/1.1
    SERVER_ADDR = x.x.x.x
    REMOTE_ADDR = y.y.y.y
    REQUEST_URI = /
    SSL_TLS_SNI = myaddr.com
    HTTPS = on
    SERVER_PORT = 443
    SERVER_NAME = myaddr.com
    SERVER_SOFTWARE = Apache/2.4.7 (Ubuntu)
    SERVER_ADMIN = youremail@example.com
    REMOTE_PORT = 51589
    DOCUMENT_ROOT = /var/myapp/public
    QUERY_STRING =
    REQUEST_METHOD = GET

    RUBY_VERSION = 2.2.6
    RUBY_PLATFORM = i386-linux-gnu
    RUBY_ENGINE = ruby
    RubyGems version = 2.4.5.2

It seems that some parts of Ruby's previous version still has influence to the WebApp, but I can't find where to correct it.
Thanks.


text:
Q: What does "computably enumerated in increasing order" mean? Some people used the terms "computably enumerated in increasing order". But I can't find formal definition about it.
Computably enumerable set means that range of some total computable function. So I think that the set $S$ is computably enumerated in increasing order iff there exists total computable function $f:A \rightarrow S$ such that for $a,b\in S$, $a<b$ implies $f(a)\leq f(b)$. But I have two questions if my definition is right.

*

*Can we always think $A$ is subset of $N$?

*How to define the order in arbitrary computably enumerable set $S$?


text:
Q: Can servers with encrypted root filesystems be made reasonably highly available? I have some servers I'd like to keep on encrypted disks, but I don't want to have to manually type a passphrase at every boot.  I also don't want to keep the key on the machine unencrypted.  TPM would be a natural fit here, but what if someone steals the entire machine?
What if I set up a "cluster" of sorts, where each machine only stored the other machine's keys on something that was encrypted at rest?  So now, only if all the machines in the cluster were offline at the same, a passphrase would be manually supplied, but only on one of the machines.
Each node would have an initramdisk with a dropbear instance and couple of scripts that would:

*

*Try detecting other nodes in the cluster.

*Send some request to the other node to turn around and log in via ssh, and supply the key for the local root filesystem.

*If no hosts are in the cluster, or no hosts have the appropriate ssh key, prompt for a passphrase.

This way, no keys are stored unencrypted anywhere, and I can reboot all my servers, so long as at least one stays up at a given time.  If they're all down at once, I have to type a password.
Would this be an secure solution?  If not, could the basic idea be modified to be made a secure solution?
(Also, is there an existing name for this type of setup?)

A: This is only a partial answer, but have you looked into arver? Arver is a tool to manage LUKS-encrypted disks on different systems by different people.


text:
Q: Laravel download pdf file stored in separate Laravel app I have 2 Laravel(5.8) apps.  One is a user application, the other is more of an API.
The Api has pdfs stored in the storage directory, I need to be able to allow a user to download the pdfs in the other application.
Really got no clue how to send the file over from app to the other.
The user app makes an api to the api with relevant file ids and things (fine), just can't work out how to send the file back, and then download it on the other end.
Tried things like return response()->stream($pdf) on the api and return response()->download($responeFromApiCall) and loads of other things but really getting nowhere fast.
Any advice welcome.

A: The laravel code you posted is basically correct, you can use one of stream(), download() or file() helper to serve a file.
file()
Serve a file using a binary response, the most straightforward solution.
// optional headers
$headers = [];
return response()->file(storage_path('myfile.zip'), $optionalHeaders);

You can also use your own absolute file path instead of the storage_path helper.
download()
The download helper is similar to file(), but it also sets a Content-Disposition header which will result in a download-popup if you retrieve the file using your browser.
$location = storage_path('myfiles/invoice_document.pdf');
// Optional: serve the file under a different filename:
$filename = 'mycustomfilename.pdf';
// optional headers
$headers = [];
return response()->download($location, $filename, $headers);

stream()
The stream() helper is a bit more complex and results in reading and serving a file in chunks. This can be used for situations where the filesize is unknown (like passing through another incoming stream from an API). It results in a Transfer-Encoding: chunked header which indicates that the data stream is divided into a series of non-overlapping chunks:
// optional status code
$status = 200;
// optional headers
$headers = [];
// The stream helper requires a callback:
return response()->stream(function() {
    // Load a file from storage.
    $stream = Storage::readStream('somebigfile.zip');
    fpassthru($stream);
    if(is_resource($stream)) {
        fclose($stream);
    }
}, $status, $headers);

Note: Storage::readStream takes the default storage disk as defined in config/filesystems.php. You can change disks using Storage::disk('aws')->readStream(...).

Retrieving your served file
Say your file is served under GET example.com/file, then another application can retrieve it with curl (assuming PHP). A popular wrapper for this would be Guzzle:
$client = new \GuzzleHttp\Client();
$file_path = __DIR__ . '/received_file.pdf';
$response = $client->get('http://example.com/file', ['sink' => $file_path]);

You can derive the filename and extension from the request itself by the way.
If your frontend is javascript, then you can retrieve the file as well but this another component which I dont have one simple example for.

A: So if I understand correctly you have two systems: user app and api. You want to serve a pdf from user app to the actual user. The user app does a call to api, which works fine. Your issue is converting the response of the api to a response which you can serve from your user app, correct?
In that case I'd say you want to proxy the response from the api via the user app to the user. I don't know what the connection between the user app and the api is, but if you use Guzzle you could look at this answer I posted before.

A: Here are the steps you should follow to get the PDF:

*

*Make an API call using AJAX ( you are probably already doing it ) from your public site ( User site ) to the API server, with file ID.

*API server fetches the PDF, copy it to the public/users/ directory, generate the URL of that PDF file.

*Send the URL as a response back to the User site. Using JS add a button/ link in the DOM, to that PDF file.
Example:
jQuery.post(ajaxurl, data, function(response) {
var responseData = JSON.parse(response);
var result = responseData.result;
var pdf_path = responseData.pdf_path;
$(".nametag-loader").remove();
$(".pdf-download-wrapper").append("Download");

});


text:
Q: AWS Canary Deployments of Lambda Functions using API GW Stage I've searched for days trying various things I've found on the web including AWS's docs, but I'm still struggling with Canary Deployments. Ultimately we'd like to orchestrate the deployments using Terraform and AWS CLI as needed - but for now I'm just trying to get canary working manually via AWS Console (with AWS CLI as needed).
First step

*

*I have an API GW setup

*lambda function hooked into the stage

*canary is not enabled in stage

*The Lambda Function in the Integration Request for the method has no version or alias to the lambda (just the name of the lambda function)
*** Lambda returns the latest response ***

Second step

*

*I enable canary via Console in API GW Stage.

*I update the Integration Request -> Lambda Function by adding the current lambda version.

*I "Deploy API" in API GW.
I see the stage and canary deploymentIds are the same.
I believe at this point the latest deployment (which includes the latest lambda version and everything else in API GW settings) is saved as both the latest deployed version and the "non-canary"/"previous"/"prod" version.
*** Lambda return the latest response *** which I believe is OK since I haven't deployed a change to the lambda since enabling canary.

Third step

*

*I change the lambda function to return a different value

*I hit "Deploy" to push the changes to the lambda function

*I then "Publish new version"

*At this point I assume I need to go back to API GW -> Integration Request and update to the latest version in the "Lambda Function" field

*And now "Deploy API"
Now I'm assuming the previous deployment is still the prod/previous/non-canary version and the deploy that just happened is the canary version with all the latest code, versions, API GW settings, etc.

Now here's where things get tricky:
If I set Canary percentage to 10% I expect to see 10% of the responses from the API to have the latest response and 90% to the previous version's response - however it is flipped and I'm getting 90% canary responses. If I change the Canary percentage to 90% in API GW -> Stage -> Canary, when testing I average 10% with the latest response.
I'd rather avoid using lambda aliases or stage variables if possible (to keep thing simple). I'm assuming that canary is flipping between 2 deployment snapshots and the latest deployment is the canary. If that is correct, I don't need to use a stageVariable in the "Integration Request -> Lambda Function" to map to the version. And since I'm not trying to do canary via Lambda traffic splitting - I don't need to make lambda aliases.
I've also tried most of the above steps with AWS CLI commands (except modifying the Lambda function code and creating the new lambda version). This yielded similar results.
I'm not trying to get fancy here yet. No CloudFormation, CodeDeploy, Terraform, etc. Automation is the next step once I can get my head around how the API GW level canary works. I'm not trying to do blue green canary either.
Thanks! Looking forward to seeing that it is something obvious/simple to fix. ;)


text:
Q: Python split string retaining the bracket I would like to split the string and eliminate the whitespaces such as
double a[3] = {0.0, 0.0, 0.0};

The expected output is
['double', 'a', '[', '3', ']', '=', '{', '0.0', ',', '0.0', ',', '0.0', '}', ';']

How could I do that with re module in Python?

A: You can make use of the fact that re.split() retains delimiters in capture groups in the output:
import re
input_string = "double a[3] = {0.0, 0.0, 0.0};"
bits = [bit for bit in (bit.strip() for bit in re.split(r'((?:\d+\.\d+)|[,}=;]|\w+)', input_string)) if bit]
expected = ['double', 'a', '[', '3', ']', '=', '{', '0.0', ',', '0.0', ',', '0.0', '}', ';']
assert bits == expected

A: One approach here might be to use re.findall:
inp = "double a[3] = {0.0, 0.0, 0.0};"
parts = re.findall(r'\d+(?:\.\d+)?|\w+|[^\s\w]', inp)
print(parts)

# ['double', 'a', '[', '3', ']', '=', '{', '0.0', ',', '0.0', ',', '0.0', '}', ';']

The regex pattern used here says to match:

*

*\d+(?:\.\d+)? an integer or float

*| OR

*\w+ a word (such as "double")

*| OR

*[^\s\w] a single non word non whitespace (such as {)

A: Solution without re:
from itertools import groupby

s = "double a[3] = {0.0, 0.0, 0.0};"
delimiters = r"[]{};,"

out = []
for word in s.split():
    for k, g in groupby(word, lambda v: any(d in v for d in delimiters)):
        if k:
            out.extend(list(g))
        else:
            out.append("".join(g))

print(out)

Prints:
['double', 'a', '[', '3', ']', '=', '{', '0.0', ',', '0.0', ',', '0.0', '}', ';']


text:
Q: Conditional locking based on value I am writing a web service that allows users to create jobs within the system. Each user has an allowance of the number of jobs they can create. I have a method which checks that the user has some remaining credits which looks like this:
private bool CheckRemainingCreditsForUser(string userId)
{
    lock(lockObj)
    {
       var user = GetUserFromDB(userId);
       if (user.RemaingCredit == 0) return false;
       RemoveOneCreditFromUser(user);
       SaveUserToDB(user);
    }
}

The problem I can see with this approach is that if multiple different users make a request at the same time they will only get processed one at a time which could cause performance issues to the client. Would it be possible to do something like this?
private bool CheckRemainingCreditsForUser(string userId)
{
    //If there is a current lock on the value of userId then wait
    //If not get a lock on the value of userId
    var user = GetUserFromDB(userId);
    if (user.RemaingCredit == 0) return false;
    RemoveOneCreditFromUser(user);
    SaveUserToDB(user);
    //Release lock on the value of userId
}

This would mean that requests with different userIds could be processed at the same time, but requests with the same userId would have to wait for the previous request to finish

A: Yes, you could do that with a Dictionary<string, object>. To link a lockObject to every userId.
The problem would be cleaning up that Dictionary every so often.
But I would verify first that there really is a bottleneck here. Don't fix problems you don't have.
The alternative is to have a (optimistic) concurrency check in your db and just handle the (rare) conflict cases.

A: Instead of locking in every methods, why aren't you using a Singleton that will manage the User's rights ?
It will be responsible from giving the remaining allowances AND manage them at the same time without loosing the thread-safe code.
By the way, a method named CheckRemainingCreditsForUser should not remove allowances since the name isn't implying it, you may be the only developer on this project but it won't hurt to make 2 methods to manage this for re-useability and code comprehension.
EDIT : And this object should also hold the Users dictionary


text:
Q: Could not execute statement SQL Grammar Exception Here is my entity class.
@Entity
public class Store implements Serializable {

    private static final long serialVersionUID = 1L;

    public Store() {
    }

    @Id
    private int id;
    private String code;
    private String password;
    private String forgetPasswordNote;
    private String key;
    private String ownerId;
    private String storeLink;
    private String activationCode;
    private String name;
    private String homepageUrl;
    private String sessionToken;
    private Date dateCreated;
    private Date expireDate;
    private Date lastModified;
    private String nmPassword;
    private String storeType;
    private String premium;
    private double money;
    private boolean refreshed;
    private String country;
    private String lang;
    private String varId;
    private String fbPageId;
    private boolean fbEnabled;
    private boolean informative;
    private boolean active;
    private String fbEnabledBy;
    private String ipAddress;
    private String comments;
    private float commission;
    private String picasaEmail;
    // all getter and setter goes here

}

Here is my controller
@Controller
public class RegController {
    @RequestMapping(value =  "/create/database")
    public String createDatabase(ModelMap map, HttpServletRequest request) {
        Store store = new Store();
        store.setId(1);
        store.setCode("1");
        System.out.println("test worl");
        @SuppressWarnings("deprecation")
        SessionFactory sessionFactory = new Configuration().configure()
                .buildSessionFactory();
        try {
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            session.save(store);
            session.getTransaction().commit();
            session.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return "home";
    }
}

When I run the url localhost:8080/MyApp/create/database I am getting and error. org.hibernate.exception.SQLGrammarException: could not execute statement
Is there any reserved keyword on my entites class?

A: I have found the solution key is reserved keyword on mysql database so I simply change the key to storekey and everything work fine.


text:
Q: React Native : how to make a value counter into textinput use formik I got stuck here ,
I needed to make a counter into the textinput ,
and I realize ,the counter has conflict with the handleChange.
I have no idea how to modify it ,could you please take a look at my code ?Thank you so much in advance !!

import { StyleSheet,  View } from 'react-native'
import React from 'react'
import AppForm from '../components/AppForm'
import * as Yup from 'yup'
import AppFormFieldWithCount from '../components/AppFormFieldWithCount';

const validationSchema = Yup.object().shape({
 userName: Yup.string().required("Username can't be empty").label("Username"),
});
const EditScreen = () => {
  const handleSubmit = async (userInfo) => {
    console.log("receive information",userInfo);
   };
  return (
    <View style={styles.container}>
  {/**  <TextInputWithCount number={12} maxLength={12} multiline={false} placeholder={"用户名"}/> */}
  <AppForm
  initialValues={{userName:''}}
  validationSchema ={validationSchema}
  onSubmit = {handleSubmit}
  >
  <AppFormFieldWithCount
  name = {'userName'}
  number ={15}
  placeholder={"Username"}
  maxLength ={15}
  multiline={false}
  />

  </AppForm>

    </View>
  )
}

export default EditScreen

const styles = StyleSheet.create({
  container:{
    padding:30,

  }
})

Below ,it is the formik TextInput :
I have added the setValue for counting the text ,but the textinput will need the handleChange for getting the textinput information .Therefore, it has the conflict here, only one of them works in onChangeText function ...
import { StyleSheet, Text, View,TextInput} from 'react-native'
import React,{useState} from 'react'
import TextInputWithCount from './TextInputWithCount'

    import AppErrorMessage from './ErrorMessage'
    import { useFormikContext } from 'formik';
    import colors from '../config/colors';

    const AppFormFieldWithCount = ({name,number,maxLength,multiline,placeholder,...otherProps}) => {
        const {setFieldTouched,handleChange,errors,touched} = useFormikContext();
        const[value,setValue] = useState('');
      return (
       <>
        <View style={styles.container}>
       <TextInput placeholder={placeholder}
         style={{flex:1,fontSize:18}}
         placeholder = {placeholder}
         multiline={multiline}
         maxLength={maxLength}
         onBlur = {()=>setFieldTouched(name)}
         onChangeText = {
          handleChange(name)
         }
         {...otherProps}
          />
         <Text>{value === "" ? "0" : value.length}/{number}</Text>
         </View>
     <AppErrorMessage error={errors[name]} visible={touched[name]} />
       </>
      )
    }

    export default AppFormFieldWithCount

    const styles = StyleSheet.create({
      container:{
        flexDirection:'row',
        borderRadius:5,
        borderWidth:1,
        borderColor:colors.medium,
        alignItems:'center',
        width:'100%',
        paddingHorizontal:10,

    }
    })


text:
Q: active_storage_drag_and_drop does not work on rails - Error: reject delegated to attachment, but attachment is nil I'm currently trying to implement the drag and drop feature to upload images using this: https://github.com/marinosoftware/active_storage_drag_and_drop
I followed all the steps and did all the gem install and included the require in my js and scss files. I have also gem install active storage before installing 'active_storage_drag_and_drop' gem.
It is working fine with the default active storage upload when is file_field:
                            <%= form_with(model: @work_order, local: true) do |form| %>
                                <%= form.file_field :image %>
                            <% end %>

However, when I changed to drag_and_drop_file_field instead:
                            <%= form_with(model: @work_order, local: true) do |form| %>
                                <%= form.drag_and_drop_file_field :image %>
                            <% end %>

The error:
[ERROR] Exception ActionView::Template::Error: reject delegated to attachment, but attachment is nil
Anyone have any idea on solving this issue? Thank you.
Version:
Rails 5.2.2, ruby 2.6.6p146 (2020-03-31 revision 67876) [x64-mingw32] and mysql2 (0.5.3)
Update 1:
Controller (for def new only):
class WorkOrdersController < ApplicationController
layout :resolve_layout, except: [:feedback, :completed_feedback, :sending_feedback]
before_action :normal_user
before_action {authorisation_for_modules("Work Orders Management")}

    def new

    initialise

    @work_order = WorkOrder.new
    @countries = Country.all
    @branches = Branch.all

end

Model:
    class WorkOrder < ApplicationRecord
#has_many :workorders, dependent: :destroy
belongs_to :branch
has_one_attached :image
end

Partial of full error:
  Rendered work_orders/new.html.erb within layouts/developers (334.9ms)

[ERROR] Exception ActionView::Template::Error: reject delegated to attachment, but attachment is nil, ["C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-5.2.2/lib/active_support/core_ext/module/delegation.rb:278:in rescue in method_missing'", "C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activesupport-5.2.2/lib/active_support/core_ext/module/delegation.rb:274:in method_missing'", ......


text:
Q: Algebra Ages Question GCSE I need help to work out this algebra question.
Question:
Ram's Daughter's Age in 3 years will be the square of her age 3 years ago.
How old is she now?
What I did:
algebraically:
x+3 is daughters age in 3 years
x-3 age years ago
x+3 = (x-3)(x-3)
   x-3 = 0
   x=3

x = 3 so her age now is 3 years old?
On the mark scheme it said the answer was 6 but it didn't show the working so please can someone try this question and tell me what I did wrong.
Thank You and Help is Appreciated

A: Your setup of
$$x + 3 = (x - 3)(x - 3)$$
is correct, but I have no idea how you concluded that $x - 3 = 0$ from this. I guess that you tried setting the factors on the right equal to zero, but there is no reason to here... their product is $x + 3$, not zero. Rather, expand and collect terms:
$$x^2 - 6x + 9 = x + 3 \iff x^2 - 7x + 6 = 0 \iff (x - 6)(x - 1) = 0.$$
So now it is valid to set each of the factors to zero, and so either $x = 6$ or $x = 1$. The latter solution doesn't make sense, so $x = 6$.


text:
Q: How to execute python script from a shell script using Nifi "ExecuteProcess" processor? I am trying to execute a python script through a shell script using the "ExecuteProcess" processor. I could find shell command inside the shell script is working, but the python script is not getting executed. When I execute the shell script manually python script and shell command both are getting executed. What change should I make to execute the python script using the "ExecuteProcess" processor.

A: It worked after setting the working directory property with the path where the shell script is present.


text:
Q: PHP code to get the json output in the following format Hi i have written an android app which interacts with php to get data from the database.
I need the json to return the data back in this format.
[
    {
        "outlet_id"    :"1",
        "outlet_desc"  :"BigBazaar",
        "outlet_loc"   :"Jayanagar4thBlock",
        "outlet_image" :"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FBigBazaar.png",
        "recommended_products": [
                                    {
                                        "item_id":"3",
                                        "item_desc":"Dettol",
                                        "item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
                                    }
                                ]
    },
    {
        "outlet_id":"2",
        "outlet_desc":"FoodWorld",
        "outlet_loc":"Basavanagudi",
        "outlet_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FFoodWorld.png","
        recommended_products":[
                                {
                                    "item_id":"3",
                                    "item_desc":"Dettol",
                                    "item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"
                                },
                                {
                                    "item_id":"3",
                                    "item_desc":"Colgate",
                                    "item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FColgate.png"
                                }
                              ]
    },
    {
        "outlet_id":"5",
        "outlet_desc":"Total",
        "outlet_loc":"MurgeshPalaya",
        "outlet_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FTotal.png",
        "recommended_products":[
                                {
                                    "item_id":"3",
                                    "item_desc":"Dettol",
                                    "item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FDettol.png"

                                },
                                {
                                    "item_id":"3",
                                    "item_desc":"Colgate",
                                    "item_image":"http%3A%2F%2Flocalhost%2FFlutura%2FPHP%2FAssets%2Fimages%2FColgate.png"

                                }
                               ]
     }
]

But right now it is giving in the following format.
[
    [
        {
            "outlet_id": "1",
            "outlet_name": "Big Bazaar",
            "lat": "12.9285690",
            "lng": "77.5831100",
            "outlet_image": "images/BigBazaar.png",
            "outlet_location": "Jayanagar 4th Block"
        }
    ],
    [
        {
            "outlet_id": "2",
            "outlet_name": "Food World",
            "lat": "12.9392350",
            "lng": "77.5780680",
            "outlet_image": "images/FoodWorld.png",
            "outlet_location": "Basavanagudi"
        }
    ],
    [
        {
            "outlet_id": "5",
            "outlet_name": "Total",
            "lat": "12.9589340",
            "lng": "77.6571610",
            "outlet_image": "images/Total.png",
            "outlet_location": "Murugeshpalya"
        }
    ],
    [
        {
            "outlet_id": "6",
            "outlet_name": "Big Bazaar",
            "lat": "12.9324963",
            "lng": "77.6228463",
            "outlet_image": "images/BigBazaar.png",
            "outlet_location": "Koramangala"
        }
    ],
    [
        {
            "outlet_id": "7",
            "outlet_name": "Food World",
            "lat": "12.9785055",
            "lng": "77.6379353",
            "outlet_image": "images/FoodWorld.png",
            "outlet_location": "Indira Nagar"
        }
    ]
]

This is my php code.
<?php
error_reporting(0);

//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
//$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT * FROM outlets";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

while($row = mysql_fetch_assoc($result))
{
  $output[] = array($row);
}
print( json_encode($output) );
?>

How can i modify the above php code to return in the 1st format. Please help as i am not so good in php.
Table Structure.
Outlets Table.
It contains the following fields.
outlet_id    outlet_name    lat    lng    outlet_image    outlet_location
Recommendations table.
It contains the following fields.
item_id    outlet_id
Items table.
It contains the following fields.
item_id    item_name    item_image    item_price    category_id

A: Ok so it's the missing sub-array. You want to create a JSON string, not a object, from a multidimensional associative array.
There are faster ways to select these rows but this is easy to follow.
$query = "SELECT * FROM outlets";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

$output=array(); # don't leave it undefined
while($row = mysql_fetch_assoc($result))
{
    # guessing this query
    $query2 = "SELECT * FROM recommended_products WHERE outlet_id=".$result['outlet_id'];

    # now we create the sub array recommended_products
    $row['recommended_products']=array();
    $result2 = mysql_query($query2) or die("Unable to verify user because : " . mysql_error());
    while($row2 = mysql_fetch_assoc($result2)){
        $row['recommended_products'][]=$row2;
    }

    # then add the modified row to the output
    $output[] = $row;
}
print( json_encode($output) );

Also, mysql_ is depreciated. Probably no genuine need to rush but it's worth at least looking at converting to mysqli or PDO.

A: Change $output[] = array($row); to $output[] = $row;


text:
Q: How do I transcribe an AppleScript? I found an AppleScript example on a website that I want to use, and the example is rendered as text in the browser (vs., say, being a suitably formatted file to download).
To use this AppleScript, I'm assuming that I need to use Automator somehow to create a Workflow (or perhaps an Application), but I can't figure out the right way to paste the AppleScript (or otherwise enter free-form text) into Automator.
I tried dragging a Run AppleScript action into the workflow window and then pasting the the AppleScript there, and (after I cleaned-up the smart quotes) I was able to use the Run button to execute it from within Automator. Though it popped up a warning about not receiving input while running inside Automator, the AppleScript seemed to execute correctly (i.e., I ended up with the right result). But it seems like this might not be the correct/efficient way to do this transcription (and/or it will result in an inefficient AppleScript).
Is there some way to open a free-form text window in Automator to type in an AppleScript?  Or is there some other way (other than trying to figure out each Action to drag into the workflow window and modify accordingly) to transcribe an AppleScript?
Corroborating my suspicions of inefficiency, I see that the resulting Application bundle/directory has a file called Contents/document.wflow and within that is the free-form pasted text as an ActionParameters member of Run AppleScript -- and this presumably will need to be parsed at every runtime.
I'm using Automator 2.7 on MacOS 10.12.6

A: You might be making this more complicated than it needs to be. If you want the code from the other site in an applescript, that page provides guidance. You don't need Automator to simply run that script.
Copy the script text onto the clipboard. Launch the Script Editor. It should open a new and empty document. Paste the copied script. The text should appear as whatever your default is for new (or uncompiled) text, e.g. probably in a purple monospaced font.
Confirm that everything is hunky dory by compiling the script: Type Command-K (or from the menus: Script > Compile). It should take on the same appearance as what you saw on the other site, e.g. some words coloured or bolded (emboldened?). Depending upon whatever, you may find that the quotation marks have been altered and you get an error. They need to be straight double quotation marks, e.g. "" and not "".
Then try it out. If it works as desired, save it somewhere easy to access, e.g. the Safari scripts folder. Then, if you have the Script menu enabled (check the box in the Script Editor General preferences), you will be able to run the script from the script icon that shows up on the right end of the menu bar (near the clock) whenever Safari is the active app.
/Users/username/Library/Scripts/Applications/Safari

NB I'd suggest saving it as a script (as opposed to application) unless you have a specific need that requires that.

A: I found that just copy / paste into a new automator window then save worked for me


text:
Q: Python 3 | Mutithreading starts before thread.start() is decleared Trying to have 2 methods running at once. One is a timer method and the other writes data to a CSV. I am trying to use Treading to run them both at once, but the thread starts before it is called.
Code;

 with open("C:\\ProgramData\\Example.txt", "r", encoding="utf8") as file:
        array = for line in file.readlines()]))

    fieldnames = 'Col1','Col2','Col3'
    with open("C:\\ProgramData\\example.csv", 'w', newline='', encoding="utf8") as csvfile:
     writer = csv.writer(csvfile)
     writer.writerow(fieldnames)
     writer.writerows(array)
     csvfile.close()

def timer():
    import time
    import sys

    time_start = time.time()
    seconds = 0
    minutes = 0

    while True:
        try:
            sys.stdout.write("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds))
            sys.stdout.flush()
            time.sleep(1)
            seconds = int(time.time() - time_start) - minutes * 60
            if seconds >= 60:
                minutes += 1
                seconds = 0
        except KeyboardInterrupt as e:
            break

if __name__=="__main__":
    print("Not running")
    t1 = threading.Thread(target=timer())
    print("clearly running")
    t2 = threading.Thread(target=regx())
    t1.setName('t1')
    t2.setName('t2')

    t1.start()
    t2.start()

    t1.join()
    t2.join()
  # pool =Pool(processes=2)
  # pool.map(timer(),regx())

The output from the console;
Not running
2 Minutes 32 Seconds
Process finished with exit code -1

Can anyone help me fix this?
Thanks

A: Don't use () unless you want to run the method immediately. If you want to reference the method itself (like to pass it to Thread), leave off the ().
Try this code:
if __name__=="__main__":
    print("Not running")
    t1 = threading.Thread(target=timer)
    print("clearly running")
    t2 = threading.Thread(target=regx)
    t1.setName('t1')
    t2.setName('t2')

    t1.start()
    t2.start()

    t1.join()
    t2.join()


text:
Q: Creating matplotlib legend with dynamic number of columns I would like to create a legend in matplotlib with at max 5 entries per column. Right now, I can manually set the number of columns like so:
leg = plt.legend(loc='best', fancybox=None, ncol=2)

How do I modify this so that at most 5 entries are allowed per column?

A: There's no built-in way to specify a number of rows instead of a number of columns.  However, you can get the number of items that would be added to the legend using the ax._get_legend_handles() method.
For example:
import numpy as np
import matplotlib.pyplot as plt

numlines = np.random.randint(1, 15)
x = np.linspace(0, 1, 10)

fig, ax = plt.subplots()
for i in range(1, numlines + 1):
    ax.plot(x, i * x, label='$y={}x$'.format(i))

numitems = len(list(ax._get_legend_handles()))
nrows = 5
ncols = int(np.ceil(numitems / float(nrows)))

ax.legend(ncol=ncols, loc='best')

plt.show()


text:
Q: combination of unary minus and float conversion Consider the following C statements:
unsigned long x = 1;
float a = -x;
double b = -x;

I would expect the unary minus term to yield an unsigned long value equal to ULONG_MAX and a and b to be set to single and double precision representations of ULONG_MAX, respectively.
This is the result I obtain with gcc 4.4.7 on 32-bit Linux and with the Intel and PGI compilers on 64-bit Linux. With gcc (tested versions 4.4.7, 4.7.2 and 4.8.0, both with -O0 and -O2) on 64-bit Linux, however, the double variable b has the expected value, but float a becomes equal to -1 instead.
By contrast, the following statements will set both a and b to floating point representations of ULONG_MAX on all compilers and systems I tested:
unsigned long x = 1;
unsigned long y = -x;
float a = y;
double b = y;

If I use unsigned int instead of unsigned long, I get the expected result on all systems, too.
Is this some kind of undefined behaviour or a compiler error?

A: This is due to a bug in GCC -- the type conversion happens before the negation.
The issue seems to be have been around for a while.  Bug 55771 - Negation and type conversion incorrectly exchanged
In your second example, the negation happens before the type conversion.  As such, you see expected results.

A: What you describe is a compiler bug.
(and there is no undefined behavior in the program below to excuse the compiler)
unsigned long x = 1;
float a = -x;
double b = -x;


text:
Q: Negative lookahead regex I have a string like so:

Year: ={year}
\

Director: ={director}
\

@{actors}
={actor}
{actors}
\

And I want to extract all ={match} that are NOT inside @{word}...{word}, so in this case I want to match ={year} and ={director} but not ={actor}. This is what I got so far but it's not working.
/(?!@.*)=\{([^{}]+)\}/g

Any ideas?
Edit: My current solution is to find all ={match} inside @{}...{} and replace the = with something like =&. Then I grab the ones that are outside and finally I come back and replace the flagged ones back to their original state.

A: You can use regular expressions to break down the string into segments, like so:
var s = '
Year: ={year}
 \

Director: ={director}
 \

@{actors}
={actor}
{actors}
',
  re = /@\{([^}]+)\}(.*?)\{\1\}/g,
  start = 0,
  segments = [];

while (match = re.exec(s)) {
  if (match.index > start) {
    segments.push([start, match.index - start, true]);
  }
  segments.push([match.index, re.lastIndex - match.index, false]);
  start = re.lastIndex;
}

if (start < s.length) {
  segments.push([start, s.length - start, true]);
}

console.log(segments);

Based on your example, you would get these segments:
[
    [0, 54, true],
    [54, 51, false],
    [105, 5, true]
]

The boolean indicates whether you're outside - true - or inside a @{}...{} segment. It uses a back-reference to match the ending against the start.
Then, based on the segments you can perform replacements as per normal.

A: here you go, needed to negative look ahead the ending {whatever}also
/(?!@.*)=\{([^{}]+)\}(?!.*\{[^{}]+\})/g
UPDATE:
Previous only works for {match} per line.
Hooking on @ would actually mean a LookBehind and it is difficult to use LookBehind in this case because LookBehind likes very much to know exactly how many chars to look for.
So let's use LookAhead for looking ahead: =\{([^{}]+)\}(?![^@]*[^=@]{) with hooking on the end {tag}
Edit: demo http://regex101.com/r/zH7uY6


text:
Q: What can change the calendar in iPhone/iOS to start weeks on Mondays and not Sundays? My iPhone's calendar, configured by me to start week Sundays, suddenly started starting week Mondays. I cannot find the setting to configure this any more. I found when I switch the phone's region settings from Irish (I am in Ireland) to US, the weeks start Sunday again, but then PM times are shown as 4:06 (rather than 16:06).
What can I do to have my weeks shown properly and the time in 24 hours and remain in my local region?

A: 24-hour vs 12-hour time is set in Settings=>General=>Date & Time:

The Sunday vs. Monday thing may be entirely dependent upon the International setting; there's no explicit place to change it, anyway.


text:
Q: Django - forms.FileField() initial value Is it possible to give initial value for forms.FileField() dynamically?

A: I'm not sure, if this is what you want, but…
Obviously you cannot set initial data for a file input (this would imply that you send a file to the user). Django has a ClearableFileInput widget though, and this widget pretends to show initial data: it displays a link to the uploaded file if the link is present.
This is implemented through checking if the initial object (the object passed to form constructor in files dictionary) has the url attribute. Once you set this attribute, the widget will display the "Currently link" line.
By the way, if you got the file object using a File Storage, then you can get the link to that file using storage's url() method.

A: By security standards, <input type="file"> can't have a default value and it can't be manipulated.
The reason is, that a hacker can set the default value of the file input to any important file on your system (containing passwords, certificates and so on), hide this field using CSS and you will never know that you have uploaded something to hackers host.


text:
Q: Math loop but solves when x is correct Is there a calculation of some sort that loops itself when for example x =1 but stops looping and solves when x is for example 5.

A: The following is more of a program (in pseudocode) than a "calculation", but it can trap itself (when $1$ is input) and can calculate $3$ (when something not $1$ is input, such as $5.$).
INPUT $x$
Label (A)
If $x=1$ GOTO (A)
If $x \neq 1$ GOTO (B)
Label (B)
OUTPUT $3$
END


text:
Q: How do you use more than 9 regex capture groups in emacs? I'm trying to transform a rather long sequence of values to a different format, using emacs' replace-regex command. There are more than 9 values to extract, so the \1 - \9 back references are not enough.
How can I back reference more than 9 capture groups in emacs?
Can named groups be used? If so, how?

A: Since Emacs 23, you can include Lisp code in a regexp replacement text. This gives you a way of using more backreferences. The function match-string returns the numbered backreferences.
\1 … \9 \,(or (match-string 10) "")

Since Emacs 22, if there's any parenthesized group in the regexp that you don't need to have a backreference for, use \(?:…\) (Emacs calls this a shy group).


text:
Q: 2Checkout API - Does recurring payments have a recurring id associated with it? We usually make a 'sale/detail_sale' API call to 2Checkouts URL, to get the details for a particular transaction/sale.
Suppose that the sale is of recurring type.
Will that particular transaction/sale have a recurring_id (or subscription_id) associated with it.
Like in PayPal:
If the transaction is of recurring type, then it has a subscription_id(like I-XXXXXXXXXX) associated with it.
All the transactions related to that subscription will have the same subscription_id, but their transaction_id's are different.The subscription_id acts like the parent-id.
Any help will be appreciated.
Thanks in advance.

A: 2Checkout recurring sales do not have any additional recurring identifier. All 2Checkout sales have a sale_id, and invoice_id and at least one lineitem_id. Recurring sales create a new invoice on each recurring installment so the sales/detail_sale API call may return multiple invoices. So the sale_id can have many invoice_id's and each invoice_id can have many linitems_id's.
If you need to stop the recurring billing on a sale, you need to stop the recurring billing an each active recurring lineitem. The lineitem_id is changed on each new invoice on a recurring sale so when making the stop_lineitem_recurring call it is necessary to use the lineitem_ids from the most recently billed invoice as demonstrated in the 2checkout-php-library.


text:
Q: How to handle test case fails in Katalon Studio In my test case I decide whether I want to toggle my radio button. I check if my radio button does not have the checked attribute as follows:
TestObject srcCurrOpModeRadioBtn = guiUtils.createControl('config-src-op-mode-currentradio')
        if(WebUI.verifyElementNotHasAttribute(srcCurrOpModeRadioBtn, 'checked', 5)){
            TestObject srcCurrOpModeToggle = guiUtils.createControl('config-src-op-mode-current')
            WebUI.click(srcCurrOpModeToggle)
            WebUI.delay(1)
        }

This works fine when my object does not have the checked attribute, but when my object is already checked (in the state that I want it to be), my test case fails. How do I make it so that instead of failing, it carries out the remaining test?
In simpler words, I have a toggle that toggles between 2 modes, lets call them mode1 and mode2. This specific test tests mode1's preferences, so before testing mode1's preferences, I have to toggle to mode1. My logic works when the toggle is at mode2 at the start of the test but it fails when I am already on mode1. I know that it fails because when mode1 is selected, its radio button already has a checked attribute and so the if statement fails but I don't want my test case to fail because of this, I want to test mode1's preferences.

A: There is another parameter to WebUI.verifyElementNotHasAttribute() - flow control.
You need to set FailureHandling.OPTIONAL so the test continues execution even if the function returns false. Then you can write the "else" part with corresponding logic.


text:
Q: Intelligently troubleshooting git ssh definition for a specific remote There's several questions and answers about this, but they don't work for me. I have added in ~/.ssh/config the following, reflecting my intent of using a specific ssh key for a specific git server:
Host HOST-NICKNAME-FOR-THIS-FILE
    Hostname THE-HOST-DOMAIN-NAME
    User THE-GIT-USER-ON-THE-HOST
    IdentityFile ~/.ssh/id_rsa_filename_for_this_host_and_host_git_user
    IdentitiesOnly yes

But am still getting a password prompt when trying to push the the remote having the Hostname defined above (second row of the config snippet). Should I refresh git or ssh in some way to pick up the new config?
Being asked my password upon pushing, I wonder whether this means the git server is trying to authenticate through both a password and the public ssh key which I have uploaded to it, or whether the wrong key is being used by git despite my definition above. How can I tell what's going on?
For doubt avoidance: I'm being asked for the git password for the remote server, not the ssh key's local passphrase.

A: try ssh with -v to see all the keys it tries
for example
ssh git@github.com -v

ssh HOST-NICKNAME-FOR-THIS-FILE -v

A: It looks like you have a permissions problem with your ssh key setup.
On the remote machine, the permissions on .ssh must be 700, on .ssh/authorized_keys must be 600.
chmod 700 ~THE-GIT-USER-ON-THE-HOST/.ssh
chmod 600 ~THE-GIT-USER-ON-THE-HOST/.ssh/authorized_keys

Of course the public key that corresponds to the private key must also be inside the authorized_keys file.


text:
Q: Trouble with VertexLabel in RelationGraph I have a bunch of high dimensional data and I want to use a graph to plot relationships among that data. To keep things small, say the data is
d[x_, y_] := Total[Abs[x - y]];
data = RandomReal[{0, 1}, {10, 5}];
RelationGraph[0.2 < d[#1, #2] < 1.5 &, data, data]

This draws a nice graph of all the elements whose distance apart is between 0.2 and 1.5. If I want to label the graph with the index number, then
RelationGraph[0.2 < d[#1, #2] < 1.5 &, dist, dist, VertexLabels -> "Index"]

works fine. But if I want to use my own labels, Mathematica does not draw the graph and simply returns the input unchanged. For example, neither of these:
RelationGraph[0.2 < d[#1, #2] < 1.5 &, dist, dist,
              VertexLabels -> {1 -> "this", 2 -> "that"}]

RelationGraph[0.2 < d[#1, #2] < 1.5 &, dist, dist,
              VertexLabels -> Table[i -> Subscript[v, i], {i, 5}]]

return any graph. Is there a trick to using VertexLabels? Or do I need to search for another way to draw the graphs?

A: RelationGraph[0.2 < d[#1, #2] < 1.5 &, data, data,
 VertexLabels -> {data[[1]] -> "this", data[[2]] -> "that"}]

RelationGraph[0.2 < d[#1, #2] < 1.5 &, data, data,
 VertexLabels -> MapIndexed[# -> Subscript[v, #2[[1]]] &, data]]


text:
Q: Replace 2nd occurance of a special character after nth occurance of a delimiter from string,in unix/linux Here My question is,
Replace 2nd or all occurance of a special character after nth occurance of a delimiter from string,in unix/linux
or
Replace "Text Qualifier" character from data field in unix.
I have below string where '"'(Double Quote) should get replaced with space.
String:
"123"~"23"~"abc"~24.50~"descr :- nut size 12" & bolt size 12"1/2, Quantity=20"~"2013-03-13"

From above string, i want below output:
"123"~"23"~"abc"~24.50~"descr :- nut size 12  & bolt size 12 1/2, Quantity=20"~"2013-03-13"

I have replaced " double quote character with space character.
"descr :- nut size 12" & bolt size 12"1/2, Quantity=20"

&
"descr :- nut size 12  & bolt size 12 1/2, Quantity=20"

I want to identify such rows from file & would like to replace such text qualifier character from data in Unix/Linux.
Request you to provide your inputs, & thanking you in advance.

A: I would use plain read to get the fields and then modify the wished ones using sed or shell variable substitution mechanisms:
echo '"123"~"23"~"abc"~24.50~"descr :- nut size 12" & bolt size 12"1/2, Quantity=20"~"2013-03-13"' | {
  IFS='~' read a b c d e f
  printf "%s~%s~%s~%s~%s~%s" "$a" "$b" "$c" "$d" "$(sed 's/"/ /g' <<<$e)" "$f"
  # or:
  printf "%s~%s~%s~%s~%s~%s" "$a" "$b" "$c" "$d" "${e//\"/ }" "$f"
}

That IFS ("Internal Field Separator") is an internal variable telling the shell how to separate fields, e.g. when using read.  In our case using this tells the shell to use ~ as separator.  Prepending the assignment directly to the read command makes that assignment only for the duration of the read command.

A: I'm going to assume you work in the bash shell.
awk(awk) can help you split your input string at the right positions, using its "-F" option:
echo xyzabcdef | awk -Fb '{print $1}'

gives you "xyza", the the first string before the separator.
Then, the tr(1) utility can help you replace characters:
tr '"' ' '

will replace '"' with ' '. I hope this helps to get you in the right direction.


text:
Q: Azure Search with CosmosDB data source shows documents in collection but Search Explorer shows all NULL or EMPTY values I have a CosmosDb database with valid data documents within it.
I have creatd an Azure Search and correctly hooked up the CosmosDB endpoint, and run the indexer which has indexed over 500 documents, with 149KB of storage used up. However, when I run a simple '*' search using Search Explorer, all my result sets are NULL except the primary key and another field from CosmosDb that gets internally generated whenever I add a new Document. What am I doing wrong? These fields are NOT null or empty in the database.
See below screenshots:

Showing the JSON from search explorer as well:
"value": [
    {
        "@search.score": 1,
        "id": "9ce19abc-a26a-5102-1919-8dcf42100067",
        "StoreName": "",
        "StoreProfile": "",
        "StoreType": "",
        "StoreStatus": "",
        "RBM": "",
        "StoreStateManager": "",
        "StoreFranchiseGroup": "",
        "Street": "",
        "City": "",
        "State": "",
        "Location": "",
        "Precinct": "",
        "AreaPopulation": "",
        "MedianAge": "",
        "MedianHHoldIncome": "",
        "Grading": "",
        "BayCount": "",
        "TenancySqm": "",
        "RetailAreaSqm": "",
        "rid": "BFA1AM5ZblIBAAAAAAAAAA=="
    },
    {
        "@search.score": 1,
        "id": "5fe1ec72-1cc9-593a-fac0-891f8b84df27",
        "StoreName": null,
        "StoreProfile": null,
        "StoreType": null,
        "StoreStatus": null,
        "RBM": null,
        "StoreStateManager": null,
        "StoreFranchiseGroup": null,
        "Street": null,
        "City": null,
        "State": null,
        "Location": null,
        "Precinct": null,
        "AreaPopulation": null,
        "MedianAge": null,
        "MedianHHoldIncome": null,
        "Grading": null,
        "BayCount": null,
        "TenancySqm": null,
        "RetailAreaSqm": null,
        "rid": "BFA1AM5ZblICAAAAAAAAAA=="
    },

The search being used is just *, e.g.

.../docs?api-version=2017-11-11&search=*

A: This issue turned out to be the use of column names with spaces in them. These originally came from the Spreadsheet I was using to obtain the original data for CosmosDB. While CosmosDB will allow columns with spaces in the names, it will negatively affect (in my experience)

*

*Azure Search

*CosmosDb queries (found this out via testing the same data set with a Web App Bot).

Removing spaces from the column name and re-testing showed the issue to be resolved.


text:
Q: Function arguments inheriting defaults from other function Let's say there's a function in a Python library (let's call it mymodule):
def some_func(a,b='myDefaultValue'):
    return some_computation

and then there's another function in another module that calls it,
import mymodule
def wrapper(a,b):
    return some_transform(mymodule.some_func(a,b))

How do I make it such that wrapper inherits some_func's default value for the b parameter? I could do something like:
def wrapper(a,b=None):
    if b:
        return some_transform(some_func(a,b))
    else:
        return some_transform(some_func(a))

but that seems needlessly cumbersome, leads to a combinatorial explosion of possibilities with multiple optional arguments, and makes it so I can't explicitly pass in None to wrapper.
Is there a way of getting the default args for a function, or is common practice to simply pull that value out into a shared constant that both function declarations can make use of?

A: You can use func_defaults:
https://docs.python.org/2/library/inspect.html?highlight=func_defaults#types-and-members

func_defaults tuple of any default values for arguments

def some_func(a,b='myDefaultValue'):
    print a, b

def wrapper(a,b):
    b = some_func.func_defaults[0] if b is None else b
    some_func(a,b)

print "b is 'there'"
a = "hello"
b = "there"
wrapper(a,b)

print "b is 'None'"
b = None
wrapper(a,b)

output:
b is 'there'
hello there
b is 'None'
hello myDefaultValue

EDIT:  To answer your question from the comments, there isn't anything built-in to look up the arguments of the function with default values  by name.  However, you know that the arguments with default values have to come after the non-optional arguments.  So if you know the total number of arguments you have, and how many of them have default values, you can subtract the 2 to get the starting point of the arguments with default values.  Then you can zip the list of arguments (starting at the previously calculated argument index) together with the list of default argument values and create a dictionary from the list.  Use the inspect module to get all of the information you need:
Like so:
>>> import inspect
>>> def some_func(a,b,c,d="dee",e="ee"):
...     print a,b,c,d,e
...
>>> some_func("aaa","bbb","ccc",e="EEE")
aaa bbb ccc dee EEE
>>> some_funcspec = inspect.getargspec(some_func)
>>> some_funcspec
ArgSpec(args=['a', 'b', 'c', 'd', 'e'], varargs=None, keywords=None, defaults=('dee', 'ee'))
>>> defargsstartindex = len(some_funcspec.args) - len(some_funcspec.defaults)
>>> defargsstartindex
3
>>> namedargsdict = dict(zip([key for key in some_funcspec.args[defargsstartindex:]], list(some_funcspec.defaults)))
>>> namedargsdict
{'e': 'ee', 'd': 'dee'}

In the example above, namedargsdict is your list of arguments with default values for some_func.
Further reading:
https://docs.python.org/2/library/inspect.html#inspect.getargspec

inspect.getargspec(func) Get the names and default values of a Python
  function's arguments. A tuple of four things is returned: (args,
  varargs, keywords, defaults). args is a list of the argument names (it
  may contain nested lists). varargs and keywords are the names of the *
  and ** arguments or None. defaults is a tuple of default argument
  values or None if there are no default arguments; if this tuple has n
  elements, they correspond to the last n elements listed in args.
Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs,
  keywords, defaults).

A: You can use argument unpacking to accomplish this:
In [1]: def some_func(a,b='myDefaultValue'):
   ...:     print a, b
   ...:

In [2]: def wrapper(a, *args, **kwargs):
   ...:     some_func(a, *args, **kwargs)
   ...:

In [3]: some_func('foo', 'bar')
foo bar

In [4]: some_func('baz')
baz myDefaultValue

In [5]: wrapper('foo', 'bar')
foo bar

In [6]: wrapper('baz')
baz myDefaultValue

If you plan to wrap multiple functions in this way, you might consider making wrapper a decorator:
In [1]: from functools import wraps

In [2]: def wrapper(func):
   ...:     @wraps(func)
   ...:     def decorated(a, *args, **kwargs):
   ...:         print 'wrapper invoked with a = {}'.format(a)
   ...:         return func(a, *args, **kwargs)
   ...:     return decorated
   ...:

In [3]: @wrapper
   ...: def some_func(a, b='myDefaultValue'):
   ...:     print a, b
   ...:

In [4]: some_func('foo', 'bar')
wrapper invoked with a = foo
foo bar

In [5]: some_func('baz')
wrapper invoked with a = baz
baz myDefaultValue

A: Your question is not clear enough. But as far as I understand from your question, you should use class so that you can easily share values among multiple functions inside the class
class SomeClass:

  def __init__(self, b='defaultvalue'):
    self.b = b

  def some_func(self, a, b):
    pass

  def wrapper(self, a):
    self.some_func(a, self.b)


text:
Q: Get a list of MCC Accounts I have been struggling with the Google Ads Api to get the MCC Accounts for the last two weeks but I am unable to achieve what I want.
I have the App.Config figured out
<GoogleAdsApi>
    <!-- API-specific settings -->
    <add key="DeveloperToken" value="XXXXXXX"/>

    <!-- OAuth2 settings -->
    <add key="AuthorizationMethod" value="OAuth2" />
    <add key = "OAuth2ClientId" value = "XXXXXXX.apps.googleusercontent.com" />
    <add key = "OAuth2ClientSecret" value = " XXXXXXX  " />
    <add key = "OAuth2Mode" value="APPLICATION"/>
    <add key = "OAuth2RefreshToken" value = "1//0gd2 XXXXXXX  " />
</GoogleAdsApi>

This is the code that I am currently working with
Public Sub GetMCCAccounts(ByVal client As GoogleAdsClient)
    Dim customerService As CustomerServiceClient = client.GetService(Services.V8.CustomerService)
    Dim customerResourceNames As String() = customerService.ListAccessibleCustomers()

    For Each customerResourceName As String In customerResourceNames
        Dim ManagerCustomerId = customerResourceName.Substring(customerResourceName.IndexOf("/") + 1)
        TextBox1.AppendText(vbCrLf & ManagerCustomerId)
    Next
End Sub

I am not getting the correct results. The MCC accounts that I was hoping for do not appear in the output. I am getting different account numbers. What am I missing?
Expected MCC Accounts
I am looking for these 10 MCC accounts.

Sub Account Settings Overview

Output
I am getting these 16 account numbers.
64xxxxxxxx
71xxxxxxxx
10xxxxxxxx
88xxxxxxxx
32xxxxxxxx
58xxxxxxxx
31xxxxxxxx
73xxxxxxxx
98xxxxxxxx
22xxxxxxxx
48xxxxxxxx
37xxxxxxxx
98xxxxxxxx
94xxxxxxxx
88xxxxxxxx
43xxxxxxxx

A: After burning the midnight oil, I finally managed to crack it!
This finally gave me the MCC accounts that I wanted.
Imports Google.Ads.GoogleAds.Lib
Imports Google.Ads.GoogleAds.V8.Services
Imports Google.Ads.GoogleAds
Imports Google.Ads.GoogleAds.V8.Resources
Imports Google.Api.Gax
Imports Google.Apis

Public Class GoogleAdsCode
    Private Const PAGE_SIZE As Integer = 1000

    '~~> Get MCC Accounts
    Public Shared Function GetMCCAccounts(MgrId As Long?) As List(Of String)
        Dim googleAdsClient As New GoogleAdsClient
        Dim googleAdsServiceClient As GoogleAdsServiceClient = googleAdsClient.GetService(Services.V8.GoogleAdsService)
        Dim customerServiceClient As CustomerServiceClient = googleAdsClient.GetService(Services.V8.CustomerService)
        Dim seedCustomerIds As New List(Of Long)
        Dim MgrList As New List(Of String)

        seedCustomerIds.Add(MgrId.Value)

        Const query As String = "SELECT
                                    customer_client.client_customer,
                                    customer_client.level,
                                    customer_client.manager,
                                    customer_client.descriptive_name,
                                    customer_client.currency_code,
                                    customer_client.time_zone,
                                    customer_client.id
                                FROM customer_client
                                WHERE customer_client.level <= 1"
        Dim customerIdsToChildAccounts As Dictionary(Of Long, List(Of CustomerClient)) = New Dictionary(Of Long, List(Of CustomerClient))()

        For Each seedCustomerId As Long In seedCustomerIds
            Dim unprocessedCustomerIds As Queue(Of Long) = New Queue(Of Long)()
            unprocessedCustomerIds.Enqueue(seedCustomerId)
            Dim rootCustomerClient As CustomerClient = Nothing

            While unprocessedCustomerIds.Count > 0
                MgrId = unprocessedCustomerIds.Dequeue()
                Dim response As PagedEnumerable(Of SearchGoogleAdsResponse, GoogleAdsRow) = googleAdsServiceClient.Search(MgrId.ToString(), query, pageSize:=PAGE_SIZE)

                For Each googleAdsRow As GoogleAdsRow In response
                    Dim customerClient As CustomerClient = googleAdsRow.CustomerClient
                    If customerClient.ToString.Contains("MCC") Then MgrList.Add(customerClient.Id & " (" & customerClient.DescriptiveName & ")")
                Next
            End While
        Next

        Return MgrList
    End Function
End Class


text:
Q: Are there benefits to keeping the Google Sign-In account connected after Firebase Auth via GSI has been signed in? When signing-in via Firebase Auth with the "google.com" provider, are there any benefits to keeping the underlying Google Account connected?
All the samples I've seen do leave it connected, but I've come across the situation where I'm better off disconnecting the Google Account as soon as I have signed into Firebase via FirebaseAuth.getInstance().signInWithCredential(GoogleAuthProvider.getCredential(result.getIdToken(), null)) instead of leaving it connected ("signed in"). It's even possible to disconnect before calling signInWithCredential, since the idToken is still valid for a certain amount of time.
Doing this doesn't seem to have any negative side effects. This is what I'm doing:
GoogleSignInClient client = GoogleSignIn.getClient(this, googleSignInOptions);
client.silentSignIn().addOnCompleteListener(new OnCompleteListener<GoogleSignInAccount>() {
    @Override public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
        if (task.isSuccessful()) {
            GoogleSignInAccount result = task.getResult();

            // Disconnect from Google Account
            GoogleSignIn.getClient(this, googleSignInOptions).signOut();

            if (result != null) {
                FirebaseAuth.getInstance().signInWithCredential(GoogleAuthProvider.getCredential(result.getIdToken(), null)).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override public void onComplete(@NonNull Task<AuthResult> task) {

                        // but I might as well disconnect here
                        //GoogleSignIn.getClient(this, googleSignInOptions).signOut();

                        if (task.isSuccessful()) {
                            final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                            // OK, user is signed in

                            //...


text:
Q: sum of power floor $ S(n,m) = \sum_{i = 1}^{n} \Bigl \lfloor \frac{n}{i^m} \Bigr \rfloor i^m $ How do I calculate
$$ S(n,m) = \sum_{i = 1}^{n} \Bigl \lfloor \frac{n}{i^m} \Bigr \rfloor i^m $$
This can be simplifies to
$$ S(n, m) = \sum_{i = 1}^{\sqrt[m] n} \Bigl \lfloor \frac{n}{i^m} \Bigr \rfloor i^m  = \sum_{i = 1}^{\sqrt[m] n} n - \sum_{i = 1}^{\sqrt[m] n}n \bmod i^m$$
Example
$$S(100,2) = \sum_{i=1}^{10} \Bigl \lfloor \frac{n}{i^2} \Bigr \rfloor i^2 = 100 + 100 + 99 + 96 + 100 + 72 + 98 + 64 + 81 + 100 = 910$$
More work.
Let's divide the $\Bigl \lfloor \frac{n}{i^{2}} \Bigr \rfloor $ into intervals of $1, 2, 3, \cdots$ Like this. and calculate the sum.
i.e from interval $\sqrt{\frac{n}{1}} \ge i \gt \sqrt{\frac{n}{2}} \quad $ like this and the summation becoms.
$$S(n,2) = \sum_{1}^{\bigl \lfloor \frac{n}{2} \bigr \rfloor} \Bigl \lfloor \frac{n}{i^2}  \Bigr \rfloor i^2  + \sum_{i = \bigl \lfloor \frac{n}{2} \bigr \rfloor}^{\lfloor n \rfloor} 1 .  i^2 $$
like so we can divide it even more but nothing converges to a smaller value and the multiplier of $i^2$ keeps on increasing.
$$S(n,2) =
\sum_{i = \bigl \lfloor \frac{n}{2} \bigr \rfloor}^{\lfloor n \rfloor} 1 .  i^2  +
\sum_{i = \bigl \lfloor \frac{n}{3} \bigr \rfloor}^{\bigl \lfloor \frac{n}{2} \bigr \rfloor} 2 . i^2 +
\sum_{i = \bigl \lfloor \frac{n}{4} \bigr \rfloor}^{\bigl \lfloor \frac{n}{3} \bigr \rfloor} 3 . i^2 + \cdots$$
Is there a way to generalize this?

A: Hint
Using the division algorithm, we can write $a=kq+r$, where $0 \leq r < k$. Then,
$$\frac{a}{k}=q+\frac{r}{k} \implies q=\lfloor\frac{a}{k}\rfloor.$$
So
$$a=k\lfloor\frac{a}{k}\rfloor+r \implies \lfloor\frac{a}{k}\rfloor k=a-r.$$


text:
Q: Blueprint IE hack breaks VS designer My client and I have both just independently experienced this.  Given an HTML page like below, when the IE hack is included, conditionally or not, everything above the "First text" is not visible in the VS designer, in 2008 and 2010, and 2008 crashes very frequently, while 2010 only crashes during certain edit ops on the page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Smart Computer Solutions</title>
    <link href="Styles/Blueprint/screen.css" rel="stylesheet" type="text/css" />
    <link href="Styles/Blueprint/print.css" rel="stylesheet" type="text/css" media="print" />

                Smart Computer Solutions

Some catchy and informative company slogan.

        First text

        Second text

            Third text

I'm also asking this on the Blueprint forum, but SO is my primary oracle.

A: Guys on the Blueprint discussion group have convinced me the problem is with the VS designer, not the IE hack.  I agree here - the design view in VS is still pathetic.


text:
Q: Characters UTF-16LE not showing on my Android Nougat
I am developing an Android Application and I need to display on a TextView special UTF-16LE characters like æ or Œ, or the one in the picture I posted.
I can't understand why everything is displayed correctly on Nougat Emulator and also on an Lollipop and Marshmallow Smartphone while on my Personal Android Nougat I can't see those characters, I can only see ": :" characters instead of the right ones.
(Careful, In the left picture, that ' character is not a normal accent and that I is not a normal I)
Why can't I display those special characters on my Smartphone? How should I proceed with that?
I debugged my application and characters are properly set on my TextView; but still, I can't read them correctly.
It seems that my Smartphone (OnePlus3 on latest Software Updates) can't read UTF-16LE characters, but still, It's really strange for me to face something like that.
Any help would be very appreciated,
Have a nice day.
UPDATE: I downloaded https://play.google.com/store/apps/details?id=org.madore.android.unicodeMap on my Smartphone and it seems that I don't have many of those unicode characters on my Smartphone, is there a way to fix it? Do I just need to install a better font?

A: I solved my issue, that's what I did. (As usual, thanks also to @Claffolo, my teammate)
I imported a free copyrighted font like Gentium in my android assets.
/assets/fonts/
On my project, I imported the new font and init a variable like that
        Typeface plain = Typeface.createFromAsset(getActivity().getAssets(), "fonts/GentiumPlus-I.ttf");

    final TextView text_view = (TextView)view.findViewById(R.id.text_view);
    text_view.setTypeface(plain);
   text_view.setText("[String with special characters]");

When I loaded my ArrayList with all the special characters, let's say my wordlist.
I did it in the following way:
//Loading my Wordlist
BufferedReader line_reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(R.raw.ipautf16le), Charset.forName("UTF-16LE")));

String line;
try {
    while ((line = line_reader.readLine()) != null) {
        WordList.add(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Collections.sort(WordList);

That's all.


text:
Q: Event Reciever Sharepoint 2010(when the calling fails) I am working on a share-point 2010 custom list event receiver(item adding, item updating,item added), once in a while i will notice that when i create a new item, it seems like the event receiver wont fire but then in the list there will be entries for the created By column and the Created Column...how can i make the event receiver to fire all the time, or else if not is there a way to throw an error on the page when the event receiver is not fried, so that the user will know that the ticket is not being generated(and then prevent the columns(createdBy and the Created columns) to be added to the list when the event is not fired

A: There is no way to act when an event is not triggered. That would sort of go against the logic of event handlers.
As per your other thread, you might have a code error in your event receiver, causing it to throw an exception and exit unfinished.
You might also have concurrency issues. Are you disabling event triggers while you are executing them (SPEventReceiverBase.EventFiringEnabled)? That will prevent events from being handled until you set Firing back to true. It will prevent any events (in the current thread) in any list until you set it back (see How DisableEventFiring / EventFiringEnabled works).
Best practice #1: If you disable event firing in your event handler, use a try-catch-finally block and re-enable them in your finally part. You might be leaving them disabling if you exit on an exception.
Best practice #2: Event handlers should be very short, especially the parts where you are disabling event firing. Especially asynchronous events.
Best practice #3: For nicer event cohabitation, implement your own event-type-specific event firing-disabling boolean (e.g. put a static bool in your event's class, and at the start of your event check if it's true or false before proceeding)
Best practice #4: You should not instantiate SPWeb or SPSite objects inside event handlers (other than SPItemEventProperties.Web) (ref)


text:
Q: How to handle a skewed response in H2O algorithms In my problem dataset response variable is extremely skewed to the left. I have tried to fit the model with h2o.randomForest() and h2o.gbm() as below. I can give tune min_split_improvement and min_rows to avoid overfitting in these two cases. But with these models, I see very high errors on the tail observations. I have tried using  weights_column to oversample the tail observations and undersample other observations, but it does not help.
h2o.model <- h2o.gbm(x = predictors, y = response, training_frame = train,valid = valid, seed = 1,
                              ntrees =150, max_depth = 10, min_rows = 2, model_id = "GBM_DD", balance_classes = T, nbins = 20, stopping_metric = "MSE",
                     stopping_rounds = 10, min_split_improvement = 0.0005)

h2o.model <- h2o.randomForest(x = predictors, y = response, training_frame = train,valid = valid, seed = 1,ntrees =150, max_depth = 10, min_rows = 2, model_id = "DRF_DD", balance_classes = T, nbins = 20, stopping_metric = "MSE",
                     stopping_rounds = 10, min_split_improvement = 0.0005)

I have tried the h2o.automl() function of h2o package for the problem for better performance. However, I see significant overfitting. I don't know of any parameters in h2o.automl() to control overfitting.
Does anyone know of a way to avoid overfitting with h2o.automl()?
EDIT
The distribution of the log transformed response is given below. After the suggestion from Erin

EDIT2:
Distribution of original response.

A: H2O AutoML uses H2O algos (e.g. RF, GBM) underneath, so if you're not able to get good models there, you will suffer from the same issues using AutoML.  I am not sure that I would call this overfitting -- it's more that your models are not doing well at predicting outliers.
My recommendation is to log your response variable -- that's a useful thing to do when you have a skewed response.  In the future, H2O AutoML will try to detect a skewed response automatically and take the log, but that's not a feature of the the current version (H2O 3.16.*).
Here's a bit more detail if you are not familiar with this process.  First, create a new column, e.g. log_response, as follows and use that as the response when training (in RF, GBM or AutoML):
train[,"log_response"] <- h2o.log(train[,response])

Caveats: If you have zeros in your response, you should use h2o.log1p() instead. Make sure not to include the original response in your predictors.  In your case, you don't need to change anything because you are already explicitly specifying the predictors using a predictors vector.
Keep in mind that when you log the response that your predictions and model metrics will be on the log scale.  So if you need to convert your predictions back to the normal scale, like this:
model <- h2o.randomForest(x = predictors, y = "log_response",
                          training_frame = train, valid = valid)
log_pred <- h2o.predict(model, test)
pred <- h2o.exp(log_pred)

This gives you the predictions, but if you also want to see the metrics, you will have to compute those using the h2o.make_metrics() function using the new preds rather than extracting the metrics from the model.
perf <- h2o.make_metrics(predicted = pred, actual = test[,response])
h2o.mse(perf)

You can try this using RF like I showed above, or a GBM, or with AutoML (which should give better performance than a single RF or GBM).
Hopefully that helps improve the performance of your models!

A: When your target variable is skewed, mse is not a good metric to use. I would try changing the loss function because gbm tries to fit the model to the gradient of the loss function and you want to make sure that you are using the correct distribution. if you have a spike on zero and right skewed positive target, probably Tweedie would be a better option.


text:
Q: How does one assert a single field in error type? Let's assume I have code such as this:
final case class CustomException(errorCode: Int, id: UUID) extends Throwable

val logic: ZIO[Any, Throwable, Unit] = ???

I would like to use ZIO Test to check for a specific error case
val checkForTimeout = testM("Logic should time out") {
  for {
    result <- logic.flip
  } yield assert(result, isSubtype[CustomException](???))
}

What I would like to do is check the errorCode field for a specific value. But it seems the existing combinators in ZIO Test only allow me to check the the full object.
I would like to only check for _.errorCode while ignoring _.id, which means equalTo is not a good enough combinator for this use case.
How would I go about addressing this?

A: You can use Assertion.hasField, which lets you "zoom in" on one part of a larger structure, to do this.
val checkForTimeout = testM("Logic should time out") {
  for {
    result <- logic.flip
  } yield assert(
      result,
      isSubtype[CustomException](hasField("errorCode", _.errorCode, equalTo(1)))
    )
}

A: The simplest thing would be to adjust the signature of logic.
val logic: ZIO[Any, CustomException, Unit] = ???

Now you can do something like:
val checkForTimeout = testM("Logic should time out") {
    for {
      result: CustomException <- logic.flip
    } yield assert(result.errorCode, equalTo(543))
}

If not you can still cast the result:
val checkForTimeout = testM("Logic should time out") {
    for {
      th <- logic.flip
      result = th.asInstanceOf[CustomException]
    } yield assert(result.errorCode, equalTo(543))
}


text:
Q: Django - define template includes/extends in one place in the same way url paths are defined in urls.py? I'm really enjoying the transition from PHP to Python/Django and the ability to extend templates. However, I'm still finding that I'm still doing a fair bit of repetitive work in defining templates and extending other templates, etc. Just wondering if anyone knows of any way to abstract all this out into one file which tells which templates other templates should extend/include?

A: The simple answer is, not with the default functionality.  Abstracting things like the {% base %} tag to another file would make the templates much harder to read.
One way to remove the "extra work" is to make your editor do it for you.  In my case, I define all of my templates as .dhtml files and have VIM paste in a template into the file whenever I open an empty .dhtml file.  Most programming-centric editors have this functionality built in to prevent you from having to manually copy/paste or retype your basic structures.
Another thing to consider is that you may be building the templates themselves in a less-than-optimal way.  For example, if you have different base templates, could you replace the different base templates with CSS?  CSS can change templates in ways that programmers can sometimes overlook.  For a good example, check out the CSS Zen Garden.  The changes you see are amazing, and they do not change the base HTML at all.
For a change like this, you could simply have this in templates/base.html:
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/default.css" />
{% block extracss %}{% endblock %}

And in order to include an over-riding CSS, you place this in your templates:
{% extends "base.html" %}
{% block extracss %}
    <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/orchid_beauty.css" />
{% endblock %}


text:
Q: In flutter how to return true when data change? I tried to animate every time I have my double change.
ex   my double change to 1.562  I search to return true and come back to false
next my double passe to 1.563  I search to return true and come back to false
etc...
like that I could launch my animation for every change of my counter.
Thank you

A: You can use streams to listen to a sequence of events.
https://dart.dev/tutorials/language/streams
You can add events to a StreamController with the _updateDouble from the place in your app where you get your new double value.
class MyWidgetState extends State<MyWidget> {
    final StreamController<double> myDoubleStreamController = StreamController();
    StreamSubscription _subscription;

    void initState() {
        _subscription = myDoubleStreamController.stream.listen((double myDouble){
            // Start animation
        });
    }

    void dispose() {
        _subscription.cancel();
    }

    void _updateDouble(double newDouble){
        myDoubleStreamController.sink.add(newDouble);
    }
}


text:
Q: Auto restart MVC application after server crashes and restarts I have used Quartz schedule in my  MVC app which starts at application_start, I deployed the app on IIS, in case if the server crashes and then restarts, how to make my app run automatically, so that schedular start again automatically
This is first time that I deployed Quartz application on any server
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            JobScheduler.Start();
        }

A: If the server crashes then on the next http request your application will start again. Then your JobSchedular will resume again as if it is running for the first time. There is nothing to be done.
However, question is when the server crashes will your AppPool restart again or not. Server crash is not a normal scenario and should not be expected to happen. Not just crash scenarios but also AppPool recycles - the whole web application will start again on the next http request.
I suggest on the IIS AppPool settings set the Idle Time-out Action to Suspend instead of the default Terminate.
After the server resumes, if you do not want to wait till the next http request then you will have to hook an external trigger to initiate the app start. You can do that with a windows schedule job (which will hit a Url of your site) or 3rd party service to hit your site in a regular interval.
After a crash if the AppPool is down (stopped) then there is nothing you can do from your web application code.


text:
Q: Magento 1.7 Directory Separator returning wrong seperator I'm trying to get a function working to re size any image using a custom module and helper class. For the record I'm running this on a local XAMPP server.
If I pass a image url and a destination url using '/' all works fine. However I need to implement this with DS for future proofing. The following is an example line of code I'm using. with the DS instead of '/'
$newPath = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . "resized" . DS . $fileName;

This returns (without the http or localhost at the start because stackoverflow doesn't allow that even in code) "/test/media/resized\catalog\category\testcat.jpg"
How do I make it so that DS correctly returns forward slashes?

A: There should be no reason at all to change the DS.
DIRECTORY_SEPARATOR is a predefined PHP constant that is set by your PHP installation itself.
If it is returning the wrong value, it is because your PHP installation is wrong.
Don't adjust Magento to suit a broken PHP install.

A: This is strictly speaking correct for Windows systems.
You probably have to set DS hardcoded, in app/Mage.php change
define('DS', DIRECTORY_SEPARATOR);

to
define('DS', '/');


text:
Q: Object/Material is infront of Camera I have start working with openinventor. I have a socube in viewer. I would like to check if socube is infront of camera or not. So when I move cube somewhere away from camera view value should be false.
SoSeparator root = new SoSeparator();
SoMaterial Material = new SoMaterial();
Material.diffuseColor.SetValue(1.0f, 0.0f, 0.0f);     // Red
root.AddChild(Material);
root.AddChild(new SoCone());
viewer = new SoWinExaminerViewer(this);
viewer.SetTitle("Example 1.1 .NET");
viewer.SetSceneGraph(root);
viewer.ViewAll();

Now I want to add a behavior something like if I move cone away from camera it returns false

A: I confirm that Open Inventor does not provide a method that implements this query. However it is possible to write one using information you can query.
If you can accept an approximately correct answer, then your goal is to answer the question: Does the bounding box of the geometry intersect the view frustum?
Get the bounding box using SoGetBoundingBoxAction, then get the current view volume parameters from the current camera, e.g. viewer->getCamera()->getViewVolume().


text:
Q: How to filter through a FormArray using Pipe in Angular to search for specific value? I have a following object as formArray that I am passing inside of the transform method in my pipe.ts file. The object looks as following

I want to access the value property of said object, where the firstName and lastName are stored. I want to filter it by those first and last name to search for a specific user inside of that FormArray

I have the following in my pipe ts file, which is referenced in the html file displaying those names and email address.
export class FilterPipe implements PipeTransform {
  transform(nameData: FormArray, searchData:string) : FormArray{

    if(searchData === ""){
      return nameData;
  }
    var arrayForms = nameData.value;
    for(var element of arrayForms){
      if(element.valid){
        return arrayForms.filter((arrayForm)=> {
          return arrayForm.value.firstName.includes(searchData);
        })
      }
    }
 }

at first I tried just using .filters to filter through, but I get error saying filter is not available for FormArray, so I tried converting the formArray into a regular array, but doing that, when debugging my nameData.value comes up as invalid, making the whole code block useless. I was expecting the filter to at first filter through the firstName property of the array

A: The FormArray type has a controls property on it which is of type AbstractControl[]. You should be able to utilize that to look into the values you want and filter accordingly. Something as follows.
nameData.controls.filter(control => control.valid && control.value.firstName.includes(searchData));

Its hard to give a full answer based on the limited information you gave above. If this code doesn't work exactly for you, providing an MVP in a StackBlitz example would help you solve your exact problem.


text:
Q: htaccess reg exp with params I have this url with optional params at the end :
http://domain.local/?_escaped_fragment_=watch/1/10/test/optionalparams/optionalparams/optionalparams/optionalparams..

and i want to redirect it to
http://domain.local/videos/watch/test?id=10

I tried a lot of htaccess rewrite rules and conds but it's not working at all..
This is my htaccess :
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)/(.*)/(.*)/(.*)(/(.*)?)$
RewriteRule ^(.*) /videos/%1/%4?id=%3 [NC,R=301]

Can someone help me to find the solution.. :)
Thanks in advance !

Edit more precisions :
When i try this url :
?_escaped_fragment_=watch/1/10/title

with this rewrite rule
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)/(.*)/(.*)/(.*)$
RewriteRule ^(.*) /videos/%1/%4?id=%3 [NC,R=301]

It's working like i want !
But if i try an url with anything after /title like this
?_escaped_fragment_=watch/1/10/title/param/param/param

It's not working...
I've tried with this reg ex with a different cond
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)/(.*)/(.*)/(.*)(/(.*)?)$
RewriteRule ^(.*) /videos/%1/%4?id=%3 [NC,R=301]

I don't understand why it's not working.. Can someone help me ? Thanks !

A: Ok i found the solution :
RewriteCond %{QUERY_STRING} ^_escaped_fragment_=/([a-zA-Z0-9\-]+)/([0-9]+)/([0-9]+)/([a-zA-Z0-9\-]+)
RewriteRule ^(.*) /videos/%1/%4/?id=%3&page=%2 [NC,R=301]


text:
Q: Difference between power and falling power I have the following question about the difference between a falling power equation and a very similar equation using normal power:
Let $m$ and $C$ be some positive integer constants, where $C > m$, and let:
$f(x) = \frac{(C-x)^\underline{m}}{D^\underline{m}}$
where $\underline{m}$ above denotes the falling factorial (e.g.: $x^\underline{4} = x(x-1)(x-2)(x-3)$).
$g(x) = \frac{(C-x)^m}{D^m}$, where $0\leq x \leq C$.
The reason for this is that $g(x)$ seems to be a "reasonable'' (for my purposes) approximation of $f(x)$. But I would like to know how "inaccurate" $g(x)$ is from $f(x)$.
To this end, I would like to know about the difference $d(x) = f(x) - g(x)$ and in particular how big it can get over the valid values of $x$. I have made a few plots and found that $d(x)$ will always have a single hump (largest difference) for some value of $x$. An example is like below ($C = 128$, $m=4$, y-axis is $d(x)$, x-axis is $x$):

Also, as $C$ increases in size, I find that the largest value of $d(x)$ gets smaller and smaller.
How can I prove this observation or maybe even show some bounds on it? Could someone give me some pointers or direction on how to approach answering the above question?
Thank you so much!


text:
Q: Odd accuracy error Java Currently I am attempting to write a change machine in java.  For some reason there is a large loss in accuracy during conversion.
It will first ask for the data values of how much is owed and how much is paid.  Then it will divide out the numbers of quarters and mod out the remainder.  Then it will perform this with dimes, nickles, and then pennies. After this it will then print out how much change is owed.
import java.io.*;
import static java.lang.System.*;

import java.util.Scanner;

class change{

     public static void main (String str[]) throws IOException {

            //asker thingy
            Scanner scan = new Scanner(System.in);
            System.out.println("Please enter the Cost of the Item:");
            System.out.print("$");
            double costowed = scan.nextDouble();
            System.out.println("Please Enter the Amount Payed:");
            System.out.print("$");
            double costpayed = scan.nextDouble();

            //Quarters
            double a1 = Math.round( (costpayed - costowed) * 100);
            int quarters = (int)(a1 / 25);
            int a2 = (int)(a1 % 25);

            //dimes
            int dimes = (int)(a2 / 10);
            int a3 = (int)(a1 % 10);

            //nickles & pennies
            int nickles = (int)(a3 / 5);
            int pennies = (int)(a1 % 5);

            //change owed
            double arc = (double)(a1 / 100);

            //print sequence
            System.out.println("Change owed: " + arc);
            System.out.println("Quarters: " + quarters);
            System.out.println("Dimes: " + dimes);
            System.out.println("Nickles: " + nickles);
            System.out.println("Pennies: " + pennies);
     }

}

A: The line
int a3 = (int)(a1 % 10);

should be:
int a3 = (int)(a2 % 10);

And likewise int pennies = (int)(a1 % 5); should be int pennies = (int)(a3 % 5);.


text:
Q: check who is connected to a specific computer on the network? In our network (Active Directory based) we have several (Windows) computers that I can connect via remote desktop.
But when I connect to a pc when someone else is already connected, that person is kicked.
Is there a way to check if someone is connected (and get his name) to a specific computer on the network via a command line?

A: It can be done using PowerShell; I needed to do this for largely the same reason. I have a modified version of Brian Wilhite's Get-LastLogon script; my version is somewhat stripped down because I don't need to worry about anything earlier than Windows 7 on our network. I should note that my environment guarantees that any computer I run this on will be running PowerShell 4 or 5.1; if you are running PowerShell Core (6 or later), you will probably have to modify it to change WMI calls to CIM calls, at the very least.

A: You can try command qwinsta /server: servername. It will display information about sessions on a Remote Desktop Session Host server.


text:
Q: Getting ScopeButtons to work in MonoTouch UISearchBar I've created a custom UISearchBarDelegate.
In the OnEditingStarted-event, I'm adding scope buttons to the search bar:
public override void OnEditingStarted(UISearchBar searchBar)
{
    searchBar.ScopeButtonTitles = new[] { "Scope 1", "Scope 2" };
    searchBar.ShowsCancelButton = true;
    searchBar.ShowsScopeBar = true;
}

This is working as expected, the scope buttons are shown underneath the search field.
The only thing is, I'm not able to toggle the scope. When tapping "Scope 2" nothing happens, not even visually.
Are there any other settings one is supposed to do, in order get this working?
Are there known/common pitfalls that can prevent (scope)buttons from working?


text:
Q: Why does this regex match one MAC address but not another? I need to use ruby to find a MAC Address in some text. The format of the MAC address is in the text is XXXX.XXXX.XXXX, where X could be an upper or lower case letter from A-F, or a number from 0-9.
I then need to convert the said MAC into this format: XX:XX:XX:XX:XX:XX.
The below code works when the MAC address in some_text is a081.572c.9a04, but doesn't work when it is 9c21.0adf.9a41.
# Matches
some_text = "some text a081.572c.9a04 some other text ..."
mac_addr = some_text.scan(/.\d+[A-Fa-f0-9].\d+[A-Fa-f0-9].\d+[A-Fa-f0-9].\d+/)[0]
puts mac_addr.to_s.gsub('.','').scan(/\w{2}/).join(':')

=> a0:81:57:2c:9a:04

# Does not match
some_text = "some text 9c21.0adf.9a41 some other text ..."
mac_addr = some_text.scan(/.\d+[A-Fa-f0-9].\d+[A-Fa-f0-9].\d+[A-Fa-f0-9].\d+/)[0]
puts mac_addr.to_s.gsub('.','').scan(/\w{2}/).join(':')

=>

Why does this code match a081.572c.9a04, but not 9c21.0adf.9a41, when they both have the same character groups?

A: You are looking for:

*

*any character

*followed by a sequence of decimal digits (at least one)

*followed by a single hexadecimal digit

*followed by any character

*followed by a sequence of decimal digits (at least one)

*followed by a single hexadecimal digit

*followed by any character

*followed by a sequence of decimal digits (at least one)

*followed by a single hexadecimal digit

*followed by any character

*followed by a sequence of decimal digits (at least one)

Your second example already fails at step #2:

*

*any character: check, we have 9

*followed by a sequence of decimal digits (at least one): FAIL!!! After the 9, we have c which is not a decimal digit, but you specified that there has to be at least one decimal digit after the first character

So, the reason why the second example is not considered to be a MAC address is simply that you have specified that a MAC address starts with any arbitrary character (?, !, , doesn't matter) followed by a sequence of decimal digits (0-9).
A more sensible way to characterize a MAC address written in the format you describe, would something like this:
/\b\h+(?:\.\h+){2}\b/

A sequence of hexadecimal digits in the beginning followed by a period, followed by sequence of digital digits, and repeating that twice. The whole thing enclosed in word boundaries.
You said that the MAC address is always in groups of 4, but are you sure about that? What about leading zeroes? What about all zeroes? Would they be written 0.0.0 or 0000.0000.0000?
The "really correct" way would be to parse your MAC address as a three-digit number in base 65536 and then pretty-print it as a 6-digit number in base 256.