Welcome Guest! To enable all features please Login. New Registrations are disabled.

Notification

Icon
Error

Login


2 Pages12>
Options
Go to last post Go to first unread
Offline Kross  
#1 Posted : 27 February 2017 07:44:02(UTC)
Kross

Rank: Newbie

Groups: Registered
Joined: 15/02/2017(UTC)
Posts: 9
Russian Federation
Location: Moscow

how to know the name of the variable
for example
Count = 5

I can get the type of the variable
GetType(Count)="number"

I can get the value as a string
var2str(Count)="5"

I can even get a description of the variable
description(Count)="TestDescription"

I need to get the variable name "Count" as a string

With best wishes

Wanna join the discussion?! Login to your SMath Studio Forum forum account. New Registrations are disabled.

Offline Davide Carpi  
#2 Posted : 27 February 2017 12:42:41(UTC)
Davide Carpi


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 13/01/2012(UTC)
Posts: 2,647
Man
Italy
Location: Italy

Was thanked: 1329 time(s) in 875 post(s)
Hello Kross,

You can't. If Count is defined (IsDefined(Count)=1), his value is replaced before being passed as argument in any function, hence the name cannot be retrieved. Why you need this? Maybe we can help you to find an alternative way to do the same or a similar task.
If you like my plugins consider to support SMath Studio buying a plan; to offer me a coffee: paypal.me/dcprojects
Offline Kross  
#3 Posted : 27 February 2017 14:35:21(UTC)
Kross

Rank: Newbie

Groups: Registered
Joined: 15/02/2017(UTC)
Posts: 9
Russian Federation
Location: Moscow

Hello Davide!

For my program StandardProject
(see the topic in Extensions)

For data exchange
the user generates a matrix

In the columns which
1 column - the name of the variable as a string
2 column - variable value as double
3 column - description as a string

to simplify and reduce errors

I was planning to write a function
which input received the list of variables
and the output was formed by the above matrix

With best wishes!

P.s.
if you're interested as implemented
watch the video
https://yadi.sk/i/GT_K4LXm3EhvAq

the full set of videos
https://yadi.sk/d/0aXk5NGQ3EhvUo

Edited by user 27 February 2017 14:40:46(UTC)  | Reason: Not specified

Offline uni  
#4 Posted : 27 February 2017 16:15:41(UTC)
uni


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 10/11/2010(UTC)
Posts: 1,494
Man
Russian Federation

Was thanked: 1274 time(s) in 745 post(s)
Теоретически это можно сделать при помощи компонента Script, т.е. можно написать функцию на c#, которая возвращала бы нужную вам матрицу, перебрав все определения в документе. Практически же не знаю заработает это или нет, давно не пробовал компонент в работе.
Russia ☭ forever
Viacheslav N. Mezentsev
Offline Jean Giraud  
#5 Posted : 27 February 2017 17:27:52(UTC)
Jean Giraud

Rank: Guest

Groups: Registered
Joined: 04/07/2015(UTC)
Posts: 6,866
Canada

Was thanked: 981 time(s) in 809 post(s)
I don't understand the request .

Inst_Colebrook Pipe Data.sm (61kb) downloaded 32 time(s).
Offline Davide Carpi  
#6 Posted : 27 February 2017 18:37:34(UTC)
Davide Carpi


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 13/01/2012(UTC)
Posts: 2,647
Man
Italy
Location: Italy

Was thanked: 1329 time(s) in 875 post(s)
Originally Posted by: Kross Go to Quoted Post
I was planning to write a function
which input received the list of variables
and the output was formed by the above matrix

unfortunately this won't work; once passed through the function even descriptions will be lost (because the values are passed on evaluation, inside the function nothing is known but the values).

2017-02-27 16_38_07-SMath Studio 0.98.6260 - [Page1_].png

My suggestion is to create a function f(name,description,value) to create your matrix; function can be extended to 3 lists using vectorize() (or built directly to handle vectors). (or you can try to follow the hint given by uni).

Edited by user 27 February 2017 18:39:36(UTC)  | Reason: Not specified

If you like my plugins consider to support SMath Studio buying a plan; to offer me a coffee: paypal.me/dcprojects
Offline Kriss  
#7 Posted : 27 February 2017 19:06:13(UTC)
Kriss


Rank: Member

Groups: Registered
Joined: 23/01/2017(UTC)
Posts: 16
Russian Federation
Location: Moscow

Thank you, Davide!

I also think that use the method proposed uni

To uni
but I can't understand how to write scripts
I propose to start with the basics

from a script to get Smath Studio any value
while it turns out to show only variables in the debug panel (the output window)

К Вячеславу
пока не могу понять как писать скрипты
предлагаю начать с азов

как из скрипта получить в Smath Studio любое значение
пока получается показать переменные только в панели отладки (окно вывода)
Offline uni  
#8 Posted : 27 February 2017 21:12:31(UTC)
uni


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 10/11/2010(UTC)
Posts: 1,494
Man
Russian Federation

Was thanked: 1274 time(s) in 745 post(s)
В скрипте есть доступ к объекту store и его методам. Насколько я помню, там есть метод AddDefinition(), с помощью которого можно добавить определение в текущий документ. То есть можно определить переменную, которой фактически нет в документе. Так работает функция include(), которая динамически добавляет определения в документ. Вы можете создать любое выражение и оно будет доступно ниже компонента Скрипт.
Проблема в том, что нужно очень точно представлять результат, чтобы описать алгоритм в скрипте. Для этого лучше сначала написать функцию в виде дополнения, отладить её, а потом поместить в скрипт. Поэтому пользоваться этим инструментом полноценно пока могут лишь разработчики дополнений, которые знакомы с документацией.
Я попробую набросать что-нибудь работающее.
Russia ☭ forever
Viacheslav N. Mezentsev
Offline Kross  
#9 Posted : 28 February 2017 07:50:23(UTC)
Kross

Rank: Newbie

Groups: Registered
Joined: 15/02/2017(UTC)
Posts: 9
Russian Federation
Location: Moscow

Спасибо за содействие!

Буду очень признателен.
Offline mkraska  
#10 Posted : 28 February 2017 20:13:48(UTC)
mkraska


Rank: Advanced Member

Groups: Registered
Joined: 15/04/2012(UTC)
Posts: 1,986
Germany

Was thanked: 1124 time(s) in 721 post(s)
Originally Posted by: uni Go to Quoted Post

Проблема в том, что нужно очень точно представлять результат, чтобы описать алгоритм в скрипте. Для этого лучше сначала написать функцию в виде дополнения, отладить её, а потом поместить в скрипт. Поэтому пользоваться этим инструментом полноценно пока могут лишь разработчики дополнений, которые знакомы с документацией.
Я попробую набросать что-нибудь работающее.


Just for curiosity and without any insight into real plugin-coding: Isn't the programmatic representation of the expressions as required in the script region that what the "Expression -> terms" dialog in the Development tools produces?

Is there a need to change the values for "List name" and "Array name"?

2017-02-28 18_07_23-Expression - Terms.png

Martin Kraska

Pre-configured portable distribution of SMath Studio: https://smath.com/wiki/SMath_with_Plugins.ashx
Offline uni  
#11 Posted : 28 February 2017 20:34:10(UTC)
uni


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 10/11/2010(UTC)
Posts: 1,494
Man
Russian Federation

Was thanked: 1274 time(s) in 745 post(s)
There are several ways how to use Script region.

Example 1.

Code:
try
{
    TMatrix m = new TMatrix( new TNumber[ 1, 3 ] );
    
    m.unit.SetValue( ( TNumber ) 1, new long[] { 0, 0 } );
    m.unit.SetValue( ( TNumber ) 2, new long[] { 0, 1 } );
    m.unit.SetValue( ( TNumber ) new TDouble( "\"Text\"" ), new long[] { 0, 2 } );
    
    store.AddDefinition( "out", m.ToTerms(), new Term[0] );
}
catch ( Exception ex ) 
{
    store.TraceData( ex.Message );
}


2017-02-28_22-29-27.png
Russia ☭ forever
Viacheslav N. Mezentsev
Offline frapuano  
#12 Posted : 28 February 2017 20:54:19(UTC)
frapuano


Rank: Advanced Member

Groups: Registered
Joined: 01/08/2010(UTC)
Posts: 115
Man
Italy
Location: Rome

Was thanked: 13 time(s) in 13 post(s)
Originally Posted by: uni Go to Quoted Post
There are several ways how to use Script region.

Example 1.

Code:
try
{
    TMatrix m = new TMatrix( new TNumber[ 1, 3 ] );
    
    m.unit.SetValue( ( TNumber ) 1, new long[] { 0, 0 } );
    m.unit.SetValue( ( TNumber ) 2, new long[] { 0, 1 } );
    m.unit.SetValue( ( TNumber ) new TDouble( "\"Text\"" ), new long[] { 0, 2 } );
    
    store.AddDefinition( "out", m.ToTerms(), new Term[0] );
}
catch ( Exception ex ) 
{
    store.TraceData( ex.Message );
}


2017-02-28_22-29-27.png


...it is quite sad/frustrating not to understand better its usage ...just to organize to give it a try.

Franco
Offline Kross  
#13 Posted : 01 March 2017 11:32:40(UTC)
Kross

Rank: Newbie

Groups: Registered
Joined: 15/02/2017(UTC)
Posts: 9
Russian Federation
Location: Moscow

To uni

it's great
how do I output the variable in the field Smath Studio - understand
Question
1. how to get a specific variable from Smath Studio
2. is it possible to imagine a script as a function Smath Studio
for the subsequent call as a "normal" function Smath Studio

Перевод
это отлично
как вывести переменную в поле Smath Studio - понял
Вопрос
1. как получить конкретную переменную из Smath Studio
2. можно ли скрипт представить в виде функции Smath Studio
для последующего вызова как обычной функции Smath Studio
Offline uni  
#14 Posted : 01 March 2017 13:03:09(UTC)
uni


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 10/11/2010(UTC)
Posts: 1,494
Man
Russian Federation

Was thanked: 1274 time(s) in 745 post(s)
Example 2. How to get definition by name

Code:
try
{
    string varname = "a";

    // System.Collections.Generic пока не подключена, поэтому используем полное имя класса.
    // Переменная store не содержит публичного метода или свойства для доступа к коллекции определений,
    // поэтому создадим список "вручную". Со списком работать удобнее, чем с массивом.
    System.Collections.Generic.List<Definition> list = new System.Collections.Generic.List<Definition>();

    for ( int n = 0; n < store.Count; n++ ) list.Add( store[ n ] );

    // Функция условия для поиска определения.
    Predicate< Definition > cond = delegate( Definition x )
    {
        // Если имя определения (переменной) равно varname.
        return x.Name.Equals( varname );
    };

    // Метод Find ищет первый элемент, который удовлетворяет условию.
    Definition def = list.Find( cond );

    // Если элемент найден, то что-нибудь делаем.
    store.TraceData( varname + ( def != null ? " " : " not " ) + "found" );

    if ( def != null )
    {
        TMatrix m = new TMatrix( new TNumber[ 2, 3 ] );

        m.unit.SetValue( ( TNumber ) new TDouble( "\"name\"" ), new long[] { 0, 0 } );
        m.unit.SetValue( ( TNumber ) new TDouble( "\"descr\"" ), new long[] { 0, 1 } );
        m.unit.SetValue( ( TNumber ) new TDouble( "\"value\"" ), new long[] { 0, 2 } );

        m.unit.SetValue( ( TNumber ) new TDouble( "\"" + def.Name + "\"" ), new long[] { 1, 0 } );
        m.unit.SetValue( ( TNumber ) new TDouble( "\"" + def.Description + "\"" ), new long[] { 1, 1 } );

        TNumber value = SMath.Math.Numeric.Expression.Calculate( def.Result, store );

        m.unit.SetValue( value, new long[] { 1, 2 } );

        Definition res = new Definition( "out", m.ToTerms(), new Term[ 0 ] );

        store.AddDefinition( res );
    }
}
catch ( Exception ex )
{
    store.TraceData( ex.Message );
}


2017-03-01_15-01-34.png
Russia ☭ forever
Viacheslav N. Mezentsev
Offline uni  
#15 Posted : 01 March 2017 13:05:14(UTC)
uni


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 10/11/2010(UTC)
Posts: 1,494
Man
Russian Federation

Was thanked: 1274 time(s) in 745 post(s)
Originally Posted by: Kross Go to Quoted Post
To uni

it's great
how do I output the variable in the field Smath Studio - understand
Question
1. how to get a specific variable from Smath Studio
2. is it possible to imagine a script as a function Smath Studio
for the subsequent call as a "normal" function Smath Studio

Перевод
это отлично
как вывести переменную в поле Smath Studio - понял
Вопрос
1. как получить конкретную переменную из Smath Studio
2. можно ли скрипт представить в виде функции Smath Studio
для последующего вызова как обычной функции Smath Studio


2. Как функцию представить нельзя.

П.С. Теоретически можно написать дополнение, в котором можно использовать написанную функцию и потом вызывать её многократно как стороннюю. Я бы мог даже добавить кнопку в компоненте Скрипт, по которой формировалась сборка, но это всё сложно и целая эпопея.

Edited by user 01 March 2017 13:21:41(UTC)  | Reason: Not specified

Russia ☭ forever
Viacheslav N. Mezentsev
Offline Davide Carpi  
#16 Posted : 01 March 2017 13:43:44(UTC)
Davide Carpi


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 13/01/2012(UTC)
Posts: 2,647
Man
Italy
Location: Italy

Was thanked: 1329 time(s) in 875 post(s)
2017-03-01 11_41_51-SMath Studio - [Page1_].png
If you like my plugins consider to support SMath Studio buying a plan; to offer me a coffee: paypal.me/dcprojects
Offline Kross  
#17 Posted : 01 March 2017 14:48:42(UTC)
Kross

Rank: Newbie

Groups: Registered
Joined: 15/02/2017(UTC)
Posts: 9
Russian Federation
Location: Moscow

То uni
Возникли проблемы
при использовании Лист.exe файл - исполняемый
1. Не обновляется поле из out переменной (выходной)
2. При перемещения тела скрипта в Область и последующим скрытием Области
при запуске Лист.exe файл - появляется сообщение - No 'Tech.CodeGenaration.dll' found in 'Лист'.
Offline Kross  
#18 Posted : 01 March 2017 15:13:26(UTC)
Kross

Rank: Newbie

Groups: Registered
Joined: 15/02/2017(UTC)
Posts: 9
Russian Federation
Location: Moscow

here's what you need to in the end

image.jpg

Edited by moderator 01 March 2017 15:29:58(UTC)  | Reason: Not specified

Offline uni  
#19 Posted : 01 March 2017 15:26:19(UTC)
uni


Rank: Advanced Member

Groups: Registered, Advanced Member
Joined: 10/11/2010(UTC)
Posts: 1,494
Man
Russian Federation

Was thanked: 1274 time(s) in 745 post(s)
Я не знаю как пересчитать лист в exe версии. Для работы нужно скопировать в папку с exe-файлом следующие сборки:

Из папки с плагином (%user%\Application Data\SMath\extensions\plugins\20ad815b-bc5e-487d-9258-57fde2ac6de8\0.1.5997.41919\):

IronPython.dll
IronPython.Modules.dll
Microsoft.Dynamic.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Core.dll
Microsoft.Scripting.Debugging.dll
Microsoft.Scripting.ExtensionAttribute.dll
Tech.CodeGeneration.dll

Из места установки программы:

SMath.Controls.dll
SMath.Manager.dll
SMath.Math.Numeric.dll
SMath.Math.Symbolic.dll

Вообще, вам лучше научиться писать плагины самому, тогда не нужно будет искать других путей. Ваша задача не решаема стандартными средствами SMath Studio.
Russia ☭ forever
Viacheslav N. Mezentsev
Offline Kriss  
#20 Posted : 01 March 2017 19:28:53(UTC)
Kriss


Rank: Member

Groups: Registered
Joined: 23/01/2017(UTC)
Posts: 16
Russian Federation
Location: Moscow

Все ясно,
Спасибо!

Буду разбираться
с написанием плагина!
Users browsing this topic
Guest
2 Pages12>
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.