text:
Q: Create Panel from DataFrame I am a new to python and pandas. And I have a problem in creating Panel at pandas.
def sq_error(w0,w1,x,y):
    return (y - (w0 - w1 * x)) ** 2;

d = dict()
w0 = 50
for w1 in range(0, 10):
    data['height_error'] = data.apply(lambda row: sq_error(w0,w1,row['Weight'],
                                              row['Height']), axis=1)
    df = data[['height_error','Weight']]
    d['df'] =  df
    d['w1'] = w1

p = pd.Panel(d)

I'm getting error 'int' object has no attribute 'shape'
I tried with list
d = dict()
w0 = 50
for w1 in range(0, 10):
    data['height_error'] = data.apply(lambda row: sq_error(w0,w1,row['Weight'],
                                              row['Height']), axis=1)
    l = df[['height_error','Weight']].values.tolist()
    d['df'] = l
    d['w1'] = w1

p = pd.Panel(d)

But still getting same error

A: Pandas is trying to access w1 as a dataFrame but it's an int. So of course it does not have a shape attribute
You should write d[w1]=df
d = dict()
w0 = 50
for w1 in range(0, 10):
    data['height_error'] = data.apply(lambda row: sq_error(w0,w1,row['Weight'],row['Height']), axis=1)
    l = df[['height_error','Weight']].values.tolist()
    d[w1] = df

p = pd.Panel(d)

Thus Pandas will accept it as a dictionary with integer keys and DataFrame values.


text:
Q: reduce image size (physical and dimensions) coming from HttpPostedFileBase then convert to base64 Does anyone have a good example of converting an image file coming from a HttpPostedFileBase to a reduced size and then converting the image to base64?  I've spent hours on this with out any luck.  Here is the start of my code.  Some of which is hardcoded (image size).
This is giving me a black image when I place the base64 in an image tag and view it in a browser.
    public ActionResult Upload(HttpPostedFileBase file, decimal? id, decimal? id2)
    {
            Image img = Image.FromStream(file.InputStream, true, true);

            var bitmap = new Bitmap(img.Width - 100, img.Height - 100);

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] imageBytes = stream.ToArray();
            string base64String = Convert.ToBase64String(imageBytes);
            InsertImage(base64String);
     }

I'm asking how to change the image then convert it to base64.  This is more specific than the question called it duplicate.

A: I have never used the HttpPostedFileBase myself.  So, I simplified the problem a bit, which is actually what you should try to do with future questions.  You should try to narrow the focus as much as possible.  That said, here is a method that reduces the dimensions of an image represented by a stream and returns the new image as an array of bytes.
    private static byte[] ReduceSize(FileStream stream, int maxWidth, int maxHeight)
    {
        Image source = Image.FromStream(stream);
        double widthRatio = ((double)maxWidth) / source.Width;
        double heightRatio = ((double)maxHeight) / source.Height;
        double ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio;
        Image thumbnail = source.GetThumbnailImage((int)(source.Width * ratio), (int)(source.Height * ratio), AbortCallback, IntPtr.Zero);
        using (var memory = new MemoryStream())
        {
            thumbnail.Save(memory, source.RawFormat);
            return memory.ToArray();
        }
    }

You can probably call this method like this:
public ActionResult Upload(HttpPostedFileBase file, decimal? id, decimal? id2)
{
    byte[] imageBytes = ReduceSize(file.InputStream, 100, 100);
    string base64String = Convert.ToBase64String(imageBytes);
    InsertImage(base64String);
}

My ReduceSize() method maintains aspect ratio. You may not need that, and you may also want to change the arguments so you can change how you specify how it is resized.  Give that a shot and let me know how it does.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent Unhandled 'error' event when starting lite-server? I install lite-server using:
npm install lite-server

But it generates the message bellow:
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

And if run:
npm run lite-server

It gives me this error:
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: watch web_app/node_modules/babel-generator/node_modules/lodash/isObject.js ENOSPC
    at exports._errnoException (util.js:1022:11)
    at FSWatcher.start (fs.js:1429:19)
    at Object.fs.watch (fs.js:1456:11)
    at createFsWatchInstance (/var/www/html/web_app/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/var/www/html/web_app/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/www/html/web_app/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleFile (/var/www/html/web_app/node_modules/chokidar/lib/nodefs-handler.js:255:21)
    at FSWatcher.<anonymous> (/var/www/html/web_app/node_modules/chokidar/lib/nodefs-handler.js:473:21)
    at FSReqWrap.oncomplete (fs.js:123:15)

I found this: https://github.com/angular/angular-cli/issues/2692, but I doesn't solve my problem.
Is there anyone who met this problem before, and how can I solve it?
Thanks!

A: After several research, I came across with this solution:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

I still don't know why I need to do this, but it works. ;)


text:
Q: Definition of connecting homomorphism for Mayer-Vietoris sequence Given a manifold $M$ and opens sets $U_1,U_2 \subseteq M$ such that $M=U_1 \cup U_2$, the Connecting Homomorphism for Mayer-Vietoris sequence is defined as $$\delta: H^p(U_1 \cap U_2) \rightarrow H^{p+1}(M) \\ [\omega] \mapsto \begin{cases} [-d(\rho_2 \omega)]  \quad\text{on}\ U_1 \\ [d(\rho_1 \omega)]  \quad \text{on} \ U_2  \end{cases}$$
where $\{\rho_j\}_{j=1,2}$ is a partition of unity subordinate to $\{U_j\}_{j=1,2}$.
So $d(\rho_j \omega)$ is an exact $(p+1)$-form for $j=1,2$. Why its cohomology class is not zero on $H^{p+1}(M)$?


text:
Q: Session popup window I want the popup to be displayed only once the window loads, but iam unable to find the solution.
Below is the source code:

<?php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$course = $_POST['course'];

$formcontent='

        <title>Message</title>

Thorsignia

Name:   '.$name.'

Phone:   '.$phone.'

Email:  '.$email.'

Course:  '.$course.'

';

$recipient = "abc@xyz.com";
$subject = "Customer Enquiry";
$mailheader = "MIME-Version: 1.0" . "\r\n";
$mailheader .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$mailheader .= "From: $email \r\n";

if(mail($recipient, $subject, $formcontent, $mailheader)){

 echo "";

}else{

 echo "";
}

 // header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

So i need only the popup to be displayed once as the window load in, that is i need to maintain a session , so please help me as how to maintain the session.

A: Try this:
Create a session after sending message and check the session is set or not. if Session is set pop up the window and unset the session with in the  condition. `
// check if session is not set
if(!isset($_SESSION['seesion_name'])) { `
   // code here to poup the window
   $_SESSION['seesion_name'] == True; // set session if popup shown once
} `


text:
Q: How to create below chart with E'chart JS I have use the echart js and now create this type of chart with e'chart. it is posible with E'chart JS.
enter image description here

A: `var dataAll = [
            [20,14,28,29,200,9,24,20,14,28,29,200,9,24,20,14,28,29,200,9,24,20,14,28,29,200,9,24,20,14,28,29,200,9,24,20,14,28,29,200,9,24],
            [2,7,3,2,5,1,8,2,7,3,2,5,1,8,2,7,3,2,5,1,8,2,7,3,2,5,1,8,2,7,3,2,5,1,8,2,7,3,2,5,1,8],
            [34,15,30,53,65,15,48,34,15,30,53,65,15,48,34,15,30,53,65,15,48,34,15,30,53,65,15,48,34,15,30,53,65,15,48,34,15,30,53,65,15,48],
            [38,12,35,58,68,16,49,38,12,35,58,68,16,49,38,12,35,58,68,16,49,38,12,35,58,68,16,49,38,12,35,58,68,16,49,38,12,35,58,68,16,49],
        ];
option = {
        color: ['#fff'],

        tooltip : {
            trigger: 'axis',
            axisPointer : {
                type : 'shadow'
            }
        },
        legend: [{
            data: ['Biding', 'Cancel', 'Cancel By User'],
            align: 'left',
        },
        {
            data: ['Driver Rating'],
            align: 'left',
            bottom:'10%',
        },
        ],

        grid: [
            {x: '10%', y: '5%', width: '85%', height: '30%'},

            {x: '10%', y2: '18.3%', width: '85%', height: '30%'},

        ],
        //calculable : true,
        xAxis : [
            {type:'category',gridIndex: 0, data : ['Operator 1', 'Operator 2', 'Operator 3', 'Operator 4', 'Operator 5', 'Operator 6', 'Operator 7','Operator 8', 'Operator 9', 'Operator 10', 'Operator 11', 'Operator 12', 'Operator 13', 'Operator 14', 'Operator 15','Operator 16', 'Operator 17', 'Operator 18', 'Operator 19', 'Operator 20', 'Operator 21','Operator 1', 'Operator 2', 'Operator 3', 'Operator 4', 'Operator 5', 'Operator 6', 'Operator 7','Operator 8', 'Operator 9', 'Operator 10', 'Operator 11', 'Operator 12', 'Operator 13', 'Operator 14', 'Operator 15','Operator 16', 'Operator 17', 'Operator 18', 'Operator 19', 'Operator 20', 'Operator 21'],  axisTick: {show: false},nameGap:'40',axisLabel: {fontWeight: 'bold',rotate: 60}},
            {type:'category',gridIndex: 1, data : ['Operator 1', 'Operator 2', 'Operator 3', 'Operator 4', 'Operator 5', 'Operator 6', 'Operator 7','Operator 8', 'Operator 9', 'Operator 10', 'Operator 11', 'Operator 12', 'Operator 13', 'Operator 14', 'Operator 15','Operator 16', 'Operator 17', 'Operator 18', 'Operator 19', 'Operator 20', 'Operator 21','Operator 1', 'Operator 2', 'Operator 3', 'Operator 4', 'Operator 5', 'Operator 6', 'Operator 7','Operator 8', 'Operator 9', 'Operator 10', 'Operator 11', 'Operator 12', 'Operator 13', 'Operator 14', 'Operator 15','Operator 16', 'Operator 17', 'Operator 18', 'Operator 19', 'Operator 20', 'Operator 21'],axisLabel:{show:false},axisTick: {show: false}},
        ],
        yAxis : [
            {type:'value',gridIndex: 0,splitLine:{lineStyle:{type:'dashed'}},  axisTick: {show: false},axisLabel: {show: false},axisLine: {show: false},splitLine: {show: false}},
            {type:'value',gridIndex: 1,inverse:true,splitLine:{lineStyle:{type:'dashed'}}, axisTick: {show: false},axisLabel: {show: false},axisLine: {show: false},splitLine: {show: false}},

        ],
        /*dataZoom: [
        {
            show: true,
            realtime: true,
            start: 1,
            end: 50,
            xAxisIndex: [0, 1]
        },
        {
            type: 'inside',
            realtime: true,
            start: 1,
            end: 50,
            xAxisIndex: [0, 1]
        }
    ],*/
        series : [
            {
                name: 'Biding',
                type: 'bar',
                xAxisIndex: 0,
                yAxisIndex: 0,
                data: dataAll[0],
                stack: 'Total amount',
                itemStyle:{color:'#62cf72'},
                barWidth:20,
                label: {
                    normal: {
                        show: false,
                        position: 'top'
                    }
                },
            },
            {
                name: 'Cancel',
                type: 'bar',
                xAxisIndex: 0,
                yAxisIndex: 0,
                stack: 'Total amount',
                data: dataAll[2],
                itemStyle: {color: '#fa76ee'},
                barWidth:20,

                label: {
                    normal: {
                        show: false,
                        position: 'top'
                    }
                },
            },
            {
                name: 'Cancel By User',
                type: 'bar',
                xAxisIndex: 0,
                yAxisIndex: 0,
                stack: 'Total amount',
                data: dataAll[3],
                itemStyle: {color: '#739ffe'},
                barWidth:20,

                label: {
                    normal: {
                        show: false,
                        position: 'top'
                    }
                },
            },
            {
                name: 'Driver Rating',
                type: 'bar',
                xAxisIndex: 1,
                yAxisIndex: 1,
                data: dataAll[1],
                itemStyle: {color: '#feb082'},
                barWidth:20,
                label: {
                    normal: {
                        show: false,
                        position: 'bottom'
                    }
                },
            },

        ]
    });

`


text:
Q: Migration from MySQL to Postgresql with auto-increments - how? I'm considering a MySQL to Postgresql migration for my web application, but I'm having a really hard time converting my existing MySQL database to Postgresql.
I tried :

*

*mysldump with --compatible=postgresql

*migration wizard from EnterpriseDB

*Postgresql Data Wizard from EMS

*DBConvert from DMSoft

and NONE of the above programs do a good job converting my database!
I saw some Perl and Python scripts for converting mysql to postgresql, but I can't figure out how to use them....(I installed ActivePerl and don't understand what I'm supposed to do next to run that script!)
I use Auto Increment fields (as a primary key) all the time, and these are just ignored... I understand that Postgresql does auto-increments in another way (with sequences), but it can't be THAT hard for MIGRATION software to implement that, or is it?
Did anybody have better luck converting a MySQL database with auto-increments as primary keys?

A: I know this is probably not the answer you are looking for, but: I don't believe in "automated" migration tools.
Take your existing SQL Scripts that create your database schema, do a search and replace for the necessary data types (autonumber maps to serial which does all the sequence handling automagically for you), remove all the "engine=" stuff and then run the new script against Postgres.
Dump the old database into flat files and import them into the target.
I have done this several times with sample databases that were intended for MySQL and it really doesn't take that long.
Probably just as long as trying all the different "automated" tools.

A: Why not use an ETL Tool? you dont have to worry about dumps or stuff like that.
I have migrated to PostgresSQL and MySQL and have had no problems with the auto increment fields.
You just need to know the connection credentials and thats it. I personally use Pentaho ( it's open source ).
Download Pentaho ETL from http://kettle.pentaho.org/
Unzip and run Pentaho (using .bat file spoon.bat)
Create a new Job:
Create DB connection for source data base (PostgreSQL) - using menu: Tools→Wizard→Create DataBase Connection (F3) Create DB connection for destination data base (Mysql) - using technique described above.
Run the Wizard: Tools → Wizard → Copy Tables (Ctrl-F10).
Select source (left dialog panel), and destination (left dialog panel). Click Finish.
The Job will be generated - Run the job.
If you need any help let me know.

A: Even when you familiar with all "PostgreSQL gotchas", doing every step by hand may take a lot of time, especially when your db is "big".
Try some other scripts/tools.

A: I know this is an old question but I just ran into the same problem migrating from MySQL to Postgres. After trying several migration tools out the very best one I could find, which will migrate your database structure as cleanly as possible, was Pgloader https://github.com/dimitri/pgloader/ it will take care of changing the Auto Increment to Postgres sequences no problem and it's super fast.


text:
Q: Terraform Error: Failed to load plugin schemas I'm adding a new module to an existing project.
I get the message that I have to do a terraform init to recognise the new module.
aws.tf:
provider "aws" {
  access_key = var.access_key
  secret_key = var.secret_key
  region     = var.region
}

terraform.tfvars:
access_key = "Removed"
secret_key = "Removed"
region     = "ap-southeast-2"

When I do that, it downloads the latest aws
- Installing hashicorp/aws v4.40.0...

Then I get below...

│ Error: Failed to load plugin schemas
│
│ Error while loading schemas for plugin components: Failed to obtain provider schema: Could not load the schema for
│ provider registry.terraform.io/hashicorp/aws: failed to instantiate provider "registry.terraform.io/hashicorp/aws" to
│ obtain schema: Unrecognized remote plugin message:
│
│ This usually means that the plugin is either invalid or simply
│ needs to be recompiled to support the latest protocol...
╵

So seems the latest aws schema is corrupt???
I can't progress.
I've copied over an older aws schema but I still have to do a terraform init and it always updates the aws schema. So stuck here.
Even if i create a new folder and have nothing in the folder and just start with terraform on its own and do an init, it creates the .terraform folder and installs the aws schema.
Then do terraform plan I get the schema error.
Terraform v1.3.5
AWS schema v4.40.0
Windows 10
Thanks in advance.

A: OK the problem was the Trend Micro Anti Virus killing the process. I've whitelisted terraform.exe in the client computer and all good now. Thanks for the responses. Hopefully this helps someone in future.


text:
Q: Reflection - casting object to interface Following on from How to reflect an interfaced type<t> at runtime I have an instance of a type that I know is inherited from base type DataPointProcessorBase
This base class is relatively simple
public abstract class DataPointProcessorBase<T> : IDataPointProcessor<T> where T : class, IDataPointInput, new()
{
    public abstract DataPointOutputBase GetOutput(T input);
}

Age_Input implements the interface and Age_Processor is set up to receive it
public class Age_Input : DataPointInputBase, IDataPointInput
{
    public int AgeExact { get; set; }
}
public class Age_Processor : DataPointProcessorBase<Age_Input>
{
    ...
}

Using reflection, I'm half way to casting it properly so I can call GetOutput()
Any ideas why I can't get into first if statement below?
var instance = Activator.CreateInstance(type);

if (instance is IDataPointProcessor<IDataPointInput>)//why can I not cast interface here?
{
    //false
}

if (instance is IDataPointProcessor<Age_Input>)//hard-coded - works fine
{
    var processor = instance as IDataPointProcessor<Age_Input>;
    Age_Input temp = item as Age_Input;
    if (temp is IDataPointInput)
    {
        //also true
    }
    var result = processor.GetOutput(temp);
}

A: This question is asked every day.  One more time!
Is a basket of apples usable when you need a basket of fruit?  No.
Why not? Because you can put a banana into a basket of fruit, but you cannot put a banana into a basket of apples.
Therefore you cannot use a basket of apples where a basket of fruit is needed.
Similarly, a basket of fruit is not usable as a basket of apples, because it might already contain a banana.
The relationship "a C<X> can be used as a C<Y> if an X can be used as a Y" is called covariance, and C# only supports covariance in a very limited set of circumstances:

*

*C<T> must be an interface or delegate

*The interface or delegate declaration must be marked as safe for variance.

*The compiler must successfully verify that the variance declaration is guaranteed to be safe.

*Both X and Y must be reference types.

In your case, you have got the first and fourth properties but you have not got the second and third.
Mark IDataPointProcessor<T> like this:
interface IDataPointProcessor<out T>

which means roughly "T is used only at output positions, never input positions".  If baskets have no ability to add fruit then the objection -- you can't put a banana into a basket of apples -- vanishes, and it becomes legal.
If the compilation succeeds then covariance will start working on IDataPointProcessor.  If not, you're probably using T in a position where a T can flow in.  The rules are a bit more subtle than I'm summarizing here; if you need a detailed description, I wrote one here: https://blogs.msdn.microsoft.com/ericlippert/2009/12/03/exact-rules-for-variance-validity/
That's why you can use an IEnumerable<Giraffe> as an IEnumerable<Animal> -- all four conditions are met.

A: I've solved this and How to reflect an interfaced type<t> at runtime by avoiding the issue entirely by not using reflection. Full answer on that page if anybody interested
Thanks all for your time
@Eric I had indeed found your article beforehand, but my head hurt at that point!

A: From what I understand, The way generic types work in the C# compiler is that the strongly typed types that are used in those generic parameters at compile time (meaning they are used in your code) are generated dynamically as strongly typed classes (Possibly on the MSIL layer).
So during run time your object doesn't have inherited Type with a generic type but instead a inherited type of a strong type.
You can build a switch case of each possible strongly typed type and try to cast to it.


text:
Q: Python ast Libary - how to retreive value of a specific node I have the following script:
extras_require={"dev": dev_reqs}
x = 3
entry_points={
    "console_scripts": ["main=smamesdemo.run.main:main"]
}

I want to retrieve the following part as python data, dict and list not Nodes.
entry_points={
    "console_scripts": ["main=smamesdemo.run.main:main"]
}

I have tried the following, but I am not actually able to get the values with this:
import ast

class CustomNodeTransformer(ast.NodeTransformer):
    def visit_Assign(self, node):
        print(node.value.__dict__)
        return node

with open("./setup.py") as f:
    code = f.read()

    node = ast.parse(code)
    CustomNodeTransformer().visit(node)

{'keys': [<ast.Constant object at 0x0000029E992962C0>], 'values': [<ast.Name object at 0x0000029E99296260>], 'lineno': 1, 'col_offset': 15, 'end_lineno': 1, 'end_col_offset': 32}

Expected:
entry_points={"console_scripts": ["main=smamesdemo.run.main:main"]}

Can anyone help me to achieve this?

A: You should use ast.NodeVisitor rather than ast.NodeTransformer since you are not making modifications to nodes. But for the purpose of retrieving a single node, it is simpler to use ast.walk instead to traverse the AST in a flat manner and find the ast.Assign node whose target id is 'entry_points', and then wrap its value in an ast.Expression node for compilation with compile and evaluation with eval into an actual Python dict. Remember to use ast.fix_missing_locations to realign the line numbers and offsets of the node when you plant it into another tree:
import ast

code = '''extras_require={"dev": dev_reqs}
x = 3
entry_points={
    "console_scripts": ["main=smamesdemo.run.main:main"]
}'''

for node in ast.walk(ast.parse(code)):
    if isinstance(node, ast.Assign) and node.targets[0].id == 'entry_points':
        expr = ast.Expression(body=node.value)
        ast.fix_missing_locations(expr)
        entry_points = eval(compile(expr, filename='', mode='eval'))

print(entry_points)

This outputs:
{'console_scripts': ['main=smamesdemo.run.main:main']}

Demo: https://replit.com/@blhsing/OrangeredCurlyApplication

A: From Python 3.9 you can use the ast.unparse function to get the equivalent code as a string from a Node
import ast

class CustomNodeTransformer(ast.NodeTransformer):
    def visit_Assign(self, node):
        print(ast.unparse(node))
        return node

code = """
extras_require={"dev": dev_reqs}
x = 3
entry_points={
    "console_scripts": ["main=smamesdemo.run.main:main"]
}
"""
node = ast.parse(code)
CustomNodeTransformer().visit(node)

# Output:
# extras_require = {'dev': dev_reqs}
# x = 3
# entry_points = {'console_scripts': ['main=smamesdemo.run.main:main']}


text: Q: Transfer guest order to customer account If a guest places an order without registering for an account and they register for a customer account at a later date, can the original order be linked to their customer account? If so, how can this be done in CE v1.9.2.1?


text:
Q: LaTex - Exact math I am quite new to LaTex and I am wondering if it's possible to use exact math in LaTex. I.e. I want to feed the script some input, which may be either a number or a variable, and it should perform some calculations on it (e.g. multiply/divide) and print the exact solution.
Consider this .tex file:
\documentclass{article}

\newcommand\mass{30}
\newcommand\acc{9.8}

\newcommand\force{\the\numexpr \mass * \acc \relax} % F=m*a

\begin{document}
  \section{Exerted force}
    F = \force N
\end{document}

This prints F = 270.8N when mass = 30 and acc = 9.8. Can this script, however, be modified in order that changing acc to a variable like g instead of a number will print F = 30g?
EDIT:
I should not have used the words 'exact math' as they are misleading as to my intentions. I have rephrased the question and it's posted here: LaTex - perform algebraic operations on variables

A: There are high-level packages for this, siunitx and xfp. The latter provides \fpeval for math expressions with a fairly natural notation.
The former provides bells and whistles for formatting numbers and units.
\documentclass{article}
\usepackage{siunitx,xfp}

\newcommand\mass{30}
\newcommand\acc{9.8}

\newcommand\force{\fpeval{\mass * \acc}}

\begin{document}

$F = \SI{\force}{N}$

$F = \SI[scientific-notation=fixed,fixed-exponent=2]{\force}{N}$

\end{document}


text:
Q: iFrame permalinks on Wordpress Can someone help me fix this links from https://smallcaps.com.au/stocks/?symbol=DTR  make it https://smallcaps.com.au/stocks/DTR ? the link I posted here is handle by iFrame, I just want to make the links looks clean instead of having "?symbol="

A: What you want is not possible.
The iframe on your page is generated by a script from WebLink that requires the ?symbol= parameter in the URL to be able to generate the correct iframe.
If you rewrote the URL the way you want the script would not work, since the symbol parameter doesn't exist anymore. WordPress would be able to access the value, but the script would not see it anymore, and it's the script that creates the iframe.
You will need to check with WebLink to see if it's possible to set the stock symbol for the iframe a different way.


text:
Q: Apple software: moving Mail to an older computer My Macbook Pro under Sierra needs repair. While it is being repaired, I am reverting to an old machine running Yosemite. Does anyone know if the format of Apple Mail files has changed between Yosemite and Sierra?
My idea is to copy Library/Mail from the machine for repair to the Yosemite machine. Will that work? Are there other files (for Apple Mail) that I should copy before taking it to the repair shop? Presumably plist files should not be copied over.
Thanks, David

A: I moved mail from Sierra to El-Capitan and it worked fine. There are no reported problems with the scenario you're describing. I'd suggest following this Apple Doc before sending your mac for repair and check that everything is working, though.
Mail for Mac: Import or export mailboxes


text:
Q: find mean and standard deviation for current and power Given that the noise current out of a 5Ω resistor is normally distributed
with a mean of 0 and a standard deviation of 2 milliamps.
Determine the power distribution out of the resistor, $fP(p)$.
Determine the mean and standard deviation for the current
and the power using Taylor's series.
$P = i^2R$.
Edited: More clarification
So the Taylor Series for P would be using the function $P = i^2R$ and the Taylor Series for current would be $I=sqrt(P/R)$?

A: Let $X \sim \mathcal{N}(0,1)$ then $X^2 \sim \chi^2(1)$ is a chi-square distribution with one degrees of freedom of mean $1$ and variance $2$.
Using the above, for $i \sim \mathcal{N}(0,2)$, then $i^2 \sim \chi^2(1)$ is a chi-square distribution with one degrees of freedom of mean $2$ and variance $8$. Note that
Therefore, $P = i^2 R \sim \chi^2(1)$ is also chi-square with $1$ degrees of freedom, of mean $10$ and variance $8 \times R^2 = 200$ .


text:
Q: Fixed image mask reveal image underneath on scroll there is probably a super simple solution to this...
I'm trying to create a portfolio page and I want to show a screenshot of a mobile site in context.
So for example, I have a tall screenshot image of the full page and I want to have it masked by an image of a mobile phone where it will only show up on the screen area. As you scroll, I want the phone to have fixed positioning and reveal the screenshot underneath in its "viewport".
Here's a diagram of what I mean:

Any thoughts?


text:
Q: How do I get the import/export working for chrome browser? I'm very, very new to learning HTML, CSS, and JS. I'm attempting to write my first page that my 'main.js' file imports a function from my 'utils.js' file to use in my 'index.html' file. My browser is google chrome Version 85.0.4183.121 (Official Build) (64-bit), and I'm running on a os of Windows 10.
The tutorial I'm trying to learn from is: (on youtube.com)
"JavaScript Modules with Import/Export Syntax (ES6) - JavaScript Tutorial"
channel is:
"dcode"
url:
https://youtu.be/s9kNndJLOjg
Below is a representation of all I've done following along.
My folder/file tree looks like below: (on Desktop)

HTML_folder-
            |-js_folder-
            |           |-main.js
            |           |-utils.js
            |
            |-index.html

My index.html document looks like below:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=10.0">
  <title>Chrome Dino Replica</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    canvas {
      display: block;
    }
  </style>
</head>
<body>
  <canvas id="game" width="640" height="400"></canvas>
  <script type="module" src="./js_folder/main.js"></script>
</body>
</html>

My main.js document looks like below:
import {double} from './utils.js';

console.log(double(5));

const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');

// Variables
let score;
let scoreText;
let highscore;
let highscoreText;
let player;
let gravity;
let obstacles = [];
let gameSpeed;
let keys = {};

// Event Listeners
document.addEventListener('keydown', function (evt) {
  keys[evt.code] = true;
});
document.addEventListener('keyup', function (evt) {
  keys[evt.code] = false;
});

class Player {
  constructor (x, y, w, h, c) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.c = c;

    this.dy = 0;
    this.jumpForce = 15;
    this.originalHeight = h;
    this.grounded = false;
    this.jumpTimer = 0;
  }

  Animate () {
    // Jump
    if (keys['Space'] || keys['KeyW']) {
      this.Jump();
    } else {
      this.jumpTimer = 0;
    }

    if (keys['ShiftLeft'] || keys['KeyS']) {
      this.h = this.originalHeight / 2;
    } else {
      this.h = this.originalHeight;
    }

    this.y += this.dy;

    // Gravity
    if (this.y + this.h < canvas.height) {
      this.dy += gravity;
      this.grounded = false;
    } else {
      this.dy = 0;
      this.grounded = true;
      this.y = canvas.height - this.h;
    }

    this.Draw();
  }

  Jump () {
    if (this.grounded && this.jumpTimer == 0) {
      this.jumpTimer = 1;
      this.dy = -this.jumpForce;
    } else if (this.jumpTimer > 0 && this.jumpTimer < 15) {
      this.jumpTimer++;
      this.dy = -this.jumpForce - (this.jumpTimer / 50);
    }
  }

  Draw () {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.fillRect(this.x, this.y, this.w, this.h);
    ctx.closePath();
  }
}

class Obstacle {
  constructor (x, y, w, h, c) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.c = c;

    this.dx = -gameSpeed;
  }

  Update () {
    this.x += this.dx;
    this.Draw();
    this.dx = -gameSpeed;
  }

  Draw () {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.fillRect(this.x, this.y, this.w, this.h);
    ctx.closePath();
  }
}

class Text {
  constructor (t, x, y, a, c, s) {
    this.t = t;
    this.x = x;
    this.y = y;
    this.a = a;
    this.c = c;
    this.s = s;
  }

  Draw () {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.font = this.s + "px sans-serif";
    ctx.textAlign = this.a;
    ctx.fillText(this.t, this.x, this.y);
    ctx.closePath();
  }
}

// Game Functions
function SpawnObstacle () {
  let size = RandomIntInRange(20, 70);
  let type = RandomIntInRange(0, 1);
  let obstacle = new Obstacle(canvas.width + size, canvas.height - size, size, size, '#2484E4');

  if (type == 1) {
    obstacle.y -= player.originalHeight - 10;
  }
  obstacles.push(obstacle);
}

function RandomIntInRange (min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

function Start () {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  ctx.font = "20px sans-serif";

  gameSpeed = 3;
  gravity = 1;

  score = 0;
  highscore = 0;
  if (localStorage.getItem('highscore')) {
    highscore = localStorage.getItem('highscore');
  }

  player = new Player(25, 0, 50, 50, '#FF5858');

  scoreText = new Text("Score: " + score, 25, 25, "left", "#212121", "20");
  highscoreText = new Text("Highscore: " + highscore, canvas.width - 25, 25, "right", "#212121", "20");

  requestAnimationFrame(Update);
}

let initialSpawnTimer = 200;
let spawnTimer = initialSpawnTimer;
function Update () {
  requestAnimationFrame(Update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  spawnTimer--;
  if (spawnTimer <= 0) {
    SpawnObstacle();
    console.log(obstacles);
    spawnTimer = initialSpawnTimer - gameSpeed * 8;

    if (spawnTimer < 60) {
      spawnTimer = 60;
    }
  }

  // Spawn Enemies
  for (let i = 0; i < obstacles.length; i++) {
    let o = obstacles[i];

    if (o.x + o.w < 0) {
      obstacles.splice(i, 1);
    }

    if (
      player.x < o.x + o.w &&
      player.x + player.w > o.x &&
      player.y < o.y + o.h &&
      player.y + player.h > o.y
    ) {
      obstacles = [];
      score = 0;
      spawnTimer = initialSpawnTimer;
      gameSpeed = 3;
      window.localStorage.setItem('highscore', highscore);
    }

    o.Update();
  }

  player.Animate();

  score++;
  scoreText.t = "Score: " + score;
  scoreText.Draw();

  if (score > highscore) {
    highscore = score;
    highscoreText.t = "Highscore: " + highscore;
  }

  highscoreText.Draw();

  gameSpeed += 0.003;
}

Start();

My utils.js document looks like below:
export function double (n) {
    return n * 2;
}

The errors that return in console:
Error 1:
Access to script at 'file:///C:/Users..../HTML/js_folder/main.js' from
origin 'null' has been blocked by CORS policy: Cross origin requests
are only supported for protocol schemes: http, data, chrome,
 chrome-extension, chrome-untrusted, https.                                                  index.html:1

Error 2:
Failed to load resource: net::ERR_FAILED                                                        main.js:1

If I remove (lines below) from 'main.js', it works..
import {double} from './utils.js';

console.log(double(5));

However, that doesn't pull in my 'utlis.js' file and I don't know the (how, what or why) I cannot load in a js module I have made for my document.
"I've tried...
google searching error
  |-- run cmd command 'chrome.exe --allow-running-insecure-content' with the 'index.html' file
  |-- look at multiple 'stackoverflow.com' & 'superuser.com' search queries of this problem and tried the
  |   solutions
  |-- watched a lot of 'youtube.com' on how to use import/export js files

rewriting the string to locate the folder multiple times"

I am very stumped.. And I don't understand the problem chrome seems to have with this, so please explain on the why of it all and how to correct it. I'd greatly appreciate it, thank you for your time.

A: This ES6 module stuff doesn't work with local html and Javascript files loaded directly from your own machine's file system with the file:// protocol. Read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
You must use a local web server to develop code using this kind of export/import module methodology. Because cybercreeps.
There's a simple web server add on for the Chrome browser here https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en
Or you can use, on Windows, the built in IIS web server. There are plenty of tutorials about setting that up for development.


text:
Q: Spark dataframe : join approach for derived columns Given a dataset as you see in below code (df), my requirement is to be able to add a derived column (DerivedCol). This column's value is constant for a idcol group of rows and is derived by application of a) predicate on another column's value(filter here), and then b) an aggregation function (max used here) over the matching group.
val df = Seq(("id1","k1","7"),("id2","k1","5"),("id1","k3","2"),("id3","k1","4"),("id2","k5","1"),("id4","k5","1"))
  .toDF("idcol","keycol","valcol")

val aggDf = df.filter($"keycol" === "k1")
  .select($"idcol",$"valcol")
  .groupBy($"idcol")
  .agg(max($"valcol".cast(IntegerType)).cast(StringType).as("DerivedCol"))
  .withColumnRenamed("idcol", "newidcol")

df.join(aggDf, df("idcol") === aggDf("newidcol"), "left_outer")
  .drop(aggDf("newidcol"))

I am using a left outer join for this. My dataset is very huge (millions of rows). I have below questions:

*

*Is there any other approach to achieve this?

*What partitioning logic should I use to reduce shuffles?

The cardinality of the idcol column is very high. Spark version is 2.1.1.

A:
Is there any other approach to achieve this?

There is - window functions.
import org.apache.spark.sql.functions.max
import org.apache.spark.sql.expressions.Window

df.withColumn(
   "derivedcol",
   max($"valcol".cast(IntegerType)).over(Window.partitionBy($"idcol")
)

Depending on:

*

*The cardinality - high cardinality is good.

*The distribution of sizes of the groups - small groups without large positive skews are good.

this might behave somewhat better or much worse than aggregation followed by join.

What partitioning logic should I use to reduce shuffles?

Probably none. There are at least two reasons:

*

*If you have large number of small groups window functions will do fine and there is no need for additional partitioning.

*If you have small number of larger groups data should be broadcasted and the only shuffle required is for aggregation.

*If there is a large number of large groups - you might consider pre-partitioning by id, but depending on the number of factors, you can at both loose and gain, and no additional shuffle (partitioning) is on average better.


text:
Q: Download the code of sample application from GoogleApps I have uploaded a sample application to google app engine. Now I would like to download the source code for that sample application which I have uploaded. Is it possible? If yes, how can I do that?

A: You didn't specify if you are using Java or Python, but here's how you download python application:
http://code.google.com/appengine/docs/python/tools/uploadinganapp.html#Downloading_Source_Code
Run this command for your SDK:
appcfg.py download_app -A <application-id> -V <application-version> <output-dir>


text:
Q: Looking for an idiom describing age I'm translating a script for a cartoon into English. In one of the scenes a grandpa's talking to his granddaughter. It goes something like this:
GRANDPA
Indeed! I have forgotten! Apparently, your grandpa's getting a bit long in the tooth. Anyway, would you give your old grandpa a hug?
She turns around slowly. She sees her grandpa with long teeth. She rubs her eyes and the vision's gone.
Seems clear, right? The thing is in my native tongue we don't say "long in the tooth", we say something along the lines of "be like a mushroom" (= be old). And, unfortunately, that's what you see when you're watching the original episode - a grandpa covered in mushrooms (not with long teeth).
As there's no way the producers are ever going to agree to change the original scene and make it work for the English audience, I need to come up with an idiom combining old age and mushrooms (a tree with fungi, possibly?)
Any ideas?

A: Merging Mynamite and StoneyB's observations, if you are stuck with the fungal image, the closest seems like

I'm getting so old and mouldy, I'm sprouting mushrooms!

[Not suggesting actual biological accuracy.]

A: Alas, mushrooms do not have this connotation in English. Quite the opposite: the proverbial cliche is "springing up like mushrooms", referring to the sudden appearance of many mushrooms where none grew before.
We do speak of moss this way—moss-covered implies long inaction—and as Mynamite says mould. Would the drawing accommodate either of these?

A: 'I'm growing some fungus around the edges.'


text:
Q: JFreeChart charts appearance when combined with JasperReports I use JFreeChart in my java application to display charts like this one:

But after creating a report with JasperReports that chart now looks like this:

And that's not all, this is how a chart looks like inside the first PDF report generated with the app:

And this is how it looks when I generate a second report, without changing anything, just generating it again:

This happens again and again, everytime I restart the application. Charts are ok until I create a report. What's happening?

A: It looks like JasperReports is using a more prosaic BarPainter in it's ChartTheme, probably to accommodate destinations that handle gradients poorly.
This forum thread suggests applying the desired theme directly to the chart. The createLegacyTheme() method "returns a ChartTheme that doesn't apply any changes to the JFreeChart defaults. It, or something similar, might be worth a try:
StandardChartTheme.createLegacyTheme().apply(chart)

A: I've moved the edits here as an answer:
The theme problem
Thanks to @trashgod I've tried the following line:
ChartFactory.setChartTheme(StandardChartTheme.createJFreeTheme());

If I use this line before creating charts in my application, reports no longer affect the appearance of them. I think it is enough to put this line just once after report creation.
So now I just have one problem: the first report is different from subsequent reports: charts are different, fonts are bolder and not antialiased...
The Problem of the second report
The pdf issue is not caused by jasper reports nor jfreechart. It is a problem of Adobe Reader. This happens when you have more than one instance of Adobe Reader running (for example, when you have two different files opened).
An example of the problem:

Similar issues:

*

*http://forums.adobe.com/message/4192938

*http://forums.adobe.com/thread/902298


text:
Q: How to retrain/update keras model? How to update/append new data to my model without starting to retrain from scratch?
My dataset are images and the output is to predict emotion.
model.fit(x=train_image, y=train_label, epochs=1, batch_size=1)

Model.fit seems not appending my new data but overwriting the model. My output is only one (the last one that I updated).

Loading a trained Keras model and continue training

I've already search for this but doesn't work as well.
Edit 1:
What can we do when we lose our previously trained data. In simple words we lose our training data just after the training is completed and we can not get the data back again, just the thing we have to retain is the learning done from it and also retrain the model when we receive new data.

A: It is really easy. For instance model.save() in Keras can save the model weights, which is what you actually need to keep.
After that you can add new images to your training set, but just use the weights you saved.
Every new epoch will pass trough all the images (new and old).


text:
Q: C: Recursive function for inverting an int I had this problem on an exam yesterday. I couldn't resolve it so you can imagine the result...
Make a recursive function: int invertint( int num) that will receive an integer and return it but inverted, example: 321 would return as 123
I wrote this:
int invertint( int num ) {
  int rest = num % 10;
  int div = num / 10;
  if( div == 0 ) {
     return( rest );
  }
  return( rest * 10 + invert( div ) )
}

Worked for 2 digits numbers but not for 3 digits or more. Since 321 would return 1 * 10 + 23 in the last stage.
Thanks a lot!
PS: Is there a way to understand these kind of recursion problems in a faster manner or it's up to imagination of one self?

A: int invertint( int num ) {
  int i ;

  for(i=10;num/i;i*=10);
  i/=10;
  if(i == 1) return num;
  return( (num % 10) * i + invertint( num / 10 ) );
}

A: Your mistake is that in the last statement you are multiplying rest by 10. Why only 10? You need to shift the rest digit by as many digits as there are left in the remaining part of the number. You are shifting by only 1. No wonder it works only for 2-digit numbers.
The last part should be done along the lines of
int tail = invert( div );
int deg = /* number of digits in `tail` */;
return rest * (int) pow(10, deg) + div;

A: int reverse(int no,int rev)
{
if(no!=0)
return reverse(no/10,rev*10+no%10);
else
return rev;
}

call this method as reverse(numberToReverse,0)

A: Just as an alternative, this could be done without recursion.
    int invertint(int num)
    {
        int res = 0;
        while (num != 0)
        {
            res = res * 10 + (num % 10);
            num /= 10;
        }
        return res;
    }

But since recursion was the assignment, given the int(int) signature, easiest would be with a pow(log10)) variation (provided that you're allowed to include math.h ? )
    int invertint(int num)
    {
        if (num == 0) return 0;
        return invertint(num / 10)  +  (int)pow(10, (int)log10(num)) * (num % 10);
    }

A: If you do it the other way, you won't need a counter.
int invertint(int num)
{
    if (0 == num || 0 == num % 10) {
        return num / 10;
    }
    int digits = floor(log10(num)) + 1;
    int modulus = pow(10, digits - 1);
    return invertint(num % modulus) * 10 + num / modulus;
}

Note that this isn't as simple as I originally thought - I had to use math.

A: The problem is with return(rest * 10 + invert(div)). You can't do the multiplication yourself. The factor depends on the number of times the function is recursed, thus you have to provide the carry as a second argument to your function (carry is initialized with 0)

A: This is the simplest approach.
int sum=0;
int reverse(int n)
{
    if(n>0)
    {
        sum=(sum*10)+(n%10);
        reverse(n/10);
    }
    return sum;
}


text:
Q: Moment js getting time ago I'm using moment to get time ago, but for things that happened 1 hour ago, it puts it like this: 'am hour ago', is it possible to get '1 hour ago'? Same thing for months, 'a  month ago' => '1 month ago'

A: You can configure moment to display relative times in any format you desire. For example:
moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s  : 'a few seconds',
        ss : '%d seconds',
        m:  "a minute",
        mm: "%d minutes",
        h:  "1 hour ago", //this is the setting that you need to change
        hh: "%d hours",
        d:  "a day",
        dd: "%d days",
        w:  "a week",
        ww: "%d weeks",
        M:  "1 month ago", //change this for month
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
});

After this change has been made the moment library can be used as usual.
Following are some examples:
moment('2021-07-23 14:00:00').fromNow();

If you have the date coming in a different format than expected then you also need to provide the format in which you are getting it. Not doing so will return 'Invalid date'.
moment('21/07/2021',"DD/MM/YYYY").fromNow();

You can also specify multiple formats:
moment('21-07-2021', ['DD/MM/YYYY', 'YYYY/MM/DD']).fromNow();

You can always check whether you got a valid date or not. This helps put some checks in place or can be helpful when debugging code:
moment('abc', ['MM/DD/YYYY', 'YYYY/MM/DD']).isValid() //false

For more information see the docs here: https://momentjs.com/docs/#/customization/relative-time/


text:
Q: Add row to HTML  at Run-time in ASP.Net I have an HTML <Select> with runat="server" in asp.net.
I want to add row to the <Select> On click event of a button or some thing like that, my option is like:
 <select id="lanHtml" runat="server"> </select>

I tried
lanHtml.InnerHtml = "<option value='en'>english</option>";

but it does not work and I get this exception:

'HtmlSelect' does not support the InnerHtml property.

How can I achieve this?

A: Try this:
var o = lanHtml as System.Web.UI.HtmlControls.HtmlSelect;

if(o!=null)
{
    o.Items.Add(new ListItem("English", "En"));
}

A: you can use
lanHtml.Items.Add(new ListItem("English", "En"));
lanHtml.Items.Add(new ListItem("French", "Fr"));


text:
Q: Fazer redirect 301 em urls especificas Como faço em htacess redirect 301 ?
Mas em urls especificas, eu troquei meu dominio, e migrei os posts por exemplo:
meusite.com.br/artigo/nomedoartigo
meusite2.com.br/artigo/nomedoartigo
Fazer um redirect 301 só quando tiver /artigo/
Ai quando pessoal que acessar o url antigo para ver um artigo por exemplo, vai direto pro meusite2.com.br
é possivel?

A: RewriteEngine on

#Somente se for o host antigo...
RewriteCond %{HTTP_HOST}    ^meusite\.com\.br$ [NC]
#... redirecionar só quando tiver artigo/
RewriteRule ^artigo(/.*|$)  http://meusite2.com.br/artigo$1 [R=301,L,NC]

Explicação:

*

*RewriteCond define uma condição para executar a próxima RewriteRule se corresponde. Neste caso, se o host antigo meusite.com.br.

*

*NC faz que ignore caixa alta/baixa.

*^artigo(/.*|$) casa:
^ - início da string
artigo - literal
(/.*|$) - um / seguido por qualquer texto, ou o fim da string
o valor que corresponde à (/.*|$) é capturado em $1.

*http://meusite2.com.br/artigo$1 o novo host, com o texto capturado na condição.

*Flags:

*

*R=301 - redirect 301.

*L -  a regra atual deve ser aplicada imediatamente, sem considerar outras regras.

*NC - faz que ignore caixa alta/baixa.


text:
Q: Only getting documents matching specific query I have multiple documents with the same subject_id and am using an aggregate  project and match query to only get those that match a certain criteria. But because there are multiple documents with the same subject_id, I am getting those that have at least that one criteria.
db.subs.aggregate([ { '$group':
               { _id: '$subject_id', test_04: { '$push':'$metrics.test_04' } }},
               { '$match': { test_04: '3- 5 or more' } } ])

I am receiving the following:
{ _id: 'sub1', test_04: [ '3- 5 or more' ] },
{ _id: 'sub2', test_04: [ '3- 5 or more', '3- 5 or more' ] },
{ _id: 'sub7', test_04: [ '2- 3 or 4', '3- 5 or more' ] },
{ _id: 'sub13', test_04: [ '3- 5 or more' ] },
{ _id: 'sub19', test_04: [ '3- 5 or more' ] }

but I only want
{ _id: 'sub1', test_04: [ '3- 5 or more' ] },
{ _id: 'sub13', test_04: [ '3- 5 or more' ] },
{ _id: 'sub19', test_04: [ '3- 5 or more' ] }


text:
Q: Text does not show properly in R plot My R was installed in a conda environment on Ubuntu 20.04.1 VM.

A: I was searching for this problem when i found this thread. I too am using RStudio from Anaconda, on Debian 10.0 (buster).
Try
par(family  = "Arial")

or whichever font name before calling plot(). It worked for me.
Update > I still had problems with ggplot2 plots not displaying labels, like above. I tried the workaround of using showtext() instead of regular text rendering.
install.packages("showtext")

After it was installed,
library(showtext)

to load the library. Then simply call
showtext_auto()

followed by the ggplot(.....) + ... + etc. function and text was rendered alright within the  plot. I did not load specific fonts using font_add(). Maybe because previously 'Arial' was loaded with par()


text:
Q: Why do Futures use pins in Rust? I understood that pin is used to pin data to one memory. When I use the poll() method in Future trait, it is called continuously until it returns Poll::Ready. Is using a pin to ensure that the data is placed in the same memory while poll() is called? In other words, is it used to prevent the compiler from moving code that may have memory movement while poll is called (generating a compile error)?

A: No. The compiler never moves data behind your back. Pin is not a language guarantee, it is a library guarantee.
There are two ways to construct a Pin:

*

*Unsafely.

*If the data is Unpin.

This ensures that unsafe code can rely on the pinning guarantees. The rule of thumb is: Unsafe code can never trust foreign safe code. It can only trust known safe code (such as std, or code inside its crate), or (even) foreign unsafe code. This is because if unsafe code rely on guarantees of foreign safe code, it can cause UB from safe code. An example (brought in the linked nomicon) is BTreeMap and Ord. BTreeMap requires item to have total ordering, but its unsafe code cannot rely on that and have to behave well even in the presence of non-total ordering. This is because Ord is safe to implement, and so one can implement it with safe code that does not obey to the total ordering rules, and together with BTreeMap cause undefined behavior using safe code only. If the type was known, not foreign (such as i32 that we know that implements Ord correctly), or BTreeMap would require a unsafe trait UnsafeOrd instead of Ord we could rely on that, because violating the contract of UnsafeOrd is undefined behavior as the trait as unsafe to implement.
Suppose we are a self-referential future. We must be sure we stay in the same place in memory, because otherwise our self-references will be dangling. Because dangling references are UB, this has to include unsafe code. We can make poll() unsafe fn, but that is incovenient - it means polling a future is unsafe. Instead, we require Pin<&mut Self>.
Now remember there are two ways to construct a Pin. If we are Unpin, that means we are not self-referential - that is, can be moved safely - and thus we can construct the Pin safely. On the other hand, if we are self referential we should not be Unpin. Now, the only way to construct the Pin is with the unsafe method new_unchecked(), which its safety preconditions require the pinned data will never be moved. Because this method is unsafe, unsafe code is required to use it, and so we can rely on its guarantees (remember we can trust foreign unsafe code).
It doesn't mean new_unchecked() is the only way to construct a Pin<NonUnpin>. A common pattern in Rust is to have an underlying unsafe mechanism that allows everything (as long as it is sound) but validates nothing, and then build various safe abstractions on top of it by restricting some abilities. A common example is interior mutability: we have UnsafeCell that is unsafe and allows everything as long as you obey the aliasing rules, and we have multiple safe abstractions on top of it, each guaranteeing safety by some restriction:

*

*Cell for Copy types and being non thread safe, and the atomic types that guarantees safety by being restricted to a specific set of types and atomic operations.

*RefCell that guarantees safety by runtime check, being as flexible as UnsafeCell but with a runtime cost.

*Mutex and RwLock that guarantee safety by blocking.

*OnceCell and LazyCell that guarantee safety by being writable only once (and possibly blocking, for the thread safe versions).

The same pattern is used with Pin: we have Pin::new_unchecked() that is unsafe, but multiple abstractions such as Box::pin() (requires boxing) or the pin!() macro (or stable versions in crates) that guarantees safety by only allow local pinning.

A: The Rust std library authors pinned the future mutable reference in Futures::poll because of the soundness guarantee they want to provide on their own libraries and to those libraries closely tied to their libraries. They want the definition of poll to help in their soundness guarantee. Memory will not be corrupted unless unsafe is used incorrectly somewhere along the line.
When a future is self referential because it wants to set a self reference to later be used by a subsequent poll, this works because the async runtimes built so far understand they may not move a future once it has been polled at least once.
But if the address of the future wasn't enforced at compile time to be pinned, a naive user might create a library's future and then repeatedly call the future's poll method themself. And if their code had moved the future in between calls to poll, they would have created the chance for the poll method to dereference an address that was no longer part of the future; they would be getting undefined behavior without every calling unsafe themself.
The fact the future address has to be pinned to call the poll method means the caller has to use unsafe. Pinning an address, by definition, involves using unsafe - that's why the idea of pinning exists.
So a user, naive or not, won't get their code to compile when they write something that calls poll unless they have used unsafe themselves. They may have used unsafe incorrectly so there could still be a compromised memory address within the poll logic, but the soundness guarantee would not have been violated - memory unsoundness was created through the misuse of unsafe, not by the misuse of a safe function or method.


text:
Q: Control frame rate of video player in Vision System toolbox? How can I control the playback rate of a video player in the Vision System toolbox in Matlab? Specifically, I want to slow video down. For instance, here is the simple example of how to load and display a movie from the documentation:
videoFReader = vision.VideoFileReader('viplanedeparture.mp4');
videoPlayer = vision.VideoPlayer;
while ~isDone(videoFReader)
  videoFrame = step(videoFReader);
  step(videoPlayer, videoFrame);
end
release(videoPlayer);
release(videoFReader);

I searched the User's Guide for how to change the frame rate in a simple way in such examples, but found nothing.

A: You're displaying images as fast as they can be retrieved and displayed with your current code. If you want a particular framerate I would use a timer that calls your update methods based upon the frame rate that you want. Here is a brief example that should be pretty robust.
videoFReader = vision.VideoFileReader('viplanedeparture.mp4');
videoPlayer = vision.VideoPlayer;

framerate = 10; % in frames/second

t = timer('ExecutionMode', 'fixedRate', ...
          'Period', 1 / framerate, ...
          'TimerFcn', @(tmr,evnt)timerfcn(tmr, videoFReader, videoPlayer), ...
          'ErrorFcn', @(tmr,evnt)cleanup(tmr, videoFReader, videoPlayer));

show(videoPlayer);
start(t)

function timerfcn(tmr, reader, player)
    % While we have more to read, read and display it.
    if ~isDone(reader) && isOpen(player)
        step(player, step(reader));
    else
        cleanup(tmr, reader, player)
    end
end

function cleanup(tmr, reader, player)
    % Callback to ensure proper cleanup of objects
    if isvalid(tmr) && strcmpi(tmr.Running, 'on')
        stop(tmr);
        delete(tmr)
    end

    release(player);
    release(reader);
end

Thanks to horchler's comments for improving the robustness of the solution.
The alternative is to place a pause(1/framerate) statement at the bottom of your while loop, but that won't take into account any time required to actually do the loading/displaying so the frame rate isn't going to be guaranteed to be very consistent.
Additional Thoughts
The comments made below by @neuronet got me thinking about why this may not be a feature of either VideoFileReader or VideoPlayer.
VideoFileReader
As @neuronet states, if the frame rate is specified within the video file that is being read using VideoFileReader, couldn't that be used automatically?
The answer is, yes if could be used but there is good reason to not use it. Since new frames are fetched with VideoFileReader.step() it woud have to be implemented as some sort of a rate limiter on step().
In this particular case, the video is being used for display purposes; however, that is not always the case. A lot of times, you may want to load a video frame by frame to do some analysis (tracking an object, etc.). Now imagine for a second that the frame rate of my video file is set to 1 frame per second (fps). And let's say that I want to load this video into MATLAB, track people in the frame, and report back to the user how many people passed through the field of view during the course of the video.
If VideoFileReader.step() was written so that it returned images only at the frame rate specified in the file, this means that the fastest I could do my processing would be at one frame per second. If this were the case, the end user would just watch the video themselves and we would be out of a job!
Another important consideration is that if you actually want to process the video frame before displaying it to the VideoPlayer object, you need to somehow account for that processing time (which obviously the VideoFileReader has no clue about).
VideoPlayer
The other option would be to have a FrameRate property for the VideoPlayer object itself.
While this too could be done, the way that it is currently implemented it is not possible. Currently to display a new frame, you have to explicitly call the VideoPlayer.step() method. It runs into the same situation as the VideoFileReader. It would have to be implemented as a rate limiter on the step() method.
One possible way that The Mathworks could make this work would be to have an alternative to using step() to update the image. For example, a NextImageFcn callback or something. Then VideoPlayer could internally setup a timer based on a specified frame rate and execute the callback when necessary (similar to our timer callback).
The other alternative could be to have VideoPlayer accept a VideoFileReader object as an input. It could then use this object to get information about the video (frame rate, etc.) and display the images at the appropriate speed.
The main issue here though, is that this serves a very small group of users. This is because the primary goal of MATLAB (and the computer vision toolbox) isn't to be a video playback system, but rather it is intended to do analysis on videos and the VideoPlayer object is intended to streamline the display of the results.
Maybe this functionality will be implemented in the future, but for now those are my thoughts on why it doesn't exist.


text:
Q: Fix all overlap errors without changing number of features This set of features are owned lands that have been individually added as features, naturally they aren't perfectly placed
I have fixed every big overlap and now only small lines overlaps are left, but 4074 of them! Here's an example :

I know there are similar questions here, I don't know if I did them wrong but they didn't work, I need the polygons to remain closed, individuals and the number of features can't change and changing the cluster tolerance affects everything else.
I want to merge for all topology errors, choosing either to receive the merged area, maybe a python code to iterate the topology errors?

A: Yes, use the integrate tool but make a backup copy of your data since this tool will alter the geometry.  For example, if you have a polygon smaller than the tolerance the polygon will collapse.


text:
Q: Matplotlib Scatter plot filter color (Colorbar) I have some data let say x, y, and z. All are 1D arrays. I have done a scatter plot with z as color as;
 import matplotlib.pyplot as plt
 plt.scatter(x,y,c=z,alpha = 0.2)
 plt.xlabel("X")
 plt.ylabel("Y")
 plt.ylim((1.2,1.5))
 plt.colorbar()

The z values are normalized and its between -1 to 1. I have attached the figure below.
The question I have is; How can I filter the colors such that let say the points that have a color value between -0.25 to 0.25 disappear form the figure (i.e set the color to white).

The values for x, y, and z can be provided if needed to answer this question. Thank you for your time.

A: import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)

# prepare random data
stats = -1, 1, 200
x = np.random.uniform(*stats)
y = np.random.uniform(*stats)
z = np.random.uniform(*stats)

# mask unwanted data
thresh = 0.4
mask = np.abs(z) <= thresh
x_ma = np.ma.masked_where(mask, x)
y_ma = np.ma.masked_where(mask, y)
z_ma = np.ma.masked_where(mask, z)

And do the plotting:
fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(10, 4),
                                        sharex=True, sharey=True)
img_left = ax_left.scatter(x, y, c=z)
fig.colorbar(img_left, ax=ax_left)
img_right = ax_right.scatter(x_ma, y_ma, c=z_ma)
fig.colorbar(img_right, ax=ax_right)

gives following result:

The plot on the right side hides all points that fall below the chosen threshold.


text:
Q: Powershell Cut Character Position String Hi how do i replicate this BASH script into powershell? It is taking a basic string and grabbing these certain chunks and putting a pipe inbetween and writing it out to the csv file. I know how to do the get-content and the output to the csv but what is the best way to chop up a string in powershell?
`cat /app/$filename |cut  -c1-9,19-138,139-198,199-238,239-240,241-245,287-296 --output-delimiter="|" >> /app/CSVs/$filename.csv`

I've used split() before but it doesn't seem like the correct way to do it. I'm thinking along the lines of looping through each line and saving each piece of that line and saving to a new string var and adding the delimiter for each section. This seems awfully inefficient.
Thoughts?
The source file is structured by character position with lots of spaces. each field has a set amount of character spaces. (It's basically a database file but in really simple txt format)
1-9 = ID (9 chars long)
19-138 = business_name (120 chars long)
139-198 = address (60 chars long)
198-237 = city (40 chars long)
238-239 = state (2 chars long)
240-244 = zip_code (5 chars long)
286-295 = phone (10 chars long)

I think using $string.substring(char#,length) will work with looping but the more help the better.
The output should look like
123456789|acme business <lots of spaces>|1234 main st <lots of spaces>|etc...

A: Looks like a job for the new PS 5 cmdlet ConvertFrom-String:

*

*ConvertFrom-String: Example-based text parsing

*PowerShell - Playing with the new ConvertFrom-String cmdlet

*PowerShell - ConvertFrom-String and the TemplateFile parameter
Unfortunately, I haven't tried it yet, so I can't provide an example. But it also can be done using regex:
Get-Content -Path '.\db.txt' |
    ForEach-Object{$_ -replace '^(.{9})(.{120})(.{60})(.{40})(.{2})(.{5})(.{10})$', '$1|$2|$3|$4|$5|$6|$7'} |
        Set-Content -Path '.\db.csv'

Get-Content \ Set-Content are quite slow, so to speed up processing you could switch to StreamReader\StreamWriter. See my answer for this question: More-efficient way to modify a CSV file's content, where I use them in the script to speed up things.

A: $subChar =0,18,138,198,238,240,286
$subLength =9,120,60,40,2,5,10

$file = Get-content 'C:\Users\jwannemacher\Desktop\out.txt'
Foreach($line in $file)
{
    $lineCounter
    $array = @()
    $lineLoop = 0
    $charLoop = 0

    foreach($sub in $subChar)
    {
        $word = $line.Substring($subChar[$charLoop],$subLength[$charLoop])
        $array += $word
        $charLoop++
    }
$array -join '|' | Out-File C:\file1.csv -Append


text:
Q: About Java object sort I experience some issues about sorting price in Java.
I want from high price to low price  and from low to high price respectively in my ArrayList.
ArrayList<orderbook> buyerlist=new ArrayList<orderbook>();

I want buyerlist to sort object sequence by price. I tried below but it does not works.
buyerlist.add(new orderbook(orderrecord.get(i).getSide(),orderrecord.get(i).getVolume(),orderrecord.get(i).getPrice()));
Collections.sort(arraylist);

ArrayList<orderbook> sellerlist=new ArrayList<orderbook>();

I want sellerlist can sort object sequence by price
here is my constructor
public class orderbook {

// here i defined three object of this constructor.
// i want sorting this sequence by price. from high to low and low to high respectively.

    String side;
    int volume;
    double price;

    public orderbook(String side,int volume,double price){
        this.side=side;
        this.volume=volume;
        // compare price is low then 0 will throw exception
        if (volume < 0) {
            throw new IllegalArgumentException("volume size illegal");
        }
        this.price=price;

        if (price < 0) {
            throw new IllegalArgumentException("price > 0 require");
        }
    }

    public String getSide() {
        return side;
    }
    public void setSide(String side) {
        this.side = side;
    }
    public int getVolume() {
        return volume;
    }
    public void setVolume(int volume) {
        this.volume = volume;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }

}

A: If you have orderbooks in some Collection for example ArrayList, then you can sort them tis way:
Collections.sort(orderBooks, new Comparator<orderbook> {
    @Override
    public int compare(orderbook ob1, orderbook ob2) {
        return o1.getPrice() - o2.getPrice();
    }
});


text:
Q: A script runs via localhost but not via 127.0.0.1 I am trying to migrate some software from apache 2.2 to 2.4. I have it working - almost. When accessing the server via address localhost things work, but when trying to access via 127.0.0.1 some things don't.
For example, http://localhost/cgi-bin/WI_facility shows me the correct page, but http://127.0.0.1/cgi-bin/WI_facility  asks me do I want to save the file WI_facility which is BIN file (164KB).
This happens on Ubuntu 16.04. On 17.04 and 17.10, both localhost and 127.0.0.1 work normally.
Key part of the apache2.conf is below:
<VirtualHost *:80>
    DocumentRoot /var/www/html
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/html>
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>

    ScriptAlias /cgi-bin/ /var/www/cgi-bin/
    <Directory /var/www/cgi-bin>
        AllowOverride All
        Options +ExecCGI
        SetHandler cgi-script
        Require local
    </Directory>
</VirtualHost>


text:
Q: How to capture image and send its Uri directly to attachment via Email I have Ui in which I have to capture an image and onActivityResult I have to send it to directly to email, for that I have tried every possible solution on stack but failed every time and its give me couldn't attach error, after a long time of searching and implementing I have found something to check a , If I can read the file or not like this file.canRead() it always gives me false. Any solution would be appreciated.
private fun sendEmail(liscence: String, desc: String) {`

val emailIntent = Intent(Intent.ACTION_SEND)`

        val to = arrayOf("info@gmail.com")`

        emailIntent.putExtra(Intent.EXTRA_EMAIL, to)`

        emailIntent.type = "text/plain";
        emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        // attachment Uri comes through camera
        emailIntent.putExtra(Intent.EXTRA_STREAM, imagePath)
        // the mail subject
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report")
        //email body
        val body = "${liscence} \n ${desc}"
        emailIntent.putExtra(Intent.EXTRA_TEXT, body)
        //need this to prompts email client only
        emailIntent.type = "message/rfc822";
        startActivity(Intent.createChooser(emailIntent, "Send email using..."))
    }

A: Did you add READ_EXTERNAL_STORAGE permission to your app and ask this permission from the user in android SDK greater than 23?
Also, if you save your attachment as private, it's not readable for mail. This link explains this more.

A: Here After a lot of research, I have found the solution in the Android documentation
https://developer.android.com/reference/android/support/v4/content/FileProvider.html#GetUri
Here is my final code for sharing a captured image to Gmail.
this code will go straight to Manifest file you have to use authorities as a valid authority provider.
 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.com.mydomain.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/picker_provider_paths" />
    </provider>

XML file for the provider:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="image_picked" path="picked/"/>
<external-path name="*" path="Pictures/"/>
</paths>

Function to SendImage as an attachment.
    private fun sendEmail() {
    val contentUri =
    FileProvider.getUriForFile(context!!,
            "yourPackageAndThen.com.mydomain.fileprovider",
    File(PATH OF IMAGE or FILE ));

    val emailIntent = Intent(Intent.ACTION_SEND)

    //need this to prompts email client only
    emailIntent.type = "message/rfc822";
    val to = arrayOf("EMAIL ID TO SEND")
    emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

    // attachment Uri comes through camera
    emailIntent.putExtra(Intent.EXTRA_STREAM, contentUri)

    // the mail subject
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report")
    //email body
    emailIntent.putExtra(Intent.EXTRA_TEXT, MESSAGEforBody)
    startActivity(Intent.createChooser(emailIntent, "Send email using..."))

}


text:
Q: Remote view html files in Kendo UI Mobile I have created an sample hybrid app using telerik app builder CLI. The project loads an initial home screen from a COMPONENTS folder in the project. Now i have Home folder with an index.js and view.html in it and the Home folder is inside Components. I added About folder with an index.js and view.html in it.
Both view.html have a div inside it. Now i need to know how to navigate from home to about. This has to happen from the JS. I tried
      var app = new kendo.mobile.Application();
      app.navigate("#AboutView");

"#AboutView" is the id of the div in view.html in About folder. This doesn't work. Could someone provide any help

A: with remote views ... you will need to provide the full path. and the reference is always from the root of the project. so in your case it will be
components/About/view.html
http://docs.telerik.com/kendo-ui/mobile/application#remote-views


text:
Q: Codeigniter File Upload with authentication In my Codeigniter app, I have an authentication method to check, if the user is logged in. It is based on session cookies (the standard CI way) and it works perfectly fine.
This method is called from the constructor of each and every controller.
If the user is not logged in, the authentication method redirects to login page.
In the app, there's an option to upload files as well and the uploading part works fine too.
The files get stored into one particular directory in the server. However, if someone has the uri/url of the uploaded file(s), he or she is able to access that, even without logging in the application. Since it is just a url and doesn't come from any controller, anybody will be able to access that even if the person is not logged in.
Any thoughts on how to prevent this.
Thanks

A: Try creating a .htaccess file in that folder, with the following line:
Deny from all

If you need to download the file, create a controller and use the download helper (force_download function). This will disable all kinds of access (so you cannot use this files in the website, if they are images you cannot use them with ).


text:
Q: `flash.discard` in Rails 2.3 fails because flash is a Hash, not a FlashHash Given a functional test such as:
def test_exciting_rails_upgrades
    login(m=users(:manager))

    post :import_users_map_fields, :csv_file => fixture_file_upload('/users.csv', 'text/csv')
    assert flash.empty?
    flash.discard
    # other goodies omitted

end

In Rails 2.3.2 there are no errors, however in 2.3.15 the error is:

    NoMethodError: undefined method `discard' for {}:Hash
    /test/functional/broken_upgrades.rb:119:in `test_exciting_rails_upgrades'

Why is flash a Hash class instead of a FlashHash?
From the source it looks like both 2.3.2 and 2.3.15 ActionPack files  lib/action_controller/flash.rb create the FlashHash class and inherit from Hash.  However what is shown in this functional test in both 2.3.2 and 2.3.15 is a Hash class, not a HashFlash, so one cannot call discard on it.
Can anyone else reproduce this error with 2.3.15 and flash.discard?

A: Here are two test cases you can use to prove ActionController changes the type of 'flash' depending on whether or not it is already set.
In my app, you cannot see :index unless you're logged in, so in test_flash_is_now_a_flashhash you see that flash was set by the backend properly, while in test_flash_is_a_plain_hash it was not.
def test_flash_is_a_plain_hash
  login(users(:permitted_user))
  get :index
  assert flash.instance_of?(Hash)
end

def test_flash_is_now_a_flashhash
  get :index
  assert_redirected_to :controller => "login"
  assert flash.instance_of?(ActionController::Flash::FlashHash)
end

You can see this for yourself in the ActionController::TestRequest code:
def flash
    session['flash'] || {}
end

Update: This has been fixed in Rails branch 2-3-stable.


text:
Q: Is there a standard data structure for a "database"-like object? I'm designing an upgrade to an older C++ assembly and want to (re-)do this right.
The situation is, I've got an object that is basically a "database" (it's various bits of data taken over lots of time-steps).  The issue is I don't know what each "column" will hold until run-time.
There are about 30 column name possibilities.  Speed is a major concern.
The old structure uses an array to store the column names (they're enums), and an array of arrays to hold the data.  You'd find the column name in the header array, then use that column index to find the right bit of data in the current data "row".  It's a perfectly viable idea, but it seems a bit...out of date.
I'd include each possible column as a property in a "row" object, it seems this would massively inflate the memory usage and creation time (which isn't acceptable).
Is there a standard structure for this kind of thing?

A: Yes, take a look at the DataSet class in the System.Data namespace.
The DataSet is the top-level container for DataTables, Relations and other "database-like" objects. In the DataTables you can define your columns and populate your rows as you wish. You can also easily  persist the whole thing via serialization.


text:
Q: Invalid Column Name - All Columns in Table All of my references to a column existing in table departments are getting binding errors. (they are highlighted) However, all of my saved queries referencing this table, though the column references are highlighted, still execute properly. NEW queries do not.
select
    i.itemnum, i.itemname
from
    inventory i
join
    departments d on i.dept_id = d.DEPT_ID
join
    categories c on d.SUBTYPE = c.cat_id

where c.description = 'vapors'

In the above query,  both d.DEPT_ID and d.SUBTYPE are highlighted as invalid column name, though they are both most definitely fields that are available in departments and will still return results.
Even in the following query I still get a highlight on DEPT_ID in the code body
select DEPT_ID from departments

Queries that reference departments still execute, although they still show the red highlight on all references to departments in the code body
I'm wondering if I might have inadvertently changed a setting on departments, although I truly don't know how I would have done so...

A: Clear your Intellisense cache. The errors/highlights are phantom. If your code works, ignore the errors or clear the cache.
"CTRL + SHIFT + R"

A: If your query is running properly and giving the expected results and only your are worry about column not highlighting then you can close and re open the SSMS and check.
If you create any new tables and do not close the SSMS then some time that new tables and columns do not give refreshed.


text:
Q: python if statement always So, I'm building up a simple game in Python to get more acquainted with the language, and couldn't find a way of searching if this was asked before. :P  Any-way, when this code block executes, I always end up with my "Position" being .y +10.  I've rearanged and checked a couple things, but feel I'm missing a quite basic part of what I would normally handle with a switch statement
mv = input('N,S,E,W?')

if mv == 'N' or 'n':
    Me.Position.Y += 10
elif mv == 'E' or 'e':
    Me.Position.X += 10
elif mv == 'W' or 'w':
    Me.Position.X -= 10
elif mv == 'S' or 's':
    Me.Position.Y -= 10
else:
    print('Stand')

and then:
print('Lage: X:', Me.Position.X, ' Y:', Me.Position.Y, ' Z:', Me.Position.Z)

with no way of my other options being used.
THANKS!

A: The problem is the or in your if-statement:
even if mv == 'N' evaluates to False, the non-empty string 'n' evaluates to True, such that mv == 'N' or 'n' is always True.
What you want is:
if mv in ['n', 'N']:
    Me.Position.Y += 10

or even just:
if mv in 'nN':
    Me.Position.Y += 10

A: A better approach would be to check if your answer is in a tuple of possible answers, i.e.,
In [1]: mv in ('n', 'N')
Out[1]: True

tuple is preferred since it's immutable.
However, if you want to stick with your original code, you want to use
 if mv == 'N' or mv == 'n':

because given
 mv ='n'

then
In [2]: mv == 'n'
Out[2]: True

In [3]: mv == 'N'
Out[3]: False

In [4]: mv == 'N' or 'n'
Out[4]: 'n'

but
In [5]: mv == 'n' or mv == 'N'
Out[5]: True

which is what I believe your original intent was.

A: Your code is being interpreted a little differently than what you expect. This line:
if mv == 'N' or 'n':

Is being interpreted as:
if (mv == 'N') or ('n'):

'n' is truthy, so your if statement will always be True. You have to be more explicit:
if mv == 'N' or mv == 'n':

Or use in:
if mv in ['N', 'n']:

Or use .lower():
if mv.lower() == 'n':


text:
Q: DPD Api Label format We are building a program to place shipping directly from our system to the DPD api. Everything works fine and we are getting the label in response.
I don't know what format it is. The documentation of the API is very poor. Does anybody has an idea what it could bee? It doesn't look like ZPL:
N

Q822,24
R40,0
S4
D15
ZB
A760,120,1,1,1,1,N,"DPD Local"
A735,080,1,1,1,1,N,"www.dpdlocal.co.uk"
A706,033,1,1,1,1,N,"Sender"
A690,033,1,1,1,1,N,""
A674,033,1,1,1,1,N,"2 SABRE WAY"
A658,033,1,1,1,1,N,""
A642,033,1,1,1,1,N,"PETERBOROUGH"
A626,033,1,1,1,1,N,"PETERBOROUGH"
A610,033,1,1,1,1,N,"PE1 5EJ"
A606,124,1,1,1,1,N,"Phone:"
A706,158,1,1,1,1,N,"Account:"
A588,033,1,1,1,1,N,"Delivery Address"
A003,035,0,4,1,1,N,""
A003,060,0,4,1,1,N,"3 SABRE WAY"
A003,085,0,4,1,1,N,""
A003,110,0,4,1,1,N,"PETERBOROUGH"
A003,135,0,4,1,1,N,"PETERBOROUGH"
A003,160,0,4,1,1,N,"PE1 5EJ"
A183,160,0,4,1,1,N,"United Kingdom"
A480,150,0,4,2,2,N,""
A003,198,0,1,1,1,N,"Contact"
A003,213,0,1,1,1,N,"Phone"
A003,265,0,1,1,1,N,"Consignment"
A003,283,0,1,1,1,N,"Ref"
A003,228,0,1,1,1,N,"Info"
A120,198,0,1,1,1,N,"SEND CONTACT 1"
A120,213,0,1,1,1,N,""
A120,228,0,1,1,1,N,""
A120,243,0,1,1,1,N,""
A120,265,0,1,1,1,N,""
A120,283,0,1,1,1,N,"MY REF 1"
A120,298,0,1,1,1,N,"MY REF 2"
A120,313,0,1,1,1,N,"MY REF 3"
A463,195,0,1,1,1,N,"Packages"
A453,245,0,1,1,1,N,"Total Weight"
A463,210,0,4,1,1,N,"1 of 1"
A463,260,0,4,1,1,N,"5 kg"
A003,397,0,1,1,1,N,"Track"
A695,390,0,1,1,1,N,"Service"
A003,350,0,4,1,2,N,"1597"
A103,350,0,4,1,1,N,"6885 0239 32T"
A160,525,0,1,1,1,N,"      06/04/21 18:55 Web 4.3.55-api      "
B010,550,0,1,3,6,200,N,"%0PE15EJ15976885023932808826"
A140,780,0,3,1,1,N,"0PE1 5EJ1 5976 8850 2393 2808 8262"
A479,342,0,4,1,2,N,"       BY 1030 PCL"
A190,490,0,4,1,1,N,"   808-GB - PE1 5EJ   "
A010,420,0,2,2,2,N,""
A008,475,0,4,2,3,N,"LOCAL"
A645,475,0,4,2,3,N,"1631"
A100,390,0,4,3,4,N,"GB-PE1 5EJ"
LO001,330,765,10
LO001,025,765,1
LO001,192,590,1
LO001,330,765,10
LO765,001,1,330
LO001,001,1,330
LO715,025,1,306
LO592,025,1,306
LO001,001,765,1
LO430,192,1,138
P1
N
"""


text:
Q: Data not getting bound in action method I am using pubs database and basically I show a list of authors on one page and there is edit link. On click of edit link, one page gets showed which has author's information and checkboxlist with checkmark besides the titles that the particular author have written.
This is my code till now:
Action methods of HomeController:
public ActionResult Edit(string id)
{
    author author = db.authors.Include("titleauthors").Where(a => a.au_id == id).Single();

    List<TitleViewModel> titleViewModelList = db.titles.Select<title, TitleViewModel>(title =>
        new TitleViewModel { IsChecked = false, Title = title.title1, title_id = title.title_id }).ToList();

    foreach (var item in author.titleauthors)
    {
        TitleViewModel titleViewModel = titleViewModelList.Where(model => model.title_id == item.title_id).SingleOrDefault();
        if (titleViewModel != null)
            titleViewModel.IsChecked = true;
    }

    AuthorViewModel AuthorViewModel = new AuthorViewModel
    {
        Author = author,
        TitleViewModels = titleViewModelList
    };

    return View(AuthorViewModel);
}

[HttpPost]
public ActionResult Edit(AuthorViewModel AuthorViewModel)
{

    return RedirectToAction("Index");
}

Edit.cshtml:
@model MVCCheckboxList.ViewModels.AuthorViewModel
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

    Edit

<fieldset>
    @using (Html.BeginForm())
    {
        <legend>Edit author</legend>

                    @Html.LabelFor(model => model.Author.au_fname)

                    @Html.TextBoxFor(model => model.Author.au_fname)

                    @Html.LabelFor(model => model.Author.au_lname)

                    @Html.TextBoxFor(model => model.Author.au_lname)

                    @Html.LabelFor(model => model.Author.address)

                    @Html.TextBoxFor(model => model.Author.address)

                    Titles

                    @Html.EditorFor(model => model.TitleViewModels, "TitleViewModels")

                        <input type="submit" value="Save" />

    }
</fieldset>

This is my AuthorViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCCheckboxList.ViewModels
{
    public class AuthorViewModel
    {
        public List<TitleViewModel> TitleViewModels { get; set; }
        public author Author { get; set; }
    }
}

and this is my TitleViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCCheckboxList.ViewModels
{
    public class TitleViewModel
    {
        public string title_id { get; set; }
        public bool IsChecked { get; set; }
        public string Title { get; set; }
    }
}

The information gets properly displayed in Edit page. But when I click on submit, the Author property in AuthorViewModel correctly holds all the data but the List<TitleViewModel> in AuthorViewModel is null. Can anybody spot the mistake why is this happening?
This is my EditorTemplate(TitleViewModels.cshtml):
@model IEnumerable<MVCCheckboxList.ViewModels.TitleViewModel>

@foreach (var item in Model) {

            @Html.HiddenFor(modelItem => item.title_id)

            @Html.CheckBoxFor(modelItem => item.IsChecked)

            @Html.DisplayFor(modelItem => item.Title)

}

A: Here you find more informations about list binding.
Just change the name of your EditorTemplate to TitleViewModel.cshtml and paste that code:
@model MVCCheckboxList.ViewModels.TitleViewModel

    @Html.HiddenFor(modelItem => Model.title_id)

    @Html.CheckBoxFor(modelItem => Model.IsChecked)

    @Html.DisplayFor(modelItem => Model.Title)

In Edit.cshtml use below code to generate editor for each element from your list

@for (int i = 0; i < Model.TitleViewModels.Count; i++) {
    @Html.EditorFor(m => Model.TitleViewModels[i])
}


text:
Q: Prove if d | a, then d | ca for any integer c. Correction I am frustrated because this is literally exercise 3 from my textbook and I still can not get it. I already failed my first midterm. I am wondering why I am bad with discrete mathematics, but love calculus?
Anyway, how do I solve this? I have tried looking for the same problem but to no avail.
Please help thanks.

A: Looking at the relevant definitions is always an important first step to take in introductory problems in proof writing.
For nonzero integers $d,a$ the following are equivalent statements:

*

*$d\mid a$

*$d$ divides $a$

*$a$ is divisible by $d$

*$a$ is an integer multiple of $d$

*There exists some integer $k$ such that $a = d\times k$

*$\frac{a}{d}$ is an integer

*$\vdots$
(There are still several more equivalent statements, but those can come later in your studies and don't need to be mentioned now)

Suppose that $d\mid a$.  We wish to show that for any integer $c$ it follows that $d\mid ac$.
Since $d\mid a$, it follows that there is some integer $k$ such that $a = d\times k$.
By multiplying both sides of that equation by $c$ and slight rearranging we have $ac = d\times (kc)$
Now... we ask, is there an integer that we can fill in the blue square with in the following $ac = d\times \color{blue}{\square}$ to make the equality true?  Yes, we can, we can fill it in with $kc$ which is also an integer since our earlier work already showed that $ac = d\times (kc)$.
Since $ac$ is an integer multiple of $d$, by definition then $d\mid ac$

Side note: you would notice that when we talked about how $d\mid a$ that means there is some $k$ such that $a=d\times k$.  If we were to also talk about how $d\mid b$ and rewrite this using another equality, it does not have to be "the same $k$" in the equality... so we would probably want to use a different letter., say for example $\ell$ such that $b = d\times \ell$.  We don't care what the integer looks like or how it is written, all we care about is that it is an integer.

A: It is always worth thinking to yourself "can I write the problem in a different way ?".
In this case $d|a$ means that $a=kd$ for some integer $k$. But if $a=kd$ then $ca = ckd$. And since $c$ and $k$ are both integers, $d$ is clearly a divisor of $ckd$, which is just $ca$ in disguise. So $d|ca$.

A: Um... not just for some $c$ but for all $c$.
$d|a$ means, by definition that $\frac ad = m$, an integer.
So me must prove there is some integer $c$ where $\frac {ca}d = k$, and integer.
Well, if there were then $\frac {ca}d  = c\frac ad = cm$.
So this is asking is there some integer $c$ where $cm$ is an integer?  And the answer is EVERY integer $c$ will have $cm$ being an integer.


text:
Q: Kudan Unity :Destroying GameObject on Touch I am using the Kudan plugin in Unity for building an android app. I am using the markerless mode. When I tap (touch) model, which spawns in this markerless mode, I want to destroy it. I am using a Raycast script as listed below. I tried attaching the script to Kudan Camera. Also I created a public Camera gameobject and passed the Kudan Camera to it. However neither option works.
Does anyone know what I am doing wrong?
public Gamobject model;

if (Input.touchCount > 0)
        RaycastHit hit;

            Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);

        if (Physics.Raycast (ray, out hit))
        {
            if (hit.collider.gameObject.tag == "chair")
            {
                Destroy (model);
            }
        }
    }

Thanks in advance!

A: Assuming that your actual code is correct and says GameObject instead of Gamobject and your if statement has an opening brace, etc, it could be that:

*

*You haven't given your model the "chair" tag. If your ray hits the model, but the model doesn't have the right tag, it will be ignored.

*The Ray isn't going far enough to hit anything (as mentioned in comments). You haven't specified a distance, which in theory should mean that there isn't a maximum distance, but you never know, Unity might have some weird default or something.

*Your model doesn't have a collider. Objects need a collider otherwise the physics engine can't register the "collision" between the ray and the object.

But really, an easier and probably better method would be to not use a Raycast at all. If you make a method in a script:
void OnMouseDown
{
    Destroy(gameObject);
}

and attach that script to your model, then when the user clicks on the model (or taps on mobile), provided it has a collider, it will be destroyed.


text:
Q: Override Ember application.hbs template I have an Ember JS application with 99% of it's resources on the root level, which the user has to be logged in to access. All those resources, with the exception of /login, have the same template.
/login, however, has an entirely different template (no nav bar, etc). What's the best way to override the application.hbs template for the login page?
Most of the answers I see in other questions involve a sort of parent route for the authenticated routes, like so:
this.route('login');
this.route('main', { path: '/' }, function() {
  this.route('posts');
});

That solution yields the right URL's, but it means link-to helpers and such have to use 'main.posts', etc routes, which rubs me the wrong way, and I'd like not to have that extraneous route level all over the place.
In Rails, I'd just say something like layout: nil, and and that would prevent the main template from being applied. Is there any equivalent in Ember, or another way to achieve the same goal cleanly?

A: To get rid of {{link-to 'main.posts'}}. You can add {resetNamespace:true} to a given route.
this.route('main', {path:'/'}, () => {
    this.route('posts', {resetNamespace:true});
});

{{link-to 'posts'}} will navigate to your posts route

A: I got another solution
    {{!-- application.hbs --}}
    {{#if session.isAuthenticated}}
      {{outlet}}
    {{else}}
      Then the welcome/login page goes here
    {{/if}}

Inspired by samselikoff in this post
======EDIT======
Maybe we can even do this
    //in app/routes/login.js
    export default Ember.Route.extend({
      renderTemplate: function() {
        this.render({ outlet: 'un-auth' });
      }
    });

and
    {{!-- application.hbs --}}
    {{#if session.isAuthenticated}}
      {{outlet}}
    {{else}}
      {{outlet "un-auth"}}
    {{/if}}


text:
Q: Aidl, android and unbinding service Could somone explain to me why after calling unbindService i'm still able to communicate with the service ?
The flow:
bindService(new Intent(IService.class.getName()), conn, Context.BIND_AUTO_CREATE)
...
mService = IService.Stub.asInterface(service);
...
writeToOutput("Droping bombs from: " + mService.getPid());
...
unbindService(mCurConnection);
...
writeToOutput("Droping bombs from: " + mService.getPid()); // no exception - still returns good values
...

A: Perhaps the service is still working on a task.
In the google documentation it states that calling unbindService(Connection) simply allows the service to stop at any time. It does not mention that it is a hard stop or a force stop.
From google doc:
"Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time."
Another possibility is that you may have another activity binding to the service and so long as you have at least one bound interface the service stays active.
If you would like to post more details about what you are doing, I can probably provide a better solution.
Thanks


text:
Q: Generate TLS Certs using fabric-ca-server I am searching for a way to generate TLS certs for nodes using a fabric-ca-server. I am using fabric-ca-client. I have used cryptogen tool to generate the TLS certs to get something like this.

tls
├── ca.crt
├── server.crt
└── server.key

Running the command
fabric-ca-client enroll -u http://admin:adminpw@localhost:7054 -M ./OrgMSP --enrollment.profile
tls

generates directory as shown below

msp
├── admincerts
├── cacerts
├── keystore
├── signcerts
└── tlscacerts

but cannot seem to get the TLS certs. So, is there a way to get these certs using the same fabric-ca service? If so, what options to provide while using the fabric-ca-client.

A: There is no difference bw two you can copy the file inside the cacerts and rename it to ca.crt, file keystore to  server.key and file in side the signcerts to server.crt and create the exact structure like generated by the cryptogen.