How to define and use macro in Mathjax? - require

I often use vector operation, and normally vector is written by Bold font, e.g.
$$ \boldsymbol x = \boldsymbol a \times \boldsymbol b + \boldsymbol c $$
which is somehow too long, so I like to define some new commands \bx, \ba, \bb first,
$$
\newcommand{\bx}{\boldsymbol x}
\newcommand{\ba}{\boldsymbol a}
\newcommand{\bb}{\boldsymbol b}
\newcommand{\bc}{\boldsymbol c}
$$
then above equation can be written shortly as:
$$ \bx = \ba \times \bb + \bc $$
Because I use these Bold fonts so often, I don't want to type them time by time, I plan to define them as macro in a file: boldfont.js , when I need to type vector, I just require boldfont.js.
I write file as follows (save the file as: /config/TeX/boldfont.js, other file (such as color.js) under the same directory):
MathJax.Hub.Config({
TeX: {
Macros: {
ba: '{\\boldsymbol a}',
bb: '{\\boldsymbol b}',
bc: '{\\boldsymbol c}',
bd: '{\\boldsymbol d}',
be: '{\\boldsymbol e}',
bf: '{\\boldsymbol f}',
bg: '{\\boldsymbol g}',
bh: '{\\boldsymbol h}',
bi: '{\\boldsymbol i}',
bj: '{\\boldsymbol j}',
bk: '{\\boldsymbol k}',
bl: '{\\boldsymbol l}',
bm: '{\\boldsymbol m}',
bn: '{\\boldsymbol n}',
bo: '{\\boldsymbol o}',
bp: '{\\boldsymbol p}',
bq: '{\\boldsymbol q}',
br: '{\\boldsymbol r}',
bs: '{\\boldsymbol s}',
bt: '{\\boldsymbol t}',
bu: '{\\boldsymbol u}',
bv: '{\\boldsymbol v}',
bw: '{\\boldsymbol w}',
bx: '{\\boldsymbol x}',
by: '{\\boldsymbol y}',
bz: '{\\boldsymbol z}',
}
}
});
And I try to use the file (using \require command) as
$$
\require{boldfont}
\bf=\bu+\bv-\bw
$$
But it doesn't work, what's wrong? How to define macro and use it?
Help me, please.

The TeX configuration block is read when the TeX input jax is first loaded, so if you call MathJax.Hub.Config() after that, the changes you make will not be seen by the TeX input jax. So any macros you add that way will not have an effect.
Instead you should use
MathJax.InputJax.TeX.Macro('bx', '\\boldsymbol{x}');
MathJax.InputJax.TeX.Macro('ba', '\\boldsymbol{a}');
...
If you have a macro that takes arguments, you can add a third parameter that is the number of arguments needed. E.g.
MathJax.InputJax.TeX.Macro('bs', '\\boldsymbol{#1}', 1);
The file should be stored in the MathJax/extensions/TeX folder (not MathJax/config/TeX), and if you call it boldfont.js, then at the end of the file, you need to add the line
MathJax.Ajax.loadComplete('[MathJax]/extensions/TeX/boldfont.js');
With those changes, I think you should be able to get it to work. If not, check your console log for messages, and also use
MathJax.Message.Log()
to see if there are any file-load failures listed.
(This is my answer from the MathJax User's Forum where this question was cross posted).

Related

Mapping errors from Command::new("/bin/bash") arguments

I am executing a bash command, for which I would like to catch an error when the move argument fails. Since there is one more command after move, my goal is to capture specifically whether the move operation got successfully executed to a status code and to break out of the entire Rust program.
Is there a way to accomplish this? I have provided below the source code.
let path : String = "/home/directory/".to_string();
let command = Command::new("bin/bash")
.arg("-c")
.arg("mv somefile1.txt /home/")
.arg("cp ~/somefile2.txt .")
.stdout(Stdio::piped())
.output();
bash -c doesn't accept two commands like that. You could try splitting it into two separate Commands:
Command::new("bash")
.arg("-c")
.arg("mv somefile1.txt /home/")
.status()?
.success() // bool
.then(|| ()) // convert bool to Option
.ok_or("mv failed")?; // convert Option to Result
Command::new("bash")
.arg("-c")
.arg("cp ~/somefile2.txt .")
.status()?
.success() // bool
.then(|| ()) // convert bool to Option
.ok_or("cp failed")?; // convert Option to Result
Or joining them into a single command with &&:
Command::new("bash")
.arg("-c")
.arg("mv somefile1.txt /home/ && cp ~/somefile2.txt .")
.status()?
.success() # bool
.then(|| ()) # convert bool to Option
.ok_or("failed")?; # convert Option to Result
Better yet, use native Rust functions:
mv → std::fs::rename
cp → std::fs::copy
~ → home::home_dir
This avoids the overhead of calling out to bash and is portable to non-Unix operating systems.
use std::fs;
use dirs::home_dir;
if let Some(home) = home_dir() {
fs::rename("somefile1.txt", home.join("somefile1.txt"))?;
fs::copy(home.join("somefile2.txt"), ".")?;
}

Multi-line wide string constant that allows single line comments in C++

This question of how to break up a (wide) string constant along multiple lines in code has been asked and answered multiple times on this platform (here, for example). I have been using the following approach to declare a static wide string in the class definition itself:
#include <Windows.h>
#include <iostream>
class Test
{
public:
static constexpr WCHAR TEST[] = L"The quick brown fox" \
L"jumped over the" \
L"lazy dog!";
/* ... */
};
int main ()
{
wprintf(Test::TEST);
return 1;
}
However, this approach does not work very well if you want to start commenting each line of your multi-line string. The only way you can achieve this is if you stick a multi-line comment in between the string and the backslash (\) like so:
class Test
{
public:
static constexpr WCHAR TEST[] = L"The quick brown fox" /* A comment */\
L"jumped over the" /* Another comment*/\
L"lazy dog!";
/* ... */
};
If you put a comment after the backslash (\), then a compiler error is raised. This means, you cannot use the traditional single line comment (//) with this method. As a matter of fact, if you put a single space after the backslash (\), then a compiler error is generated.
My question is as follows, is there a way to declare a wide string over multiple lines where you can use single line comments (//) to comment each line?
I am idling looking for something like this (similar to Java):
static constexpr ... = L"The quick brown fox" + // A little comment here...
L"jumped over the" + // A little comment there.
L"lazy dog!";
I understand things are incredibly different in Java (i.e. namely everything is an object), but I am just giving this as an example of what I am after.
Simply drop the backslashes:
static constexpr WCHAR TEST[] = L"The quick brown fox" // a comment
L"jumped over the" // another comment
L"lazy dog!"; // yet another comment
Comments are replaced by space characters in translation phase 3. Adjacent string literals are concatenated in translation phase 6.

Ada language - How to store a string value returned by a function?

I'm attempting to some basic command-line interaction in Ada 2012 and I can't find a way to capture the string returned from the Ada.Command_Line.Command_Name() function.
All the examples I can find online simply print the String using Put() without first storing it in a local variable. Here's the faulty code I've tried, which does compile but throws a CONSTRAINT_ERROR ... length check failed when I try to assign the return String value to the String variable...
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
procedure Command_Line_Test is
ArgC : Natural := 0;
InvocationName : String (1 .. 80);
begin
ArgC := Argument_Count;
Put ("Number of arguments provided: ");
Put (ArgC'Image);
New_Line;
InvocationName := Command_Name; -- CONSTRAINT_ERROR here
Put ("Name that the executable was invoked by: ");
Put (InvocationName);
New_Line;
end Command_Line_Test;
I'm just using Command_Name as an example, but imagine it was any other function that could return a string (perhaps a string that would change multiple times during the program's life), how should we declare the local variable in order to store the returned string?
String handling in Ada is very different from other programming languages and when you declare a String(1..80) it expect that string returned by a function will actually have length 1..80 while your executable path (which is returned by Command_Name) may be a bit shorter (or longer).
You may always introduce new declare block and create a String variable inside of it
like here
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
procedure Main is
ArgC : Natural := 0;
begin
ArgC := Argument_Count;
Put ("Number of arguments provided: ");
Put (ArgC'Image);
New_Line;
declare
InvocationName: String := Command_Name; -- no more CONSTRAINT_ERROR here
begin
Put ("Name that the executable was invoked by: ");
Put (InvocationName);
New_Line;
end;
end Main;
Or you may use Ada.Strings.Unbounded package
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Main is
ArgC : Natural := 0;
InvocationName : Unbounded_String;
begin
ArgC := Argument_Count;
Put ("Number of arguments provided: ");
Put (ArgC'Image);
New_Line;
InvocationName := To_Unbounded_String(Command_Name); -- no more CONSTRAINT_ERROR here
Put ("Name that the executable was invoked by: ");
Put (To_String(InvocationName));
New_Line;
end Main;
Agree with Timur except that there is no need to move the declaration of Invocation_Name into a nested declare block.
You could have just written;
Invocation_Name : String := Command;
Where it was in the original code, in the declarations of procedure Main.
or better yet;
Invocation_Name : constant String := Command;
or better yet, eliminate the declaration altogether and replace the last 3 lines of Main with;
Put_Line ("Name that the executable was invoked by: " & Command);

I need to know how to implement multithreading

I am trying to implement multithread functionality perl script for more speed
I am trying to implement multithread functionality perl script for more speed
I need to know how to implement multithreading for the following perl code
#!/usr/bin/perl
use if $^O eq "MSWin32", Win32::Console::ANSI;
use Getopt::Long;
use HTTP::Request;
use LWP::UserAgent;
use IO::Select;
use HTTP::Headers;
use IO::Socket;
use HTTP::Response;
use Term::ANSIColor;
use HTTP::Request::Common qw(POST);
use HTTP::Request::Common qw(GET);
use URI::URL;
use IO::Socket::INET;
use Data::Dumper;
use LWP::Simple;
use LWP;
use URI;
use JSON qw( decode_json encode_json );
use threads;
my $ua = LWP::UserAgent->new;
$ua = LWP::UserAgent->new(keep_alive => 1);
$ua->agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31");
{
chomp($site);
push(#threads, threads->create (\&ask, \&baidu, $site));
sleep(1) while(scalar threads->list(threads::running) >= 50);
}
eval {
$_->join foreach #threads;
#threads = ();
};
########### ASK ###########
sub ask {
for ( $i = 0; $i < 20; $i += 1) {
my $url = "https://www.ask.com/web?o=0&l=dir&qo=pagination&q=site%3A*.fb.com+-www.fb.com&qsrc=998&page=$i";
my $request = $ua->get($url);
my $response = $request->content;
while( $response =~ m/((https?):\/\/([^"\>]*))/g ) {
my $link = $1;
my $site = URI->new($link)->host;
if ( $site =~ /$s/ ) {
if ( $site !~ /</ ) {
print "ask: $site\n";
}
}
}
}
}
########### Baidu ###########
sub baidu {
for ( my $ii = 10; $ii <= 760; $ii += 10 ) {
my $url = "https://www.baidu.com/s?pn=$ii&wd=site:fb.com&oq=site:fb.com";
my $request = $ua->get($url);
my $response = $request->content;
while ( $response =~ m/(style="text-decoration:none;">([^\/]*))/g ) {
my $site = $1;
$site =~ s/style="text-decoration:none;">//g;
if ( $site =~ /$s/ ) {
print "baidu: $site\n";
}
}
}
}
If run this code I get only Result from Ask.com.
How I can fix this problem and thanks for all ?
C:\Users\USER\Desktop>k.pl -d fb.com
ask: messenger.fb.com
ask: yourbusinessstory.fb.com
ask: research.fb.com
ask: communities.fb.com
ask: shemeansbusiness.fb.com
ask: nonprofits.fb.com
ask: messenger.fb.com
ask: yourbusinessstory.fb.com
ask: research.fb.com
ask: communities.fb.com
ask: shemeansbusiness.fb.com
ask: nonprofits.fb.com
ask: politics.fb.com
ask: communities.fb.com
ask: live.fb.com
ask: messenger.fb.com
ask: yourbusinessstory.fb.com
ask: research.fb.com
ask: communities.fb.com
ask: shemeansbusiness.fb.com
ask: nonprofits.fb.com
ask: politics.fb.com
ask: communities.fb.com
ask: live.fb.com
ask: techprep.fb.com
ask: newsroom.fb.com
ask: rightsmanager.fb.com ask: messenger.fb.com
ask: yourbusinessstory.fb.com
ask: research.fb.com
ask: communities.fb.com
ask: shemeansbusiness.fb.com
ask: nonprofits.fb.com
ask: politics.fb.com
ask: communities.fb.com
ask: live.fb.com
ask: messenger.fb.com
ask: yourbusinessstory.fb.com
ask: research.fb.com
ask: communities.fb.com
ask: shemeansbusiness.fb.com
ask: nonprofits.fb.com
ask: politics.fb.com
ask: communities.fb.com
ask: live.fb.com
ask: techprep.fb.com
ask: newsroom.fb.com
ask: rightsmanager.fb.com
ask: politics.fb.com
ask: communities.fb.com
ask: live.fb.com
ask: messenger.fb.com
ask: yourbusinessstory.fb.com
ask: research.fb.com
ask: communities.fb.com
ask: shemeansbusiness.fb.com
ask: nonprofits.fb.com
ask: politics.fb.com
ask: communities.fb.com
ask: live.fb.com
ask: techprep.fb.com
ask: newsroom.fb.com
ask: rightsmanager.fb.com
OK, so first off - there's some really quite icky looking things you're doing here, and I'd suggest you need to step back and review your code. It's looking a bit 'cargo-cult' thanks to things like:
use HTTP::Request::Common qw(POST);
use HTTP::Request::Common qw(GET);
Or:
my $ua = LWP::UserAgent->new;
$ua = LWP::UserAgent->new(keep_alive => 1);
... you're creating a new LWP::UserAgent instance, and then ... creating another one with a different parameter.
You've also got a load of errors that you're not seeing because you didn't include the most important use items:
use strict;
use warnings qw ( all );
Turn these on first, and then fix the errors.
But here for example:
push(#threads, threads->create (\&ask, \&baidu, $site));
What do you think this line is supposed to do? Because what's actually happening here is you try and invoke the ask sub, and then pass it arguments of a code reference to baidu sub, and a string $site - which is undefined at this point in the code. But that's academic, because you NEVER READ THEM in your subroutine.
So it's not really a surprise your code isn't really working - it's nonsense.
But that aside - perls threading model is often misunderstood. It is not a lightweight thread like you might be thinking of in other programming languages - actually it's rather heavyweight.
You're creating and spawning a thread per iteration, and that's not very efficient either.
What you really want to be doing is using Thread::Queue.
Spawn a small number of 'worker' threads per task, have them read from the queue, and do their work individually.
end the queue when it's done with, and let the threads exit and be reaped by the main process.
Something like in this answer: Perl daemonize with child daemons
... but are you sure there isn't a module that does what you want anyway?

Does Free Pascal have type variables like Haskell?

Haskell lets you define functions like thrice, which accepts an element of type a and returns a list of the element repeated three times, for any data type a.
thrice :: a -> [a]
thrice x = [x, x, x]
Does Free Pascal allow type variables? If not, is there another way to do this in Free Pascal?
As a haskell person who doesn't know Pascal, this appears to be a similar thing. Sorry for not being able to expand.
http://wiki.freepascal.org/Generics
Unfortunately FreePascal currently has only generic classes, not generic functions. Though, your goal can still be achieved, albeit a little awkwardly. You need to define a new class to encapsulate your operation:
unit Thrice;
interface
type
generic ThriceCalculator<A> = class
public
class function Calculate(x: A): array of A;
// We define it as a class function to avoid having to create an object when
// using Calculate. Similar to C++'s static member functions.
end;
implementation
function ThriceCalculator.Calculate(x: A): array of A;
begin
SetLength(Result, 3);
Result[0]:= x;
Result[1]:= x;
Result[2]:= x;
end;
end.
Now, unfortunately when you want to use this class with any specific type, you need to specialize it:
type
IntegerThrice = specialize ThriceCalculator<Integer>;
Only then you can use it as:
myArray:= IntegerThrice.Calculate(10);
As you see, Pascal is not the way to go for generic programming yet.
...answering from the future.
FreePascal has support for generic functions and procedures outside of classes.
Here's code that shows how you could implement Thrice as a special case of Times to also illustrate your ask about "FourTimes, FiveTimes, etc.".
The code includes a couple of examples using different types (integer, string, record):
{$mode objfpc}
program Thrice;
uses sysutils;
type
TPerson = record
First: String;
Age: Integer;
end;
generic TArray<T> = array of T;
var
aNumber: integer;
aWord: String;
thePerson: TPerson;
aPerson: TPerson;
generic function TimesFn<T, RT>(thing: T; times: Integer): RT;
var i: integer;
begin
setLength(Result, times);
for i:= 0 to times-1 do
Result[i] := thing;
end;
generic function ThriceFn<T, RT>(thing: T): RT;
begin
Result := specialize TimesFn<T, RT>(thing, 3);
end;
begin
{ Thrice examples }
for aNumber in specialize ThriceFn<Integer, specialize TArray<Integer>>(45) do
writeln(aNumber);
for aWord in specialize ThriceFn<String, specialize TArray<String>>('a word') do
writeln(aWord);
thePerson.First := 'Adam';
thePerson.Age := 23;
for aPerson in specialize ThriceFn<TPerson, specialize TArray<TPerson>>(thePerson) do
writeln(format('First: %s; Age: %d', [aPerson.First, aPerson.Age]));
{ Times example }
for aNumber in specialize TimesFn<Integer, specialize TArray<Integer>>(24, 10) do
writeln(aNumber);
end.

Resources