how to know the name of the variable

how to know the name of the variable - Messages

#1 Posted: 2/27/2017 1:44:02 AM
Kross

Kross

0 likes in 10 posts.

Group: User

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
#2 Posted: 2/27/2017 6:42:41 AM
Davide Carpi

Davide Carpi

1416 likes in 2873 posts.

Group: Moderator

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 please consider to support the program buying a license; for personal contributions to me: paypal.me/dcprojects
#3 Posted: 2/27/2017 8:35:21 AM
Kross

Kross

0 likes in 10 posts.

Group: User

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
#4 Posted: 2/27/2017 10:15:41 AM
Вячеслав Мезенцев

Вячеслав Мезенцев

1402 likes in 1708 posts.

Group: Moderator

Теоретически это можно сделать при помощи компонента Script, т.е. можно написать функцию на c#, которая возвращала бы нужную вам матрицу, перебрав все определения в документе. Практически же не знаю заработает это или нет, давно не пробовал компонент в работе.
Russia ☭ forever, Viacheslav N. Mezentsev
#5 Posted: 2/27/2017 11:27:52 AM
Jean Giraud

Jean Giraud

983 likes in 6866 posts.

Group: User

I don't understand the request .

Inst_Colebrook Pipe Data.sm (60 KiB) downloaded 61 time(s).
#6 Posted: 2/27/2017 12:37:34 PM
Davide Carpi

Davide Carpi

1416 likes in 2873 posts.

Group: Moderator

Wrote

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).
If you like my plugins please consider to support the program buying a license; for personal contributions to me: paypal.me/dcprojects
#7 Posted: 2/27/2017 1:06:13 PM
Krid

Krid

0 likes in 16 posts.

Group: User

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 любое значение
пока получается показать переменные только в панели отладки (окно вывода)
#8 Posted: 2/27/2017 3:12:31 PM
Вячеслав Мезенцев

Вячеслав Мезенцев

1402 likes in 1708 posts.

Group: Moderator

В скрипте есть доступ к объекту store и его методам. Насколько я помню, там есть метод AddDefinition(), с помощью которого можно добавить определение в текущий документ. То есть можно определить переменную, которой фактически нет в документе. Так работает функция include(), которая динамически добавляет определения в документ. Вы можете создать любое выражение и оно будет доступно ниже компонента Скрипт.
Проблема в том, что нужно очень точно представлять результат, чтобы описать алгоритм в скрипте. Для этого лучше сначала написать функцию в виде дополнения, отладить её, а потом поместить в скрипт. Поэтому пользоваться этим инструментом полноценно пока могут лишь разработчики дополнений, которые знакомы с документацией.
Я попробую набросать что-нибудь работающее.
Russia ☭ forever, Viacheslav N. Mezentsev
#9 Posted: 2/28/2017 1:50:23 AM
Kross

Kross

0 likes in 10 posts.

Group: User

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

Буду очень признателен.
#10 Posted: 2/28/2017 2:13:48 PM
Martin Kraska

Martin Kraska

1222 likes in 2150 posts.

Group: Moderator

Wrote


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



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://en.smath.info/wiki/SMath%20with%20Plugins.ashx
#11 Posted: 2/28/2017 2:34:10 PM
Вячеслав Мезенцев

Вячеслав Мезенцев

1402 likes in 1708 posts.

Group: Moderator

There are several ways how to use Script region.

Example 1.

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
#12 Posted: 2/28/2017 2:54:19 PM
frapuano

frapuano

13 likes in 115 posts.

Group: User

Wrote

There are several ways how to use Script region.

Example 1.

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
#13 Posted: 3/1/2017 5:32:40 AM
Kross

Kross

0 likes in 10 posts.

Group: User

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
#14 Posted: 3/1/2017 7:03:09 AM
Вячеслав Мезенцев

Вячеслав Мезенцев

1402 likes in 1708 posts.

Group: Moderator

Example 2. How to get definition by name

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
#15 Posted: 3/1/2017 7:05:14 AM
Вячеслав Мезенцев

Вячеслав Мезенцев

1402 likes in 1708 posts.

Group: Moderator

Wrote

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. Как функцию представить нельзя.

П.С. Теоретически можно написать дополнение, в котором можно использовать написанную функцию и потом вызывать её многократно как стороннюю. Я бы мог даже добавить кнопку в компоненте Скрипт, по которой формировалась сборка, но это всё сложно и целая эпопея.
Russia ☭ forever, Viacheslav N. Mezentsev
#16 Posted: 3/1/2017 7:43:44 AM
Davide Carpi

Davide Carpi

1416 likes in 2873 posts.

Group: Moderator

2017-03-01 11_41_51-SMath Studio - [Page1_].png
If you like my plugins please consider to support the program buying a license; for personal contributions to me: paypal.me/dcprojects
#17 Posted: 3/1/2017 8:48:42 AM
Kross

Kross

0 likes in 10 posts.

Group: User

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

Kross

0 likes in 10 posts.

Group: User

here's what you need to in the end

image.jpg
#19 Posted: 3/1/2017 9:26:19 AM
Вячеслав Мезенцев

Вячеслав Мезенцев

1402 likes in 1708 posts.

Group: Moderator

Я не знаю как пересчитать лист в 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
#20 Posted: 3/1/2017 1:28:53 PM
Krid

Krid

0 likes in 16 posts.

Group: User

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

Буду разбираться
с написанием плагина!
  • New Posts New Posts
  • No New Posts No New Posts