Maya Python/MEL script to replace/swap out material - python

I've search around the web for about 6 hours without luck on this issue.
In autodesk maya (2016) I want to swap out/replace materials from standard phong material named "dg_plastic" to another sort of material named "plastic".
The standard phong material will have a pre-defined name, as in the example above.
We have a library of ready made materials with pre-defined names to pick from.
Is there a way to write a script in Python or MEL to solve this?
Thanks!

There is a old thread on CreativeCrash that deals with this. The script that i presented there look as follows (see original thread for more info):
proc connectAndSet(string $original, string $target){
$conn = `connectionInfo -sfd $original`;
if ($conn != ""){
connectAttr -force $conn $target;
} else {
connectAttr -force $original $target;
disconnectAttr $original $target;
}
}
proc convertPhongToMia(string $original){
$target = `mrCreateCustomNode -asShader "" mia_material_x`;
connectAndSet($original + ".color", $target + ".diffuse");
// ... any other mapping you need comes here...
// a bit weak test should work for simple materials,
// not used in special context
$sg = `connectionInfo -dfs ($target + ".message")`;
$sgr = `match "[^.]*" ((string)$sg[0])`;
$sg0 = `connectionInfo -dfs ($original + ".outColor")`;
$sgr0=`match "[^.]*" ((string)$sg0[0])`;
sets -e -forceElement $sgr `sets -q $sgr0`;
delete $original;
rename $sgr $sgr0;
rename $target $original;
}
for ($item in `ls -et phong`)
convertPhongToMia($item);
It should be possible for you to re purpose this for your needs.

Related

Running a python script in C# after publishing C# project [duplicate]

I have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This in itself is no problem:
...Usual Stuff
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace Program
{
public partial class Form1 : Form
{
Microsoft.Scripting.Hosting.ScriptEngine py;
Microsoft.Scripting.Hosting.ScriptScope s;
public Form1()
{
InitializeComponent();
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
}
private void doPython()
{
//Step 1:
//Creating a new script runtime
var ironPythonRuntime = Python.CreateRuntime();
//Step 2:
//Load the Iron Python file/script into the memory
//Should be resolve at runtime
dynamic loadIPython = ironPythonRuntime.;
//Step 3:
//Invoke the method and print the result
double n = loadIPython.add(100, 200);
numericUpDown1.Value = (decimal)n;
}
}
}
However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?
Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...
and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else; If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;
var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);

Python print certain lines from terraform output from certain resource

I'm trying to print certain line, from a string that is inside a variable in python3, the variable comes from os.popen execution like the following example.
some_url = os.popen(f"terraform state show 'module.dns.aws_route53_record.main'").read()
In order to print the output I do something like this
print(f"{color.DARKCYAN}[SOME_URL]{color.END}, {some_url}")
But the output look's like this...
[SOME_URL], # module.dns.aws_route53_record.main:
resource "aws_route53_record" "main" {
allow_overwrite = true
fqdn = "xxxxxxxxxx-xxxxxxxxxxxx-xxxxxxx-xxxxxx.xxxxxx.xxxxxxxx.xxxxxxx.com"
id = "xxxxxxxxxxxxxxxxxxxxxxxxx_xxxxx-xxxxxxxxxxxxx-xxxxxx-xxxxx.xxxxx.xxxx.xxxxxxx.com_CNAME"
name = "xxxxxxxxx-xxxxxxxxxxxxx-xxxxxxx-xxxxxxx.xxxxxxxxx.xx.xxxxxx.xxxx"
records = [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxx.xxxxxxxxxx.xxxx.xxxxxxxxxxxx.xxx",
]
ttl = xxxx
type = "xxxx"
zone_id = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
}
Is it a simple way to parse and print just the line with the fqdn after [SOME_URL] ???
Is this what you were looking for?
import re
string = '''
resource "aws_route53_record" "main" {
allow_overwrite = true
fqdn = "xxxxxxxxxx-xxxxxxxxxxxx-xxxxxxx-xxxxxx.xxxxxx.xxxxxxxx.xxxxxxx.com"
id = "xxxxxxxxxxxxxxxxxxxxxxxxx_xxxxx-xxxxxxxxxxxxx-xxxxxx-xxxxx.xxxxx.xxxx.xxxxxxx.com_CNAME"
name = "xxxxxxxxx-xxxxxxxxxxxxx-xxxxxxx-xxxxxxx.xxxxxxxxx.xx.xxxxxx.xxxx"
records = [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxx.xxxxxxxxxx.xxxx.xxxxxxxxxxxx.xxx",
]
ttl = xxxx
type = "xxxx"
zone_id = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
}
'''
if m := re.search("(?<=\n)\s*fqdn\s.*", string):
fqdn = re.sub("\s+=", " =", m.group().strip())
print(f"\x1b[1;36m[SOME_URL]\x1b[0m, {fqdn}")
[SOME_URL], fqdn = "xxxxxxxxxx-xxxxxxxxxxxx-xxxxxxx-xxxxxx.xxxxxx.xxxxxxxx.xxxxxxx.com"
The expression should be precise enough.
I can recommend learning regular expressions especially for these cases!
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.'
Now they have two problems."
"Regular expressions tend to be easier to write than they are to read. This is less of a problem if you are the only one who ever needs to maintain the program (or sed routine, or shell script, or what have you), but if several people need to watch over it, the syntax can turn into more of a hindrance than an aid.")
(Stephen Ramsay, University of Virginia)
Terraform has a very nice way to grant you access to information you need from the state in the form of outputs values. In your case, you can create an output variable for the fqdn and read just this one piece of information:
output "main_dns" {
value = aws_route53_record.main.fqdn
}
And in the python call you use the terraform output main_dns command
some_url = os.popen(f"terraform output main_dns").read()
Now you can use the fqdn as you see fit.
terraform output documentation

How can I make QScintilla auto-indent like SublimeText?

Consider the below mcve:
import sys
import textwrap
from PyQt5.Qsci import QsciScintilla
from PyQt5.Qt import *
if __name__ == '__main__':
app = QApplication(sys.argv)
view = QsciScintilla()
view.SendScintilla(view.SCI_SETMULTIPLESELECTION, True)
view.SendScintilla(view.SCI_SETMULTIPASTE, 1)
view.SendScintilla(view.SCI_SETADDITIONALSELECTIONTYPING, True)
view.setAutoIndent(True)
view.setTabWidth(4)
view.setIndentationGuides(True)
view.setIndentationsUseTabs(False)
view.setBackspaceUnindents(True)
view.setText(textwrap.dedent("""\
def foo(a,b):
print('hello')
"""))
view.show()
app.exec_()
The behaviour of the auto-indent of the above snippet is really bad when comparing it with editors such as SublimeText or CodeMirror. First let's see how nice will behave the autoindent feature in SublimeText with single or multiple selections.
And now let's see how the auto-indent works in with the above snippet:
In comparison to SublimeText the way QScintilla works when auto-indentation is enabled with both single/multi selections is corky and really bad/unusable.
The first step to make the widget more like SublimeText/Codemirror would be disconnecting the current slot that makes autoindentation to behave badly, we can achieve that by doing:
print(view.receivers(view.SCN_CHARADDED))
view.SCN_CHARADDED.disconnect()
print(view.receivers(view.SCN_CHARADDED))
At this point you'd be ready to connect SCN_CHARADDED with your custom slot doing all the magic :)
QUESTION: How would you modify the above snippet so all selections will be preserved and the auto-indentation will behave exactly like SublimeText, Codemirror or any serious text editor out there?
REFERENCES:
https://www.riverbankcomputing.com/static/Docs/QScintilla/classQsciScintillaBase.html#signals
QScintilla source code, below you can see what the private slot we've disconnected by using disconnect would look like:
qsciscintilla.h
class QSCINTILLA_EXPORT QsciScintilla : public QsciScintillaBase
{
Q_OBJECT
public:
...
private slots:
void handleCharAdded(int charadded);
...
private:
void autoIndentation(char ch, long pos);
qsciscintilla.cpp
connect(this,SIGNAL(SCN_CHARADDED(int)),
SLOT(handleCharAdded(int)));
...
// Handle the addition of a character.
void QsciScintilla::handleCharAdded(int ch)
{
// Ignore if there is a selection.
long pos = SendScintilla(SCI_GETSELECTIONSTART);
if (pos != SendScintilla(SCI_GETSELECTIONEND) || pos == 0)
return;
// If auto-completion is already active then see if this character is a
// start character. If it is then create a new list which will be a subset
// of the current one. The case where it isn't a start character seems to
// be handled correctly elsewhere.
if (isListActive() && isStartChar(ch))
{
cancelList();
startAutoCompletion(acSource, false, use_single == AcusAlways);
return;
}
// Handle call tips.
if (call_tips_style != CallTipsNone && !lex.isNull() && strchr("(),", ch) != NULL)
callTip();
// Handle auto-indentation.
if (autoInd)
{
if (lex.isNull() || (lex->autoIndentStyle() & AiMaintain))
maintainIndentation(ch, pos);
else
autoIndentation(ch, pos);
}
// See if we might want to start auto-completion.
if (!isCallTipActive() && acSource != AcsNone)
{
if (isStartChar(ch))
startAutoCompletion(acSource, false, use_single == AcusAlways);
else if (acThresh >= 1 && isWordCharacter(ch))
startAutoCompletion(acSource, true, use_single == AcusAlways);
}
}
IMPORTANT: I've decided to post the relevant c++ bits so you'll got more background about how the indentation is achieved internally to give more clues about a possible replacement... The goal of this thread is to try to find a pure python solution though. I'd like to avoid modifying the QScintilla source code (if possible) so maintenance/upgrading will remain as simple as possible and QScintilla dep can still be seen as a black box.
It looks like you have to code your own version, the documentation mentions the most important point's about it already in the chapter Installation:
As supplied QScintilla will be built as a shared library/DLL and installed in the same directories as the Qt libraries and include files.
If you wish to build a static version of the library then pass CONFIG+=staticlib on the qmake command line.
If you want to make more significant changes to the configuration then edit the file qscintilla.pro in the Qt4Qt5 directory.
If you do make changes, specifically to the names of the installation directories or the name of the library, then you may also need to update the Qt4Qt5/features/qscintilla2.prf file.*
Further steps are explained there too.
There is no integrated way to make auto-indentation work in QScintilla (especially as it is in SublimeText). This behaviour is a language-specific and user-specific. Native Scintilla documentation includes examples of how to trigger auto-indentation. Sorry but it's written in C#. I haven't found it written in Python.
Here's a code (I know that a QScintilla is a Port to Qt, this Scintilla-oriented code should work with QScintilla too, or at the worst you can adapt it for C++):
private void Scintilla_InsertCheck(object sender, InsertCheckEventArgs e) {
if ((e.Text.EndsWith("" + Constants.vbCr) || e.Text.EndsWith("" + Constants.vbLf))) {
int startPos = Scintilla.Lines(Scintilla.LineFromPosition(Scintilla.CurrentPosition)).Position;
int endPos = e.Position;
string curLineText = Scintilla.GetTextRange(startPos, (endPos - startPos));
// Text until the caret so that the whitespace is always
// equal in every line.
Match indent = Regex.Match(curLineText, "^[ \\t]*");
e.Text = (e.Text + indent.Value);
if (Regex.IsMatch(curLineText, "{\\s*$")) {
e.Text = (e.Text + Constants.vbTab);
}
}
}
private void Scintilla_CharAdded(object sender, CharAddedEventArgs e) {
//The '}' char.
if (e.Char == 125) {
int curLine = Scintilla.LineFromPosition(Scintilla.CurrentPosition);
if (Scintilla.Lines(curLine).Text.Trim() == "}") {
//Check whether the bracket is the only thing on the line.
//For cases like "if() { }".
SetIndent(Scintilla, curLine, GetIndent(Scintilla, curLine) - 4);
}
}
}
//Codes for the handling the Indention of the lines.
//They are manually added here until they get officially
//added to the Scintilla control.
#region "CodeIndent Handlers"
const int SCI_SETLINEINDENTATION = 2126;
const int SCI_GETLINEINDENTATION = 2127;
private void SetIndent(ScintillaNET.Scintilla scin, int line, int indent) {
scin.DirectMessage(SCI_SETLINEINDENTATION, new IntPtr(line), new IntPtr(indent));
}
private int GetIndent(ScintillaNET.Scintilla scin, int line) {
return (scin.DirectMessage(SCI_GETLINEINDENTATION, new IntPtr(line), null).ToInt32);
}
#endregion
Hope this helps.

how can i pass xml format data from flex to python

i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python should convert all the data into xml format,and pass all the data to the flex..
Thank's in advance.....
See http://www.artima.com/weblogs/viewpost.jsp?thread=208528 for more details, here is a breif overview of what I think you are looking for.
The SimpleXMLRPCServer library allows you to easily create a server. Here's about the simplest server you can create, which provides two services to manipulate strings:
import sys
from random import shuffle
from SimpleXMLRPCServer import SimpleXMLRPCServer
class MyFuncs:
def reverse(self, str) :
x = list(str);
x.reverse();
return ''.join(x);
def scramble(self, str):
x = list(str);
shuffle(x);
return ''.join(x);
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(MyFuncs())
server.serve_forever()
Once you make a connection to the server, that server acts like a local object. You call the server's methods just like they're ordinary methods of that object.
This is about as clean an RPC implementation as you can hope for (and other Python RPC libraries exist; for example, CORBA clients). But it's all text based; not very satisfying when trying to create polished applications with nice GUIs. What we'd like is the best of all worlds -- Python (or your favorite language) doing the heavy lifting under the covers, and Flex creating the user experience.
To use the library, download it and unpack it somewhere. The package includes all the source code and the compiled as3-rpclib.swc library -- the .swc extension indicates an archive file, and pieces of this library can be pulled out and incorporated into your final .swf. To include the library in your project, you must tell Flexbuilder (you can get a free trial or just use the free command-line tools, and add on the Apollo portion) where the library is located by going to Project|Properties and selecting "Apollo Build Path," then choosing the "Library path" tab and pressing the "Add SWC..." button. Next, you add the namespace ak33m to your project as seen in the code below, and you're ready to create an XMLRPCObject.
Note: the only reason I used Apollo here was that I was thinking in terms of desktop applications with nice UIs. You can just as easily make it a Flex app.
Here's the entire Apollo application as a single MXML file, which I'll explain in detail:
<?xml version="1.0" encoding="utf-8"?>
<mx:ApolloApplication xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:ak33m="http://ak33m.com/mxml" layout="absolute">
<mx:Form>
<mx:FormHeading label="String Modifier"/>
<mx:FormItem label="Input String">
<mx:TextInput id="instring" change="manipulate()"/>
</mx:FormItem>
<mx:FormItem label="Reversed">
<mx:Text id="reversed"/>
</mx:FormItem>
<mx:FormItem label="Scrambled">
<mx:Text id="scrambled"/>
</mx:FormItem>
</mx:Form>
<ak33m:XMLRPCObject id="server" endpoint="http://localhost:8000"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.AsyncToken;
import mx.controls.Alert;
import mx.collections.ItemResponder;
private function manipulate() : void {
server.reverse(instring.text).addResponder(new ItemResponder(reverseResult, onFault));
server.scramble(instring.text).addResponder(new ItemResponder(scrambleResult, onFault));
}
private function reverseResult(event : ResultEvent, token : AsyncToken = null) : void {
reversed.text = event.result.toString();
}
private function scrambleResult(event : ResultEvent, token : AsyncToken = null) : void {
scrambled.text = event.result.toString();
}
private function onFault (event : FaultEvent, token : AsyncToken = null) : void {
Alert.show(event.fault.faultString, event.fault.faultCode);
}
]]>
</mx:Script>
</mx:ApolloApplication>

Get the title of the current active Window/Document in Mac OS X

Refering to a previously asked question, I would like to know how to get the title of the current active document.
I tried the script mention in the answers to the question above. This works, but only gives me the name of the application. For example, I am writing this question: When I fire up the script it gives me the name of the application, i.e. "Firefox". This is pretty neat, but does not really help. I would rather like to capture the title of my current active document. See the image.
Firefox title http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg
I am using Leopard, so no backward compatibility needed. Also I am using Python's Appkit to gain access to the NSWorkspace class, but if you tell me the Objective-C code, I could figure out the translation to Python.
Ok, I've got a solution which is not very satisfing, thats why I don't mark Koen Bok's answer. At least not yet.
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
tell application frontApp
if the (count of windows) is not 0 then
set window_name to name of front window
end if
end tell
Save as script and invoke it with osascript from the shell.
As far as I know your best bet is wrapping an AppleScript. But AppleScript is magic to me so I leave it as an exercise for the questioner :-)
This might help a little: A script to resize frontmost two windows to fill screen - Mac OS X Hints
In Objective-C, the short answer, using a little Cocoa and mostly the Carbon Accessibility API is:
// Get the process ID of the frontmost application.
NSRunningApplication* app = [[NSWorkspace sharedWorkspace]
frontmostApplication];
pid_t pid = [app processIdentifier];
// See if we have accessibility permissions, and if not, prompt the user to
// visit System Preferences.
NSDictionary *options = #{(id)kAXTrustedCheckOptionPrompt: #YES};
Boolean appHasPermission = AXIsProcessTrustedWithOptions(
(__bridge CFDictionaryRef)options);
if (!appHasPermission) {
return; // we don't have accessibility permissions
// Get the accessibility element corresponding to the frontmost application.
AXUIElementRef appElem = AXUIElementCreateApplication(pid);
if (!appElem) {
return;
}
// Get the accessibility element corresponding to the frontmost window
// of the frontmost application.
AXUIElementRef window = NULL;
if (AXUIElementCopyAttributeValue(appElem,
kAXFocusedWindowAttribute, (CFTypeRef*)&window) != kAXErrorSuccess) {
CFRelease(appElem);
return;
}
// Finally, get the title of the frontmost window.
CFStringRef title = NULL;
AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute,
(CFTypeRef*)&title);
// At this point, we don't need window and appElem anymore.
CFRelease(window);
CFRelease(appElem);
if (result != kAXErrorSuccess) {
// Failed to get the window title.
return;
}
// Success! Now, do something with the title, e.g. copy it somewhere.
// Once we're done with the title, release it.
CFRelease(title);
Alternatively, it may be simpler to use the CGWindow API, as alluded to in this StackOverflow answer.
refered to https://stackoverflow.com/a/23451568/11185460
package main
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa
#import <Cocoa/Cocoa.h>
int
GetFrontMostAppPid(void){
NSRunningApplication* app = [[NSWorkspace sharedWorkspace]
frontmostApplication];
pid_t pid = [app processIdentifier];
return pid;
}
CFStringRef
GetAppTitle(pid_t pid) {
CFStringRef title = NULL;
// Get the process ID of the frontmost application.
// NSRunningApplication* app = [[NSWorkspace sharedWorkspace]
// frontmostApplication];
// pid_t pid = [app processIdentifier];
// See if we have accessibility permissions, and if not, prompt the user to
// visit System Preferences.
NSDictionary *options = #{(id)kAXTrustedCheckOptionPrompt: #YES};
Boolean appHasPermission = AXIsProcessTrustedWithOptions(
(__bridge CFDictionaryRef)options);
if (!appHasPermission) {
return title; // we don't have accessibility permissions
}
// Get the accessibility element corresponding to the frontmost application.
AXUIElementRef appElem = AXUIElementCreateApplication(pid);
if (!appElem) {
return title;
}
// Get the accessibility element corresponding to the frontmost window
// of the frontmost application.
AXUIElementRef window = NULL;
if (AXUIElementCopyAttributeValue(appElem,
kAXFocusedWindowAttribute, (CFTypeRef*)&window) != kAXErrorSuccess) {
CFRelease(appElem);
return title;
}
// Finally, get the title of the frontmost window.
AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute,
(CFTypeRef*)&title);
// At this point, we don't need window and appElem anymore.
CFRelease(window);
CFRelease(appElem);
if (result != kAXErrorSuccess) {
// Failed to get the window title.
return title;
}
// Success! Now, do something with the title, e.g. copy it somewhere.
// Once we're done with the title, release it.
CFRelease(title);
return title;
}
static inline CFIndex cfstring_utf8_length(CFStringRef str, CFIndex *need) {
CFIndex n, usedBufLen;
CFRange rng = CFRangeMake(0, CFStringGetLength(str));
return CFStringGetBytes(str, rng, kCFStringEncodingUTF8, 0, 0, NULL, 0, need);
}
*/
import "C"
import (
"github.com/shirou/gopsutil/v3/process"
"reflect"
"unsafe"
)
//import "github.com/shirou/gopsutil/v3/process"
func cfstringGo(cfs C.CFStringRef) string {
var usedBufLen C.CFIndex
n := C.cfstring_utf8_length(cfs, &usedBufLen)
if n <= 0 {
return ""
}
rng := C.CFRange{location: C.CFIndex(0), length: n}
buf := make([]byte, int(usedBufLen))
bufp := unsafe.Pointer(&buf[0])
C.CFStringGetBytes(cfs, rng, C.kCFStringEncodingUTF8, 0, 0, (*C.UInt8)(bufp), C.CFIndex(len(buf)), &usedBufLen)
sh := &reflect.StringHeader{
Data: uintptr(bufp),
Len: int(usedBufLen),
}
return *(*string)(unsafe.Pointer(sh))
}
func main() {
pid := C.GetFrontMostAppPid()
ps, _ := process.NewProcess(int32(pid))
title_ref := C.CFStringRef(C.GetAppTitle(pid))
println(pid) // pid
println(ps.Name()) // process name
println(cfstringGo(title_ref)) // active window title
}
I then found this property wont change after it is called.
By this, only after we implement NSWorkspaceDidActivateApplicationNotification, we can monitor the change of activity window. But I didn't find any solution which can implement NSWorkspaceDidActivateApplicationNotification in golang.
A workaround method is compile one go program and call it by another go program. I then try full Objective-C code in here

Categories

Resources