text:
Q: TypeError: __init__() takes from 1 to 6 positional arguments but 7 were given I am using multithreading concept in my script. But I am getting the above error while running the script. I used the same code in python 2.7 and it worked fine but in python 3.6 it is giving me error. Could you please help me how to solve this?
Code Which I am using-
class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}, Verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs, Verbose)
        self._return = None
    def run(self):
        if self._Thread__target is not None:
            self._return = self._Thread__target(*self._Thread__args,
                                                **self._Thread__kwargs)
    def join(self):
        Thread.join(self)
        return self._return

May be syntax is different in python 3.6 Please help me to solve this error.
Error:
Traceback (most recent call last):
  File "/app/HTA/Scripts/Python/HTA_Consump_Layer_Procs.py", line 588, in <module>
    main()
  File "/app/HTA/Scripts/Python/HTA_Consump_Layer_Procs.py", line 585, in main
    parallel_Execution()
  File "/app/HTA/Scripts/Python/HTA_Consump_Layer_Procs.py", line 395, in parallel_Execution
    p2 = ThreadWithReturnValue(target = partial(parallel_temp2, unique_exec_seq, df ))
  File "/app/HTA/Scripts/Python/HTA_Consump_Layer_Procs.py", line 365, in __init__
    Thread.__init__(self, group, target, name, args, kwargs, Verbose)
TypeError: __init__() takes from 1 to 6 positional arguments but 7 were given

A: Well, I did a trial of ignoring Verbose in Thread.__init__() Then it works fine to my end. Find my demo code and output. Prior Python<3 used Verbose in Thread but after 3.x+ Verbose is ignored.
from threading import Thread

def foo(bar):
    print('hello {0}'.format(bar))
    return "foo"

class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs)
        self._return = None

    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)

    def join(self, *args):
        Thread.join(self, *args)
        return self._return

twrv = ThreadWithReturnValue(target=foo, args=('world!',))
twrv.start()
print(twrv.join())

# Output
# hello world!
# foo


text:
Q: Python Базы Данных Работаю с большим количеством баз данных на python. Работа заключается в поиске совпадений в той или иной базе. Вопрос: Как можно улучшить, упростить код, который я указал ниже?
import aiosqlite
import asyncio

class DataBase:

    async def __aenter__(self):
        self.db = await aiosqlite.connect('Bases/mybase.db')
        return self

    async def __aexit__(self, *args):
        await self.db.close()

    async def information(self, phonenum: str) -> str:
        cursor = await self.db.execute("SELECT * FROM Users WHERE phonenum == ?", (phonenum,))
        row = await cursor.fetchone()
        return row

async def content():
    async with DataBase() as db:
        cont = await db.information('phonenum')
        return cont

asyncio.run(content())

redpajama_set_name: RedPajamaStackExchange


text:
Q: Array assignment produces NullPointerException I am experiencing problems when assigning a value to an array, which is previously declared like so:
Enemy[] enemies = new Enemy[100];

I also have another variable defining the number of enemies spawned:
int numEnemies = 0;

Later, I (attempt to) dynamically assign members of this array to Enemy objects when the screen is touched:
public void spawnEnemy() {
Enemy enemy = new Enemy(...);
... initialise enemy ...
enemies[numEnemies++] = enemy;  // this line causes NPE
}

I have this stack trace:
01-24 02:00:28.509: E/AndroidRuntime(1394): FATAL EXCEPTION: UpdateThread
01-24 02:00:28.509: E/AndroidRuntime(1394): Process: com.example.menutest, PID: 1394
01-24 02:00:28.509: E/AndroidRuntime(1394): java.lang.NullPointerException
01-24 02:00:28.509: E/AndroidRuntime(1394): at com.example.menutest.GameScene.spawnEnemy(GameScene.java:333)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at com.example.menutest.GameScene.initJoints(GameScene.java:325)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at com.example.menutest.GameScene.loadLevel(GameScene.java:189)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at com.example.menutest.GameScene.createScene(GameScene.java:80)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at com.example.menutest.BaseScene.<init>(BaseScene.java:24)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at com.example.menutest.GameScene.<init>(GameScene.java:32)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at com.example.menutest.SceneManager$1.onTimePassed(SceneManager.java:118)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at org.andengine.engine.handler.timer.TimerHandler.onUpdate(TimerHandler.java:94)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at org.andengine.engine.handler.UpdateHandlerList.onUpdate(UpdateHandlerList.java:47)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at org.andengine.engine.Engine.onUpdateUpdateHandlers(Engine.java:618)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at org.andengine.engine.Engine.onUpdate(Engine.java:605)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at org.andengine.engine.Engine.onTickUpdate(Engine.java:568)
01-24 02:00:28.509: E/AndroidRuntime(1394):     at org.andengine.engine.Engine$UpdateThread.run(Engine.java:858)

EDIT:
My app is written in AndEngine, so the CreateScene() method is called from a SceneManager which I am certain works perfectly.
public class GameScene extends BaseScene {

Enemy enemies[] = new Enemy[100];
int numEnemies = 0;

    public void createScene() {
        ResourcesManager.getInstance().setGameScene(this);
        this.setOnSceneTouchListener((IOnSceneTouchListener) ResourcesManager.mBaseGameActivity);
        createBackground();
        createHUD();
        createPhysicsWorld();
                // the above set up scene for later use
        loadLevel(1);
    }

    public void loadLevel(int levelID) {
        initJoints();
    }

    private void initJoints() {
        mPlanet = new Planet(400, 225, ResourcesManager.getInstance().planet, mVertexBufferObjectManager, 500);
        mPlanet.mBody = PhysicsFactory.createBoxBody(mPhysicsWorld, mPlanet, BodyType.StaticBody, FIXTURE_DEF);
        mPlanet.mBody.setUserData(mPlanet);
        this.attachChild(mPlanet);
        mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPlanet, mPlanet.mBody, true, true));

        float x1 = 200;
        float y1 = 112;
        mSatellite = SatelliteFactory.createSatellite(SatelliteType.BASIC, x1, y1, mVertexBufferObjectManager, mPlanet);
        this.attachChild(mSatellite);

    spawnEnemy(); // causes exception

    }

    private void spawnEnemy() {
        float y = getRandomY();
        float maxHealth = 100;
        Enemy enemy = new Enemy(0, y, ResourcesManager.getInstance().satellite_no_image, ResourcesManager.mVertexBufferObjectManager, maxHealth);
        enemy.mBody = PhysicsFactory.createBoxBody(mPhysicsWorld, enemy, BodyType.DynamicBody, FIXTURE_DEF);

        this.attachChild(enemy);
        enemy.mBody.setLinearVelocity(new Vector2((mPlanet.getX() - enemy.mBody.getPosition().x) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
                (mPlanet.getY() - enemy.mBody.getPosition().y) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT));
        enemy.mBody.setLinearVelocity(new Vector2(mPlanet.getX(), mPlanet.getY() - y));
        mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(enemy, enemy.mBody, true, true));

        enemies[numEnemies++] = enemy; // NPE
    }
}

A: Please add a Log.d() and see what is shown:
Log.d("~~~","\n\n\n\n~~~ enemies="+enemies+"  enemy="+enemy);
enemies[numEnemies++] = enemy;  // this line causes NPE

I suspect this is because of the order of initialization, the function definitely is invoked from a constructor or initializer.
Note also the following in the log:
at com.example.menutest.GameScene.initJoints(GameScene.java:325)
at com.example.menutest.GameScene.loadLevel(GameScene.java:189)
at com.example.menutest.GameScene.createScene(GameScene.java:80)
at com.example.menutest.BaseScene.<init>(BaseScene.java:24)
at com.example.menutest.GameScene.<init>(GameScene.java:32)

the GameScene constructor calls the BaseScene constructor which in turn calls GameScene methods -- before the GameScene instance creation is finished.
In addition, you write: I (attempt to) dynamically assign members of this array to Enemy objects when the screen is touched but I see that the code is launched upon a timeout:
at com.example.menutest.SceneManager$1.onTimePassed(SceneManager.java:118)

A: Ok, try this: just before the line where you get the NPE, add
if (enemy == null) System.out.println("enemy is null");
if (numEntries == null) System.out.println("numEntries is null");
if (enemies == null) System.out.println("enemies is null");
enemies[numEnemies++] = enemy; // NPE

Does that give you any useful information?

A: I'll explain what happens:
How do I call an instance method before calling the instance constructor?
class B {
  B() {
    m();
  }
  void m() {
    System.out.println("B.m()");
  }
}
class X extends B {
  int x = 8;
  void m() {
    System.out.println("X.m() x="+x);
  }
}

public class A {
    public static void main(String[] p) {
        X x = new X();
        x.m();
    }
}

Let's run it:
$ javac A.java

$ java A
X.m() x=0
X.m() x=8

This kind of misbehavior is not possible in C++ where B.m() rather than X.m() would be called from within the base class constructor.
The constructor B() is called automatically before executing any code from the constructor X(), and so the method X.m() is called before any code within the constructor X() receives control.


text:
Q: Mocking in Swift How do you mock an object in Swift?
The Mirror protocol sounded promising, but it doesn't do much right now.
So far the only approach I found is to subclass and override all methods of the mocked class. This is of course not a true mock, far from ideal, and a lot of work.
Any other ideas?
Why not OCMock?
From the source:

Can I use OCMock using the language bridge functionality?
Yes, but
with limitations. If you are brave. As of now this is highly
experimental. There's no guarantee that OCMock will ever fully support
Swift.

Known limitations:

*

*Tests have to be written in Objective-C

*Objects that should be mocked must inherit from NSObject

*No stubbing/expecting/verifying of class methods

A: NSHipster touches on language features in Swift which make an external mocking library less necessary:

In Swift, classes can be declared within the definition of a function, allowing for mock objects to be extremely self-contained. Just declare a mock inner-class, override and [sic] necessary methods:

func testFetchRequestWithMockedManagedObjectContext() {
    class MockNSManagedObjectContext: NSManagedObjectContext {
        override func executeFetchRequest(request: NSFetchRequest!, error: AutoreleasingUnsafePointer<NSError?>) -> [AnyObject]! {
            return [["name": "Johnny Appleseed", "email": "johnny@apple.com"]]
        }
    }

    ...
}

The ability to create a subclass of your external dependency in the local scope plus the addition of XCTestExpectation solve a lot of the same problems as OCMock.
The one thing that a library such as OCMock provides that is very useful are its "verify" methods to ensure that the mock classes were called.  It's possible to manually add this, but the automatic addition is nice.

A: I want to point something in addition to marked answer - I do not know whether it's a bug or not.
If you subclass NSObject somehow(in my case I was subclassing UIView which internally subclass NSObject) you need to declare overriden function explicity with @objc otherwise your test wont compile. In my case the compiler itself crashes with following:

Segmentation Fault: 11

So the following class:
public class ClassA: UIView
{
    @objc public func johnAppleseed() {

    }
}

Should be unit tested the following way:
class ClassATests: XCTestCase {

    func testExample()
    {
        class ClassAChildren: ClassA
        {
            @objc private override func johnAppleseed() {

            }
        }
    }
}

A: I create my mock classes by wrapping everything in a protocol. I hand roll a mock class to conform to the protocol in question, like so:
protocol Dog: class {
    var name: String { get }

    func bark()
}

class DogImpl: Dog {
    var name: String

    init(name: String) {
        self.name = name
    }

    func bark() {
        print("Bark!")
    }
}

class DogMock: Dog {
    var name = "Mock Dog"
    var didBark = false

    func bark() {
        didBark = true
    }
}

I use this in conjunction with dependency injection to achieve full test coverage. It's a lot of boilerplate, but I haven't had any issues with this approach so far.
Regarding subclass mocking, you'll run into trouble with final classes, or if they have non-trivial initializers.

A: You can achieve this kind of mocking with MockFive.
The gist of it is that you have to create a mock 'by hand' of the source class that you want to mock--
but then, you can stub its methods dynamically, so you can use it wherever you need and configure its behavior there.
I wrote an article about how to use it here.

A: I recommend using Cuckoo, which can handle most standard mocking tasks.
Example Classes:
class ExampleObject {

    var number: Int = 0

    func evaluate(number: Int) -> Bool {
        return self.number == number
    }

}

class ExampleChecker {

    func check(object: ExampleObject) -> Bool {
        return object.evaluate(5)
    }

}

Example Test:
@testable import App
import Cuckoo
import XCTest

class ExampleCheckerTests: XCTestCase {

    func testCheck() {
        // 1. Arrange
        let object = MockExampleObject().spy(on: ExampleObject())
        stub(object) { object in
            when(object.evaluate(any())).thenDoNothing()
        }
        let checker = ExampleChecker()

        // 2. Action
        checker.check(object)

        // 3. Assert
        _ = verify(object).number.get
        verify(object).evaluate(any())
        verifyNoMoreInteractions(object)
    }

}

A: Because of the limitations you wrote, OCMock does not work very well in Swift (as every mocking framework strongly dependent on the runtime).
There are several mocking frameworks for Swift though, from semi-manual to almost fully automatic mock generation. Some of them are already listed in the answers, so I'll just recommend another one, which I'm one of authors.
https://github.com/MakeAWishFoundation/SwiftyMocky
I won't go much into details, it has its minor limitations, but from what I see it has widest set of features from Swift frameworks (at least the ones I know), including generics support, @objc members, and updating mocks while you write/change protocols (watcher mode).


text:
Q: Add two array elements using loop I am trying a task with arrays: add two elements and check if the sum is less than or equal to 50. If the condition is satisfied, it should break.
Example program:
public class HelloWorld {

     public static void main(String []args)
     {
         int[] nums = new int[2];

         for (int i = 0; i < 100; i++)
         {
             nums[i] = i + 1;
             System.out.println(i);
         }
         System.out.println(nums[1]);
         System.out.println(nums[2]);

         if  (nums[0]+nums[1]<=50)
         {
             System.out.printf("Sucessfully finished");
         }
     }
}

Of course, my program is not working. I want i value to store in the two elements
nums[0] = 1 and nums[1] = 2. I also want to add these two elements and check if the sum is less than or equal to 50. I have allocated two elements in the array which means nums want to add and check the current two elements of i and clear and adds next two elements and check if its less than or equal to 50.
nums[0]=1;
nums[1]=2; check <=50 . fails clear the the array elements and store next i value
nums[0]=3;
nums[1]=4; check <=50 . fails clear the the array elements and store next i value
...
nums[0]=25;
nums[1]=26; check <=50 .

A: There are a lot of ways to do this but here is a nifty trick that solves exactly this kind of problem.
int[] nums = new int[2];

for (int i = 0; i < 100; i++) {
    nums[i % nums.length] = i + 1;

    if (nums[0] + nums[1] <= 50) {
        System.out.println("sum is less than or equal to 50");
        break;
    }
}

What the mod operator (%) does is calculate the remainder of i based on the array's length. This ensures that i goes from 0 to 99 but the array index always "resets" and stays within the range of the array. For example after i == 0 and i == 1, i will be incremented to out of bounds at i == 2 but 2 % 2 == 0. When i == 3, 3 % 2 == 1 and so on.
But as a side note, the condition you've described ("if the sum is less than or equal to 50...it should break") will be satisfied immediately (sums 1 at nums[0] and 0 at nums[1]) and the loop will not execute past the first iteration (i == 0). I'm not sure that's what you are wanting. Do you mean "not less than or equal to 50"?
int[] nums = new int[2];

for (int i = 0; i < 100; i++) {
    nums[i % nums.length] = i + 1;

    if (nums[0] + nums[1] > 50) {
        System.out.println("sum was NOT less than or equal to 50");
        break;
    }
}

As an alternate solution finding this result can be very much shortened to the following while loop:
int i = 0;

// note sum of two consecutive integers will never be even (never 50)
while (i + ++i < 50);

System.out.println("min increments with sum > 50 was " + (i - 1) + " and " + i);

The output is min increments with sum > 50 was 25 and 26.

A: I believe, you need 1 more for loop, to go about checking each  num[i] + num[i+1].  You can do it in a single for loop as well, but kept the code as simple as possible for your clarity.(As you are new to java programming ;))
public class HelloWorld{

public static void main(String[] args) {
    int[] nums = new int[100];

    for (int i = 0; i < 100; i++) {
        nums[i] = i + 1;
        System.out.println(i);
    }

    for (int i = 0; i < 99; i++) {
        System.out.println(nums[i]);
        System.out.println(nums[i+1]);

        if (nums[i] + nums[i+1] == 50) {
            System.out.printf("Successfully finished");
        }
    }
}
}

A: I'm not sure if this is what you meant. Have a try.
public static void main(String[]    args) {
    int[] nums = new int[100];
    nums[0] =1;
    for (int i = 1; i < 100; i++) {
        nums[i] = i + 1;
        if ((nums[i] +nums[i-1]) >= 50) {
             System.out.printf("Successfully finished");
        }
    }
  }

A: I'm not entirely sure on what your end goal is. If you just want to add two numbers (i, and i+1) and see if they are less than 50 then you can use this.
for (int i =0; i < 100; i++) {
    int j = i+1;
    int total = i+j;
    if((i+(i+1)) < 50) {
        System.out.println("Numbers '" + i + "' and '" + j + "' equal '" + total + "'.");
    }
}

This will print out all the pairs of numbers that add to less than 50 along with what they add to.
I accept that you're probably wanting something more. :)


text:
Q: SOAP-ERROR: Parsing WSDL: Couldn't load from (PHP 5.6 Certificate checking) I have been fighting the following error for longer than I would like to admit. The solutions I was finding were not related to what the actual problem was.
PHP Fatal error:  SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://x.x.x.x/iControl/iControlPortal.cgi?WSDL=LocalLB.Class' : failed to load external entity "https://x.x.x.x/iControl/iControlPortal.cgi?WSDL=LocalLB.Class"
My prod environment is CentOS 6 which is packaged with PHP 5.3 which has been EOL since August 2014. From my understanding CentOS backports security fixes, I still wanted to do some testing with a newer version and there was some other features not available in 5.3 that I could possibly leverage.
I built out a new DEV environment with PHP 5.6 and all seemed to be working until I tried a SOAP call and got the message above. After a lot of searching I finally found that in PHP 5.6 SSL Certificate check is enabled by default. In my DEV environment it is completely contained and the application requires SSL. I do not have a valid certificate. I have not tested in my PROD environment which does have valid certificates.
To get around this I added:
'stream_context'=>stream_context_create
(
    array
    (
        'ssl'=>array
        (
            'verify_peer'=>false,
            'verify_peer_name'=>false
        )
    )
)

Here it is put together in the code. This is kind of messy just threw it together for testing.
<?php

$device_ip = "x.x.x.x";
$user = "username";
$pw = "password";

$location = "https://" . $device_ip . "/iControl/iControlPortal.cgi?";
$wsdl_class = "https://" . $device_ip . "/iControl/iControlPortal.cgi?WSDL=LocalLB.Class";
$soap_class = new SoapClient($wsdl_class, array('location'=>$location, 'login'=>$user, 'password'=>$pw, 'stream_context'=>stream_context_create(array('ssl'=>array('verify_peer'=>false, 'verify_peer_name'=>false)))));

$response = $soap_class->get_string_class(array("SomeName"));
var_dump($response);

?>

although I was able to find a workaround for not having a valid certificate. Is there a way to import the self-signed certificate so that I would not have use the workaround in my DEV environment?


text:
Q: How do you get Dog Fight medals? I'm working on unlocking the various camos and one of the challenges is to get 50 Dog Fight medals. How are these earned?

A: Killing someone while both of you are in the air. Use the hover exo ability to make it easier

A: To get the Dog Fight medal, you simply have to be in the air during the kill as well.

A: Basically exo jumping into the air as you would to get a strafe medal only this time your enemy has to be in the air too. Kill them then at the top of your screen will appear the strafe medal. GOOD LUCK!


text:
Q: Issues with migration AzureRm to Az Currently, I am working on refactoring code to move from AzureRM to Az module, but I have been blocked for some time on one strange thing.
I have already changed all the commands to Az module and everything works smoothly locally.
But the issue starts when I try to run this powershell script from Azure DevOps
I've attached a small part of the code, which is the main problem point of my code. From Azure, DevOps code runs successfully, but it doesn't perform the action from this script block. It's quite important to run it as a background job ( asynchronously ) but Az module somehow is causing issues ( or maybe something else ).
Previously ( with AzureRM module )the same part of code worked like a charm.
I have the same Az module and PowerShell versions on both, local pc and Azure DevOps agents.
Any ideas why script block is not performing any actions?
Any help appreciated!
Cheers!
Start-Job -ScriptBlock {
    param($resourceGroupName, $deployment)
    Remove-AzResourceGroupDeployment -ResourceGroupName $resourceGroup -Name $deployment.DeploymentName
} -ArgumentList @($resourceGroup, $deployment) | Out-Null

A: One point to note is that you need to select the 4.*(preview) version for Azure PowerShell task which support Az Module.
For now Az module is only support with v4 of the Azure Powershell task.
Since Azure PowerShell – Cross-platform "Az" module replacing "AzureRM" is a trend.
You could also find the open source source code for V4 Azure Powershell task in GitHub: https://github.com/microsoft/azure-pipelines-tasks/tree/master/Tasks/AzurePowerShellV4

A: It's something to do with your arguments I think. There's a mismatch with arg, parameter and variable usage in the command between $resourceGroupName and $resourceGroup
By the looks of your usage it seems that $resourceGroup is a string and $deployment is an array. If that's the case then your args  should be -ArgumentList @($deployment),$resourceGroup
Full snippet

Start-Job -ScriptBlock { param($deployment, $resourceGroup) Remove-AzResourceGroupDeployment -ResourceGroupName $resourceGroup -Name $deployment.DeploymentName
} -ArgumentList @($deployment),$resourceGroup | Out-Null

The amount of info provided isn't great though. I'd just try running the Remove-AzResourceGroupDeployment command without the job as an initial test. This will tell you if it's the Az module or or your job. Also, I've had problems with modules loading on hosted agents in the past so try install-module Az.Resources -force -allowclobber.


text: Q: Are there any file managers out there for Angular4? I'm looking for a file manager that I can use in my Angular4 App (this is a work related question). While browsing I could only find AngularJS file managers. Do they not yet exist for Angular4 or is there another way to solve my problem?


text:
Q: VSCode extension developmet: convert x, y coordinates on the screen to line, column number in the file I'm now trying to develop a VSCode extension, which aims to convert x, y coordinates of the screen data to line, column number of code file. But I cannot even get the size and location of text editor.
Visual Studio and Eclipse has interface like Microsoft.VisualStudio.Text.Editor.ITextView or org.eclipse.swt.custom.StyledText to complete the task, but I haven't found similar interface in VSCode.
The TextEditor and TextDocument class in VSCode Extension API have some attributes like visibleRanges or lineAt but they only measure position with line, character number. I can't find the function connecting between screen pixels with them.


text:
Q: MVC3 - Coding a custom HTML Helper which output works with unobtrusive Javascript I am attempting to add unobtrusive JavaScript to a file upload input control, using a custom HTML Helper extension. However, I have checked various blogs which use different methods to create the control, such as tab-builder but I couldn't find out how the unobtrusive data tags are added.

A: Unobtrusive data tags mainly means using the HTML 5 extensible "data-" attribute.
Check this blog post of Brad Wilson about unobtrusive javascript in MVC 3, he describes the various attributes used by the unobtrusive framework.

A: If you are using TagBuilder, you can do this:
var validationAttributes = html.GetUnobtrusiveValidationAttributes(name, metadata);

then use MergeAttributes on your tagbuilder to add the unobtrusive validation attributes to your tag.


text:
Q: Who is the first robot that is still in working form in Futurama? Who was the first robot that still exists in working form?  Ignoring robots for whom:

*

*No Date Of Manufacture was mentioned or implied (by existing at a particular early time).

*Got to where they are by time travel.

A: I had thought vaguely that "Crimes of the Hot" had stated robots were invented by
Professor Farnsworth, but I just watched the episode again and he actually says..

 I know the source of the greenhouse gases, but in my shame I've kept it secret for 75 long years .. Back then you see, robots were slow moving, stiff, and a little on the uptight side. .. All modern robots descend from my original smog blasting designs.

(That is the last 'spoiler warning' I am including - the rest is basically spoilers..)
Note that Bender is provably older than most robots.  Not only did he get sent back
to 1945 in "All's well that Roswell", but also acted as the stooge for the scammers
that activated the time code so he could travel back in time repeatedly to steal things
for them.  He must be eons old.  And that is not to consider the times he, Fry and the
Professor traveled through a few different iterations of the universe, especially since
that took only hours in their own 'local' time frame.
But noting the 2nd criterion, he is disqualified.
So let's list some of the potentials.

*

*2801/2802 - Santa Claws was made by Mom's Friendly Robot Company.  Mentioned in
"Xmas Story".

*ca. 2200 - Kwanzaa Bot complains in "A Tale of Two Santas" that he has been distributing the 'What the hell is Kwanzaa?' pamphlet for 800 years.

*2008 - Calculon was working as a robot arm.  Mentioned in "The Honking".  He was turned into a Werecar by project Satan, but not only did he exist before Project Satan was finished and activated, he also outlasted it.

*ca. 2008 - And that brings me to the Robot Devil.  In one episode he asks for Calculon's ears, Calculon complies on the basis that the Robot Devil gave him his acting ability.  In
"The Honking", Calculon mentions he was all of histories great acting units - Thespomat, David Duchovny ..  Given the reference to Duchovny, that implies he is also relatively old, though I don't think that any time of origin has ever been put forward for him.

*? - Robot God?  Same problem as the Robot Devil - no date of manufacture mentioned.

*1495 - 1498: Then we come to Animatronio, who apparently predates Leonardo da Vinci's
painting of The Last Supper, in which he (or at least part of him) appears.

Animatronio is the earliest made, currently existing robot I can immediately track down.
Did I miss an even earlier one?


text:
Q: Is there any way to make a method check if there is existing unique data in database? My goal is to create a method in android studio that checks if there is an existing username (which is unique) in my database. But my problem is, I have no idea why my implemented code does not work and returns an error in logcat. The app does not crash however.
In fact, I have tried implementing 2 different methods. The first one is to put all selected existing usernames from the database into an arraylist and use the ArrayList.contains(username) method to see if the arraylist contains the similar username.
The other method I have tried using is to select a username in the database that is the same as my inputted username and see if they are the same. (Might sound confusing but I will show you the code).
MainActivity.java
DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 1);

UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

            if (mydb.existingUsername(tvUsername.getText().toString()) == false) {
                mydb.insertTable(userInfo);
                Intent intent = new Intent(MainActivity.this, Lobby.class);
                intent.putExtra("username", userInfo.getUsername());
                startActivity(intent);
            } else {
                // some code
            }

DatabaseHelper.java
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + "(" +
            COLUMN_ID + " integer primary key autoincrement, " +
            COLUMN_USERNAME + " text not null unique, " +
            COLUMN_PASSWORD + " text)");
}

// Method 1 (Commented out)
public ArrayList<UserInfo> existingUsername() {
    UserInfo userInfo;
    ArrayList<UserInfo> userArray = new ArrayList<UserInfo>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        userInfo = new UserInfo(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
        userArray.add(userInfo);
        cursor.moveToNext();
    }
    return userArray;
}

// Method 2 (Currently in use)
public boolean existingUsername(String username) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME + " WHERE " + COLUMN_USERNAME + " = ?", new String[]{username});
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        if (cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username) {
            return true;
        } else {
            cursor.moveToNext();
        }
    }
    return false;
}

Expected results:
I want it to check if the "username" I put already exists in the database or not. If no, run the "if" statement and go to the next activity. If yes, run the "else" statement.
Actual results:
However, it turns out the code keeps running the "if" statement and goes the next activity whether the inputted username already exists in the database or not. If the inputted username already exists in the database, it gives me this error in the logcat.
Logcat
019-06-01 14:06:19.774 27199-27199/com.karimun.myapplication E/SQLiteDatabase: Error inserting password=232323 username=Igor
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: users.username (code 2067 SQLITE_CONSTRAINT_UNIQUE)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
    at com.karimun.myapplication.DatabaseHelper.insertTable(DatabaseHelper.java:70)
    at com.karimun.myapplication.MainActivity$2.onClick(MainActivity.java:58)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

A: You have a wrong comparison
cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username

This cause your program continue inserting even when the username already exists.
Change to equals() for correct string comparison. Do not use == to compare String (and objects generally)
username.equals(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)))

if username is not null
or
Objects.equals(username, cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)))

A: You should let SQL do all of the work for you:
Select count(*) from sometable where username = @username

This will return the number of records that contain @username. If the number is 0, then the username does not exist in the table. If it's 1, then the username exists and is unique. If it's greater than 1, then the username exists and is not unique.

A: You don't show your insertTable(userInfo) method but if you use (assuming you are using the execSQL method to insert) then using INSERT OR IGNORE instead of INSERT then the duplicate will be ignored.
However, if instead you use the insert method (this effectively uses INSERT OR IGNORE). It returns the rowid, as a long, of the inserted row, if the row wasn't inserted then it returns -1. So checking the return value will tell you that for some reason (likely a duplicate) that the row wasn't inserted (so negates the need for a pre-check and the associated overheads).

*

*As you have defined the ID columns using integer primary key autoincrement, this column is an alias of the rowid column (so the value of rowid will be the same as the ID column).

The following is the code as it could perhaps be, based upon what can be gleaned from the available code.
public long insertTable(UserInfo userInfo) {

    ContentValues cv = new ContentValues();
    SQliteDatabase db = this.getWritableDatabase();
    cv.put(COLUMN_USERNAME,userInfo.getUserName());
    cv.put(COLUMN_PASSWORD,userInfo.getPassword());
    return db.insert(TABLE_NAME,null,cv);
}

*

*Note as this has the same name and signature this would have to replace your existing method or be named differently.

*Note getPassword may be the wrong method used to get the password value from the UserInfo

The code in MainActivity.java could then be :-
        UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

        long id;
        if (id = mydb.insertTable(userInfo) > 0) {
            Intent intent = new Intent(MainActivity.this, Lobby.class);
            intent.putExtra("username", userInfo.getUsername());
            intent.putExtra("userid",id); //<<<<<<<<<< you now have the id
            startActivity(intent);
        } else {
            // some code because user was not added
        }

*

*Note the above is in-principle code and may contain some errors as it hasn;t been tested or run.


text:
Q: Converse to Sard's theorem Combining the inverse function theorem and sard's theorem we arrive at:

$f: \mathbb{R}^n \to \mathbb{R}^n$ is smooth and locally injective $\implies$ f is a local
  diffeomorphism almost everywhere

Does a converse to this exist? In other words:
Let $f: \mathbb{R}^n \to \mathbb{R}^n$ be a continuous locally injective map which is a local diffeomorphism almost everywhere.
Must $f$ be smooth?

A: No, take for example $f(x)=x|x|$. Then $f$ is locally a diffeomorphism everywhere except at $x=0$, but not smooth.


text:
Q: Undefined first referenced symbol in file (ld: fatal: symbol referencing errors) I have these 3 functions Which I converted it into templatized version to make it more generic.
#ifndef __CPPMARSH_H__
#define __CPPMARSH_H__

template<typename listT>
void cppListFromWire(void *&src,listT &dest, factorywv);
void cppListToWire(listT &src, void *&dest);
long cppListToWireSize(listT &list);

Defined in a different folder (not as in where I declared) as below,
template<typename listT>
void cppListToWire(listT &list, void *&dest)
{
        int nItems = (int) list.entries();
        cppIntToWire(&nItems, dest);
        //RWSlistIterator next(list);
        RWTValSlist<void *> next(list);
        while (next())
                ((AISObject*)next.key())->toWire(dest, 0);
}

But facing the below issue.Here RWTValSlist is a sourcePro library function,
Undefined                       first referenced
 symbol                             in file
void cppListToWire<RWTValSlist<CSSCODERec*, std::allocator<CSSCODERec*> > >(RWTValSlist<CSSCODERec*, std::allocator<CSSCODERec*> >&, void*&) /app/sdasup/home/mhp/source/develop/sd/lib/libsdHostSupport.so
long cppListToWireSize<RWTValSlist<CSSCODERec*, std::allocator<CSSCODERec*> > >(RWTValSlist<CSSCODERec*, std::allocator<CSSCODERec*> >&) /app/sdasup/home/mhp/source/develop/sd/lib/libsdHostSupport.so
void cppListFromWire<RWTValSlist<CSSCODERec*, std::allocator<CSSCODERec*> > >(void*&, RWTValSlist<CSSCODERec*, std::allocator<CSSCODERec*> >&, AISObject* (*)()) /app/sdasup/home/mhp/source/develop/sd/lib/libsdHostSupport.so
ld: fatal: symbol referencing errors

These are the different methods I tried to resolve but in vain,

*

*Tried prototyping the function

*Tried including the flags under makefile ROGUEFLAGS=-lsdHostSupport
ROGUELIBS=lsdHostSupport

*export LD_LIBRARY_PATH=/opt/RogueWave/SourcePro/2021/rw/ For this method though it clears the errors but throws the following eror,
3a. ld.so.1: buildserver: fatal: libtux.so.71: open failed: No such file or directory ----To mitigate this one I tried " ldd /opt/tuxedo/tuxedo12.2.2.0.0/lib/libtux.so.71"  which didn't work.
Any help amounts to great appreciation.


text:
Q: How to pass a path of image as a prop in Gatsby in Gatsby-plugin-image I am trying to pass a path of an image as a prop to a component
Note: Both the component and the index page can access the image through the same path. It is not working when i pass the path as a prop
In the below code i have tried with both GatbsyImage and StaticImage tag both seems to fail
index.js
import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../styles/index.scss';
import Main from  '../Layouts/main';
import ImageOverlay from '../components/ImageOverlay';
import { StaticImage } from "gatsby-plugin-image"

function Home(){
  // Home page images
  return (

      <ImageOverlay path="../images/home/places/portblair.png"> </ImageOverlay>

  )
}

export default Home

components/ImageOverlay.js
import React from 'react';
import { GatsbyImage, StaticImage } from "gatsby-plugin-image"
const ImageOverlay = ({path}) =>{
    return(

          <GatsbyImage image={path}></GatsbyImage>
          <StaticImage src={path}></StaticImage>

    )
}
export default ImageOverlay;

I used GatsbyImage and StaticImage just incase to check
Thanks for the help in advance

A: You can't use outer props on StaticImage, it's a known restriction:

Restrictions on using StaticImage
There are a few technical restrictions to the way you can pass props
into StaticImage. Most importantly, you can't use any of the parent
component's props. For more information, refer to the Gatsby Image
plugin reference guide. If you find yourself wishing you could use a
prop passed from a parent for the image src then it's likely that you
should be using a dynamic image.

And extending the referenced guide:

// ⚠ Doesn't work
export function Logo({ logo }) {
  // You can't use a prop passed into the parent component
  return <StaticImage src={logo}>
}

The solution, if you want to use StaticImage is to use the static approach, appending the src directly:
import React from 'react';
import { GatsbyImage, StaticImage } from "gatsby-plugin-image"
const ImageOverlay = ({path}) =>{
    return(

          <StaticImage src={`../images/home/places/portblair.png`}></StaticImage>

    )
}
export default ImageOverlay;

If you want to use GatsbyImage, you will need to query your image to get the proper data:
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

function Home({ data }) {
 const image = getImage(data.blogPost.avatar)
 return (

     <GatsbyImage image={image} alt={data.blogPost.author} />

{data.blogPost.body}

 )
}

export const pageQuery = graphql`
 query {
   blogPost(id: { eq: $Id }) {
     title
     body
     author
     avatar {
       childImageSharp {
         gatsbyImageData(
           width: 200
           placeholder: BLURRED
           formats: [AUTO, WEBP, AVIF]
         )
       }
     }
   }
 }
`

Note: of course, adapt the snippet to your needs but get the idea
If you want to use a dynamic image, you are forced to make a GraphQL query to allow Gatsby and their transformers to parse and resolve the image. You can use the bunch of available filters to create a specific query for your image using as well as the relativePath and the absolutePath, test the query at localhost:8000/___graphql.


text:
Q: Will I ever have to uninstall windows 8? If I've installed the consumer preview and would like to keep Windows 8 as my main operating system, will I ever have to uninstall it or purchase it in the future?

A: In short, yes. According to this site: "Previous beta versions of Windows 8, like the Developer Preview or Consumer Preview, can not be upgraded" to the full version.


text:
Q: With nginx proxy/rewrite can I keep the original URL in the browser's Location field? Using nginx.conf features like proxy-pass/rewrite, can I keep the original URL in the browser's Location field?
I have several PlayFramework apps running on different ports (9001, 9002, ...) with proxy forwarding set up via nginx.conf.  People browse to them as:

*

*http://domain.name/App1/

*http://domain.name/App2/

*etc.

My nginx.conf entries look like this:
location /App1/ {
    proxy_pass http://localhost:9001/;
    rewrite ^/App1/(.*) http://domain.name:9001/$1;
}

If I ask for http://domain.name/App1/, what I see in the browser's Location field is http://domain.name:9001.  What I wish I saw was http://domain.name/App1/, that is, I want the name App1 to remain in the URI, and I'd rather not expose the port number.
Let's say App1 has a link /location/ABC.  When I click on it I see http://domain.name:9001/location/ABC when I wish I saw http://domain.name/App1/location/ABC.
Can I achieve this with nginx.conf?
P.S.  I put http://domain.name explicitly in the rewrite rule because without it I was getting localhost in the browser, and my browser's localhost is not the same as the server's.

A: Rewrites issue redirects for browser.
If you just want to mount several locations from upstreams - you do not need rewrites, just use:
location /App1/ {
    proxy_pass http://localhost:9001/;
}

But apps should use relative links or account for their absolute location.
For more complex url manipulation you can use break-rewrites:
location /App1/ {
    rewrite ^/App1/(.*) /$1 break;
    proxy_pass http://localhost:9001;
}


text:
Q: Adding year dummy to a fixed-effect model for  panel-data Working with a panel dataset (n=50 units, t=20 years at the monthly level = 240), I am fitting a fixed-effects model while controlling for the seasonality by monthly dummy variables. I defined the panel data by unit (1:50) and the time as a year-month (1:240). Here is how I did that in r's plm package.
paneldata <- pdata.frame(data, c("unit", "year_month_serial"))
fe_model <- plm(y ~ x1+x2+x3+factor(month)
          , data= paneldata
          , model="within"
          , effect="individual")

My understanding is this model controls for the unit level as a fixed-effect and seasonality (by monthly dummies) without explicitly taking into account the year (time) effects. My question: is it appropriate to add a year variable factor(year) to the model to capture the time effects? What statistical tests that can be run to verify?
Similarly (or maybe not), if the units are companies, for instances, and they are categorized in 4 industries (which are believed to have an effect on the dependent variable due to different policies or characteristics), What is an appropriate to control for the industry level (given that the industry level is time-invariant and cannot be used as a dummy indicator in the model)?


text:
Q: Android - How to get sensor details based on sensor name? I'm writing a simple application as an exercise - display a list of all sensors on the device as a ListView, and display current sensor values/details in a new activity when clicking on each sensor name in the ListView.
I have the ListView working correctly, and can pass the sensor name to the new activity so far. Is there a way to get the sensor details using this passed name? It seems like I cannot use putExtra() to pass the sensor itself to the new activity. Or is there another approach to this?
SensorList activity:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_sensor_activity);

    sensorListView = (ListView) findViewById(R.id.sensorlist);
    sensorListView.setOnItemClickListener((AdapterView.OnItemClickListener) this); //allows each item in ListView to be clickable

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL); //get list of sensors
    ArrayList<String> sensorNames =  new ArrayList<String>(); //list of sensor names

    //iterate through list of sensors, get name of each and append to list of names
    for(int i=0; i< sensorList.size(); i++) {
        String sensor= sensorList.get(i).getName();
        if(sensor == null || sensor.equals(""))
            continue;
        sensorNames.add(sensor);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, sensorNames);
    sensorListView.setAdapter(adapter); //populate ListView with sensor names
}

@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id ) {
    Intent sensorDetails = new Intent(ListSensorActivity.this, SensorDetailActivity.class);
    sensorDetails.putExtra("SENSOR_NAME", sensorList.get(position).getName()); //pass sensor name to detail activity
    startActivity(sensorDetails);
}

** SensorDetail activity **
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sensor_detail);

        sensorTitle = (TextView) findViewById(R.id.sensortitle);

        manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);

        Bundle extras = getIntent().getExtras();
        sensorName = extras.getString("SENSOR_NAME");
        sensorTitle.setText(sensorName);
    }

A: Pass the type from the sensor to the second activity, then request the sensor in the activity via SensorManager.getDefaultSensor(type)

A: Please check this:
 private  SensorManager mSensorManager;
 private  Sensor sensorNames;

and in Class
 mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
 sensorNames= mSensorManager.getDefaultSensor(Sensor.TYPE_ALL);

and for passing the value from list as per position:
  Intent intent= new Intent(this, SensorDetailActivity.class);
  intent.putExtra("SENSOR_NAME", sensorNames.get(position).toString());
  startActivity(intent);

Let me know if still you are not getting solution.. :)


text:
Q: Put something on top of the stagewebview with flash builder 4.6 I'm using stagewebview > Flash Builder 4.6
I have a stagewebview and I load an url in it. I want to show sometimes a slide panel on top of the stagewebview.  I tried it, but the panel is always behind the stagewebview. I know that stagewebview isn't a display object, but does anyone know if there is any way I can do it?
Thanks in advance

A: I think I have the answer, it's a little trickery but I think it's the only way
You need to take a picture of the stagewebview, add the picture to the stage, hide the real stagewebview and THEN you can add something over the top of the pic.
Thanks


text:
Q: (Source Insight) How to hide references of function definition in Relation Window? I am using "Relation Window" view in Source Insight and want to know how to hide references of function when it's just a function definition(usually in header files) as it's useless.

A: Right click on Relation pane and then "Relation Window Properties"

Select Referenced by Functions


text:
Q: Merging multiple dataframes and summing values I have multiple dataframes, all having the same shape but with different values. I need to merge the dataframes into one and add the values in the A, B, and C columns. Below is an example:
df1:
**Name,A,B,C**
Fred, 3, 4, 5
Tim, 1, 3, 0
Jake,4,2,10

df2:
**Name,A,B,C**
Fred, 1,0,4
Tim, 7,1,2
Jake,3,3,1

What I'm looking for is such:
df_merged:
**Name,A,B,C**
Fred,4,4,9
Tim,8,4,2
Jake,7,5,11

Keep in mind that I have multiple dataframes that need merged into 1 (6+).

A: Use concat with aggregate sum by GroupBy.sum:
dfs = [df1, df2, df3, ...]
df = pd.concat(dfs).groupby('Name', as_index=False).sum()

dfs = [df1, df2]
df = pd.concat(dfs).groupby('Name', as_index=False).sum()
print (df)
   Name  A  B   C
0  Fred  4  4   9
1  Jake  7  5  11
2   Tim  8  4   2


text:
Q: Automatically add tags Using MS Word documents as our source files, is there a way to include special token characters or MS Word fields inside an uploaded document so that Dousing can read the special tokens or field  and replace them with the appropriate tags and signatory data?
This would allow me to adjust our document creation software to insert tokens where we needed tags, along with hidden filed that contained recipient data, and then our users could just click a button to get the contract, upload it to DS and have all the fields and tags populate properly.
Tell me you can do this!

A: Yes, DocuSign can automatically place DocuSign tabs in documents using "anchor text" that exists in the documents.  The "Anchoring tabs" section of the REST API guide (starting on p 292) -- http://www.docusign.com/sites/default/files/REST_API_Guide_v2.pdf -- provides information about how you can achieve this when creating an Envelope with the REST API.
Using "anchor text" with tabs enables you to have DocuSign automatically add/place the tabs in the documents in each place where the text string you specify (i.e., the "anchor text" string) exists in the document.  For example, if your documents contained the string ~s1 in each location where the first signer's signature was required, the REST API request you use to create the envelope would include the following tabs information to have DocuSign automatically add a Signature tab for the signer in each location where ~s1 appears in the documents:
"tabs": {
  "signHereTabs": [
    {
    "anchorString": "~s1",
    "anchorXOffset": "1",
    "anchorYOffset": "0.5",
    "anchorIgnoreIfNotPresent": "false",
    "anchorUnits": "inches"
    }
  ]
}

Note: The only property absolutely required to use anchor text for tab placement is anchorString -- I've included some additional properties in the sample above that you may or may not want to utilize.  See the REST API guide for information about the meaning/purpose of the other properties included in the sample above.

A: Yes you can do this with DocuSign, as long as you insert these tokens into the document content itself, once the document is uploaded the DocuSign platform will scan through the content and insert any anchor tags where applicable.
For instance, if you have an invisible string in your Word document that is \s1 and you have a Custom Tag saved in your DocuSign account that has \s1 set for its anchor string then signature tabs (or whatever type of tab you'd like) will be inserted wherever \s1 is found in the document.  Or if you don't want to save anchor tags at the account level (which means they are applied on all of your envelopes) you can anchor your tabs through api call(s) so that they are only applied to that envelope.
For more information please see the Tab Positioning section under Explore -> Features in the DocuSign Dev Center:
http://www.docusign.com/developer-center/explore/features/stick-etabs
You'll see that one common approach is to set the font color of these special tokens to the same color as the document background (usually white) which in turn makes them invisible so that you only see the DocuSign tabs at those locations.


text:
Q: Connecting Druid with MySQL I finish setting up Druid on my computer by reading quickstart guide. I do setup MySQL extension by reading MySQL Metadata Store as well.
But, when I sign to mysql to
mysql -u druid -p dirud

I got druid table only.I don't have any data that I imported with the following command via example.
curl -X 'POST' -H 'Content-Type:application/json' -d @quickstart/wikiticker-index.json localhost:8090/druid/indexer/v1/task

I saw Success status on Druid console http://localhost:8090/console.html as well.
The following is my common.runtime.properties for mysql setup
druid.metadata.storage.type=mysql
druid.metadata.storage.connector.connectURI=jdbc:mysql://127.0.0.1:3306/druid
druid.metadata.storage.connector.user=druid
druid.metadata.storage.connector.password=diurd

Is something wrong with my setup?

A: I think you are mistaken in understanding druid. Mysql is used just for storing the metadata of the segments and not the actual log data. The druid ingestion here must be using your local filesystem.

A: Mysql or postgresql just use to store the metabase about jobs/task info,the ingestion data was be store in your local filesytem \hdfs \S3 etc.

A: Apache Druid uses MySQL for reading and writing segment Metadata. It's highly inadvisable to use the same MySql database. An existing set up can be used by Druid. If I were you I would restrict Druid tables to druid user. And create a separate user for other application tables.


text:
Q: How to run java jar file on AWS EC2 server How to ran Java Jar file in AWS EC2 server.
I have tried -
nohup java -jar myfilename.jar > output.log &

With the above approach, I will store the logs in output.log file. I want to rotate it after 150 MB completed, Without stopping the application.
Also tried using PM2 -
Create process.json
{
    "apps":[
    {
        "name": "my-backend-api",
        "cwd":".",
        "script":"/usr/bin/java",
        "args":[
            "-jar",
            "/home/ubuntu/my-backend/target/my-api-0.0.1-SNAPSHOT.jar"
        ],
        "watch":[
            "/home/ubuntu/my-backend/target/my-api-0.0.1-SNAPSHOT.jar"
        ],
        "node_args":[],
        "log_date_format":"YYYY-MM-DD HH:mm Z",
        "exec_interpreter":"",
        "exec_mode":"fork"
     }
   ]
}

pm2 start process.json
Does not seems to be working, each and every time, its restart the application. I don't want to do that.
Any help here ? Would be appreciated. Thank you in advanced

A: We can ran our application -
nohup java -jar ./mybackend-api/target/myapp-api-0.0.1-SNAPSHOT.jar > ./logs/mylogs.log &

Install Logrotate - (For Ubuntu >= 18.0 version)
sudo apt update
sudo apt install logrotate

logrotate --version

Rotate Logs -
https://crontab.guru/
5 * * * * // Every 5 minutes
/home/ubuntu/logs/*.log {
missingok
maxsize 5M
rotate 2
compress
copytruncate
}
Run Cron Job -
crontab -e

Change in the file for every 5 minutes to change the logs
-> 5 * * * * logrotate -f logrotate.conf
Restart CRON -
sudo service cron reload

Or
/etc/init.d/cron reload

This is for rotating logs, if you wanted to do so.


text:
Q: How not to make a db call for checking user role in php? I know the standard way to check user roles mostly like if(isUserAuthorizedForTheOperation(userId)) in PHP which is create a db and for every user check the db and find out.Now this adds to immense performace issues.For every hit in my .php file,I find it extremly costly to query the database.What is the alternative?

A: Do you perform one query per hit/session or multiple? Make sure you only load in the roles once, store it in a (session) variable, and then keep checking that variable - instead of performing a query for every time you want to check.
(Taken from the comments as OP said it answered his question.)


text:
Q: iOS: How can I get username/password out of keychain for function "isEqual"? I'd like to autologin the user when the user is logged in. the credentials are saved in keychain, but now i have to compare them..
how can I get them out for a comparison?

A: Take a look at the GenericKeychain classes made by Apple. This shows how to access the keychain securely.
EDIT
Take a look at this blog post: Simple iPhone Keychain Access.


text:
Q: Springboot application (Spring 2.1.4) HTTPS Enabled I have to make my Spring boot application HTTPS enabled. For this task, I created a CSR and sent it to Security team of my employer. They provided a signed certificate ncf.cer to me. I was following steps from a website (https://www.thomasvitale.com/https-spring-boot-ssl-certificate/) and performed below steps.

*

*Import ncf.cer into Java/JDK1.8/JRE/lib/security/cacerts (assuming it is JKS keystore)
with alias 'ncf'

*In the code, placed ncf.p12 into src/main/resources

*Made below changes in applications.properties
server.ssl.key-store-type=PKCS12
server.ssl.key-store=src/main/resources/keystore/ncf.p12
server.ssl.key-store-password=changeit
server.ssl.key-alias=ncf

I am getting an error when I start the Springboot application:
Caused by: java.io.IOException: jsse.alias_no_key_entry

Can anyone please help me in getting the proper steps for making my application HTTPS enabled?

A: I fixed this issue finally. Below are the steps

*

*import .cer into cacerts with an alias.

*import .p12 into cacerts without providing alias. Here system will generate alias (long
alphanumeric number) for you. Mention this alias number inside applicatins.properties.

*Copy .p12 inside src/main/resoruces/keystore and then refer this path inside
applications.properties.

A: This error means your keystore doesn't contain the original private key.
The signed certificate ncf.cer is supposed to be imported into the original keystore where the cert request was generated. Is it cacerts? Typically this file only contains public keys of trusted certificates instead of the public/private key pair.
Once you have the signed certificate ncf.cer imported into the correct keystore, you can export into the PKCS12 format then use in your folder as ncf.p12. If you can share how the ncf.cer file was imported and ncf.p12 was created, I can further help.


text:
Q: How to "unfold" rows according to a column in Pandas There is this dataframe with a column which is actually a list:
import pandas as pd
df = pd.DataFrame([
    {"a":"a1", "b":"['b11','b12','b13']"},
    {"a":"a2", "b":"['b21','b22','b23']"}
])

which is just:
    a                    b
0  a1  ['b11','b12','b13']
1  a2  ['b21','b22','b23']

how can I have it unfolded like:
    a    b
0  a1  b11
1  a1  b12
2  a1  b13
3  a2  b21
4  a2  b22
5  a2  b23

My first guess was:
from functools import reduce
vls = df.apply(lambda x: [{'a': x['a'], 'b': b} for b in list(eval(x['b']))], axis=1).values
df = pd.DataFrame(reduce(lambda x, y: x + y, vls))

It works, but it takes a huge time for a small set (~ 1000 rows) of my data, and I must apply it to millions of rows.
I wonder if exists a better way using pandas api only.

A: Try this:
df.groupby('a').apply(lambda df: pd.DataFrame({'a':[df.a.iloc[0]] * len(eval(df.b.iloc[0])),'b': eval(df.b.iloc[0])}))

Instead of using reduce, this uses groupby function to expand the rows - assuming your a column is unique.


text:
Q: CNN with CTC loss I want to extract features using a pretrained CNN model(ResNet50, VGG, etc) and use the features with a CTC loss function.
I want to build it as a text recognition model.
Anyone on how can i achieve this ?

A: I'm not sure if you are looking to finetune the pretrained models or to use the models for feature extraction. To do the latter freeze the petrained model weights (there are several ways to do this in PyTorch, the simplest being calling .eval() on the model), and feed the logits from the last layer of the model to your new output head. See the PyTorch tutorial here for a more in depth guide.


text:
Q: How can I pass a method as an argument in Ruby? I am passing a method as an argument to a called function:
def my_function(args1)
   puts args1
end

def my_calling_method
   self.my_function(def do_this
             return 2*3
           end)
end

When I call my_calling_method which makes a call to my_function, I am getting args1 as nil instead of def do_this return 2*3 end.
Am I doing anything wrong? Can we pass method as an argument in Ruby?
Alright, I tried implemented a Proc for my requirement now but I am having a hard time to pass it to the calling method.
my_Proc = Proc.new do
    return 2*3
end

def my_calling_method
    self.my_function
end

def my_function my_Proc
   my_Proc.call
end

The reference material I used passes a Proc as an argument to the method like I do, but I am getting error, zero arguments passed to my_function as I am not passing any argument through my_calling_method.

A: Defining a new method will not return a value. (Much like writing down a phone number does not result in a conversation.)
irb:001>def something
irb:002>   # code here
irb:003>end
=> nil

When you run that in IRB, you get nil, right? So, if you define that method as part of a method call:
some_method( def something; stuff; end )

You are getting back nil from the method definition and hence nil is what gets passed into some_method.
Without knowing exactly what it is you are trying to accomplish, I will tell you that you can pass methods, or what are called "blocks", into your method call.
def my_function(&block)
  puts block.call
end

my_function {2*3}
#=> 6
my_function {t = Time.now; t + 8640}
#=> 2013-08-09 14:03:29 -0500
my_function do
   name = "Charlie"
   name.downcase.reverse.capitalize
end
#=> Eilrahc

In fact, this is what you are doing (more or less) with the method .each
array.each {|ele| foo}

I recommend reading up on Ruby's block, Procs, and Lambdas for passing methods in as arguments.

A: Nothing wrong. A method definition returns nil. The value of def do_this; return 2*3 end is nil. That is what you get.


text:
Q: How to debug failing updates for custom post type? Issue Overview
I have a post that I am working on for a few days, when I try to update it I get a error updating failed.
Steps to Reproduce (for bugs)
Make a post
Select a sub industry taxonomy
Save (I get the error).
Expected Behavior
It should update the post
Current Behavior
I get a error message "Updating failed"
Screenshots / Video
https://i.gyazo.com/66f11f5992c6780a62906ac6e4eb20d0.png
What I have done so far
Disabled Plugins one by one
Disabled All Plugins just leaving ACF and CPT UI
All points to some Gutenberg issue
Debug Info from Custom Post Tools
### Begin Custom Post Type UI Debug Info ###

Multisite:                No

SITE_URL:                 https://ktccidtdsdev.wpengine.com
HOME_URL:                 https://ktccidtdsdev.wpengine.com

WordPress Version:        5.5.1
Permalink Structure:      /%postname%/
Active Theme:             UnderStrap BUILDER

Registered Post Types:    post, page, attachment, revision, nav_menu_item, custom_css, customize_changeset, oembed_cache, user_request, wp_block, acf-field-group, acf-field, wpcf7_contact_form, benchmark_post, company, company_post, investor_post, notable_example, ignore, vc_grid_item, aoc_popup, vc4_templates

PHP Version:              7.3.22-1+ubuntu18.04.1+deb.sury.org+1
MySQL Version:            5.7.29
Web Server Info:          Apache

Show On Front:            page
Page On Front:            Home 2 (#3405)
Page For Posts:           Basic Blog (#2823)

WordPress Memory Limit:   40MB

TOTAL PLUGINS: 36

MU PLUGINS: (4)

Force Strong Passwords - WPE Edition: 1.6.4
WP Engine Seamless Login Plugin: 1.5.5
WP Engine Security Auditor: 1.0.9
WP Engine System: 4.0.0

ACTIVE PLUGINS: (34)

AddToAny Share Buttons: 1.7.42
Admin Columns: 4.2.2
Advanced Custom Fields: 5.9.1
Advanced Custom Fields PRO: 5.8.12
All-in-One WP Migration: 7.28
Better Search Replace: 1.3.3
Contact Form 7: 5.2.2
CSS Animator for VC: 1.6
Custom plugin for KnowTheChain by TBL: 0.1.1
Custom Post Type UI: 1.8.1
Disable REST API: 1.5
Display Posts: 3.0.2
Duplicate / Clone Pages and Posts: 1.2
Easy Forms for Mailchimp: 6.7.0
Fonts Plugin | Google Fonts Typography: 2.3.1
GDPR Compliance for Mailchimp: 1.3.3
Google Analytics Dashboard for WP (GADWP): 6.2.2
Hide admin menu: 1.0.9
Jetpack by WordPress.com: 9.0.2
LayerSlider WP: 5.5.1
Mailgun: 1.7.1
Popup anything on click: 1.7.7
Redirection: 4.8
Sassy Social Share: 3.3.13
SSL Insecure Content Fixer: 2.7.2
Ultimate Addons for WPBakery Page Builder: 3.19.3
What The File: 1.5.4
WordPress Importer: 0.7
WPBakery Page Builder: 6.1
WP Clone by WP Academy: 2.2.10
WP Mail SMTP: 2.4.0
WP Migrate DB Pro: 1.8.5
WP MVC: 1.3.20
WP Post Popup: 3.6.2

INACTIVE PLUGINS: (2)

Classic Editor: 1.6
Redux: 4.1.21

Post Types:
{"benchmark_post":{"name":"benchmark_post","label":"Benchmark Posts","singular_label":"benchmark_post","description":"","public":"false","publicly_queryable":"false","show_ui":"false","show_in_nav_menus":"false","delete_with_user":"false","show_in_rest":"false","rest_base":"","rest_controller_class":"","has_archive":"false","has_archive_string":"","exclude_from_search":"false","capability_type":"post","hierarchical":"false","rewrite":"true","rewrite_slug":"","rewrite_withfront":"true","query_var":"true","query_var_slug":"","menu_position":"","show_in_menu":"true","show_in_menu_string":"","menu_icon":"","supports":["title","editor","thumbnail"],"taxonomies":[],"labels":{"menu_name":"","all_items":"","add_new":"","add_new_item":"","edit_item":"","new_item":"","view_item":"","view_items":"","search_items":"","not_found":"","not_found_in_trash":"","parent_item_colon":"","featured_image":"","set_featured_image":"","remove_featured_image":"","use_featured_image":"","archives":"","insert_into_item":"","uploaded_to_this_item":"","filter_items_list":"","items_list_navigation":"","items_list":"","attributes":"","name_admin_bar":"","item_published":"","item_published_privately":"","item_reverted_to_draft":"","item_scheduled":"","item_updated":""},"custom_supports":""},"company":{"name":"company","label":"Companies","singular_label":"Company","description":"","public":"true","publicly_queryable":"true","show_ui":"true","show_in_nav_menus":"true","delete_with_user":"false","show_in_rest":"true","rest_base":"","rest_controller_class":"","has_archive":"false","has_archive_string":"","exclude_from_search":"false","capability_type":"post","hierarchical":"false","rewrite":"true","rewrite_slug":"","rewrite_withfront":"true","query_var":"true","query_var_slug":"","menu_position":"","show_in_menu":"true","show_in_menu_string":"","menu_icon":"","supports":["title","editor","excerpt"],"taxonomies":[],"labels":{"menu_name":"Companies","all_items":"All Companies","add_new":"","add_new_item":"","edit_item":"","new_item":"","view_item":"","view_items":"","search_items":"","not_found":"","not_found_in_trash":"","parent_item_colon":"","featured_image":"","set_featured_image":"","remove_featured_image":"","use_featured_image":"","archives":"","insert_into_item":"","uploaded_to_this_item":"","filter_items_list":"","items_list_navigation":"","items_list":"","attributes":"","name_admin_bar":"","item_published":"","item_published_privately":"","item_reverted_to_draft":"","item_scheduled":"","item_updated":""},"custom_supports":""},"company_post":{"name":"company_post","label":"Company Posts","singular_label":"Company Post","description":"","public":"true","publicly_queryable":"true","show_ui":"true","show_in_nav_menus":"true","delete_with_user":"false","show_in_rest":"true","rest_base":"","rest_controller_class":"","has_archive":"false","has_archive_string":"","exclude_from_search":"false","capability_type":"post","hierarchical":"false","rewrite":"true","rewrite_slug":"","rewrite_withfront":"true","query_var":"true","query_var_slug":"","menu_position":"","show_in_menu":"true","show_in_menu_string":"","menu_icon":"","supports":["title","editor","thumbnail","excerpt"],"taxonomies":[],"labels":{"menu_name":"","all_items":"","add_new":"","add_new_item":"","edit_item":"","new_item":"","view_item":"","view_items":"","search_items":"","not_found":"","not_found_in_trash":"","parent_item_colon":"","featured_image":"","set_featured_image":"","remove_featured_image":"","use_featured_image":"","archives":"","insert_into_item":"","uploaded_to_this_item":"","filter_items_list":"","items_list_navigation":"","items_list":"","attributes":"","name_admin_bar":"","item_published":"","item_published_privately":"","item_reverted_to_draft":"","item_scheduled":"","item_updated":""},"custom_supports":""},"investor_post":{"name":"investor_post","label":"Investor Posts","singular_label":"Investor Post","description":"","public":"true","publicly_queryable":"true","show_ui":"true","show_in_nav_menus":"true","delete_with_user":"false","show_in_rest":"true","rest_base":"","rest_controller_class":"","has_archive":"false","has_archive_string":"","exclude_from_search":"false","capability_type":"post","hierarchical":"false","rewrite":"true","rewrite_slug":"","rewrite_withfront":"true","query_var":"true","query_var_slug":"","menu_position":"","show_in_menu":"true","show_in_menu_string":"","menu_icon":"","supports":["title","editor","thumbnail","excerpt"],"taxonomies":["company_sector","company_post_topic"],"labels":{"menu_name":"","all_items":"","add_new":"","add_new_item":"","edit_item":"","new_item":"","view_item":"","view_items":"","search_items":"","not_found":"","not_found_in_trash":"","parent_item_colon":"","featured_image":"","set_featured_image":"","remove_featured_image":"","use_featured_image":"","archives":"","insert_into_item":"","uploaded_to_this_item":"","filter_items_list":"","items_list_navigation":"","items_list":"","attributes":"","name_admin_bar":"","item_published":"","item_published_privately":"","item_reverted_to_draft":"","item_scheduled":"","item_updated":""},"custom_supports":""},"notable_example":{"name":"notable_example","label":"Notable Examples","singular_label":"Notable Example","description":"","public":"true","publicly_queryable":"true","show_ui":"true","show_in_nav_menus":"true","delete_with_user":"false","show_in_rest":"true","rest_base":"","rest_controller_class":"","has_archive":"false","has_archive_string":"","exclude_from_search":"false","capability_type":"post","hierarchical":"false","rewrite":"true","rewrite_slug":"","rewrite_withfront":"true","query_var":"true","query_var_slug":"","menu_position":"","show_in_menu":"true","show_in_menu_string":"","menu_icon":"","supports":["title","editor","thumbnail"],"taxonomies":[],"labels":{"menu_name":"","all_items":"","add_new":"","add_new_item":"","edit_item":"","new_item":"","view_item":"","view_items":"","search_items":"","not_found":"","not_found_in_trash":"","parent_item_colon":"","featured_image":"","set_featured_image":"","remove_featured_image":"","use_featured_image":"","archives":"","insert_into_item":"","uploaded_to_this_item":"","filter_items_list":"","items_list_navigation":"","items_list":"","attributes":"","name_admin_bar":"","item_published":"","item_published_privately":"","item_reverted_to_draft":"","item_scheduled":"","item_updated":""},"custom_supports":""},"ignore":{"name":"ignore","label":"ignore","singular_label":"ignore","description":"","public":"true","publicly_queryable":"true","show_ui":"true","show_in_nav_menus":"true","delete_with_user":"false","show_in_rest":"true","rest_base":"","rest_controller_class":"","has_archive":"false","has_archive_string":"","exclude_from_search":"false","capability_type":"post","hierarchical":"false","rewrite":"true","rewrite_slug":"","rewrite_withfront":"true","query_var":"true","query_var_slug":"","menu_position":"","show_in_menu":"true","show_in_menu_string":"","menu_icon":"","supports":["title","editor","thumbnail"],"taxonomies":[],"labels":{"menu_name":"","all_items":"","add_new":"","add_new_item":"","edit_item":"","new_item":"","view_item":"","view_items":"","search_items":"","not_found":"","not_found_in_trash":"","parent_item_colon":"","featured_image":"","set_featured_image":"","remove_featured_image":"","use_featured_image":"","archives":"","insert_into_item":"","uploaded_to_this_item":"","filter_items_list":"","items_list_navigation":"","items_list":"","attributes":"","name_admin_bar":"","item_published":"","item_published_privately":"","item_reverted_to_draft":"","item_scheduled":"","item_updated":""},"custom_supports":""}}

Taxonomies:
{"company_category":{"name":"company_category","label":"Company Categories","singular_label":"Company Category","description":"","public":"true","publicly_queryable":"true","hierarchical":"true","show_ui":"true","show_in_menu":"true","show_in_nav_menus":"true","query_var":"true","query_var_slug":"","rewrite":"true","rewrite_slug":"","rewrite_withfront":"1","rewrite_hierarchical":"0","show_admin_column":"false","show_in_rest":"true","show_in_quick_edit":"true","rest_base":"","rest_controller_class":"","labels":{"menu_name":"","all_items":"","edit_item":"","view_item":"","update_item":"","add_new_item":"","new_item_name":"","parent_item":"","parent_item_colon":"","search_items":"","popular_items":"","separate_items_with_commas":"","add_or_remove_items":"","choose_from_most_used":"","not_found":"","no_terms":"","items_list_navigation":"","items_list":""},"meta_box_cb":"","object_types":["company","company_post","investor_post"]},"company_year_category":{"name":"company_year_category","label":"Sectors","singular_label":"Sector","description":"","public":"true","publicly_queryable":"true","hierarchical":"true","show_ui":"true","show_in_menu":"true","show_in_nav_menus":"true","query_var":"true","query_var_slug":"","rewrite":"true","rewrite_slug":"","rewrite_withfront":"1","rewrite_hierarchical":"0","show_admin_column":"false","show_in_rest":"true","show_in_quick_edit":"true","rest_base":"","rest_controller_class":"","labels":{"menu_name":"","all_items":"","edit_item":"","view_item":"","update_item":"","add_new_item":"","new_item_name":"","parent_item":"","parent_item_colon":"","search_items":"","popular_items":"","separate_items_with_commas":"","add_or_remove_items":"","choose_from_most_used":"","not_found":"","no_terms":"","items_list_navigation":"","items_list":""},"meta_box_cb":"","object_types":["company"]},"topic":{"name":"topic","label":"Topics","singular_label":"Topic","description":"","public":"true","publicly_queryable":"true","hierarchical":"true","show_ui":"true","show_in_menu":"true","show_in_nav_menus":"true","query_var":"true","query_var_slug":"","rewrite":"true","rewrite_slug":"","rewrite_withfront":"1","rewrite_hierarchical":"0","show_admin_column":"false","show_in_rest":"true","show_in_quick_edit":"","rest_base":"","rest_controller_class":"","labels":{"menu_name":"","all_items":"","edit_item":"","view_item":"","update_item":"","add_new_item":"","new_item_name":"","parent_item":"","parent_item_colon":"","search_items":"","popular_items":"","separate_items_with_commas":"","add_or_remove_items":"","choose_from_most_used":"","not_found":"","no_terms":"","items_list_navigation":"","items_list":""},"meta_box_cb":"","object_types":["company_post","investor_post"]},"company_brand":{"name":"company_brand","label":"Brands","singular_label":"Company Brand","description":"","public":"true","publicly_queryable":"true","hierarchical":"true","show_ui":"true","show_in_menu":"true","show_in_nav_menus":"true","query_var":"true","query_var_slug":"","rewrite":"true","rewrite_slug":"","rewrite_withfront":"1","rewrite_hierarchical":"0","show_admin_column":"false","show_in_rest":"true","show_in_quick_edit":"true","rest_base":"","rest_controller_class":"","labels":{"menu_name":"","all_items":"","edit_item":"","view_item":"","update_item":"","add_new_item":"","new_item_name":"","parent_item":"","parent_item_colon":"","search_items":"","popular_items":"","separate_items_with_commas":"","add_or_remove_items":"","choose_from_most_used":"","not_found":"","no_terms":"","items_list_navigation":"","items_list":""},"meta_box_cb":"","object_types":["company"]},"subindustry":{"name":"subindustry","label":"Sub Industries","singular_label":"Subindustry","description":"","public":"true","publicly_queryable":"true","hierarchical":"true","show_ui":"true","show_in_menu":"true","show_in_nav_menus":"true","query_var":"true","query_var_slug":"","rewrite":"true","rewrite_slug":"","rewrite_withfront":"1","rewrite_hierarchical":"0","show_admin_column":"false","show_in_rest":"true","show_in_quick_edit":"","rest_base":"","rest_controller_class":"","labels":{"menu_name":"","all_items":"","edit_item":"","view_item":"","update_item":"","add_new_item":"","new_item_name":"","parent_item":"","parent_item_colon":"","search_items":"","popular_items":"","separate_items_with_commas":"","add_or_remove_items":"","choose_from_most_used":"","not_found":"","no_terms":"","items_list_navigation":"","items_list":""},"meta_box_cb":"","object_types":["company"]},"company_year":{"name":"company_year","label":"Company Years","singular_label":"Company Year","description":"","public":"true","publicly_queryable":"true","hierarchical":"false","show_ui":"true","show_in_menu":"true","show_in_nav_menus":"true","query_var":"true","query_var_slug":"","rewrite":"true","rewrite_slug":"","rewrite_withfront":"1","rewrite_hierarchical":"0","show_admin_column":"false","show_in_rest":"true","show_in_quick_edit":"","rest_base":"","rest_controller_class":"","labels":{"menu_name":"","all_items":"","edit_item":"","view_item":"","update_item":"","add_new_item":"","new_item_name":"","parent_item":"","parent_item_colon":"","search_items":"","popular_items":"","separate_items_with_commas":"","add_or_remove_items":"","choose_from_most_used":"","not_found":"","no_terms":"","items_list_navigation":"","items_list":""},"meta_box_cb":"","default_term":"","object_types":["company"]}}

### End Debug Info ###


text:
Q: How can I fill in turtle directions in a list using Python? I have a list of turtle directions:
redlist = ['seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)']

How can I fill this in using the list?

A: Although a list of syntactically correct Python statements like this seems like an opportunity to use eval(), resist that temptation.  The syntax here is simple enough, function with one argument, that we can use the re module to parse the commands and only execute what appear to be valid functions against valid arguments:
import turtle
import re

redist = [ \
    'seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', \
    'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', \
    'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', \
    'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)' \
    ]

valid_functions = { \
    'seth': turtle.setheading, \
    'forward': turtle.forward, \
    }

valid_arguments = { \
    'drawdist': 50, \
    }

turtle.begin_fill()

for command in redist:
    match = re.match(r"^(\w+)\((\w+)\)$", command)

    if match is None:
        raise SyntaxError("Invalid syntax")

    function, argument = match.group(1), match.group(2)

    if function not in valid_functions:
        raise ValueError("Invalid function")

    if argument in valid_arguments:
        argument = valid_arguments[argument]
    elif argument.isdigit():
        argument = int(argument)
    else:
        raise TypeError("Invalid argument")

    valid_functions[function](argument)

turtle.end_fill()

turtle.hideturtle()

turtle.mainloop()

For those who want to read ahead, it draws a filled square.  The exceptions I raise above may not be the correct ones but the point is that you need to error check everything, and raise exceptions, when attempting to execute code that's been handed to you as a string.

A: Use pendown, then the fillcolor method in a loop:
def draw_n_fill(self,redlist):
  self.pendown()
  [self.getAttr(entry)() for entry in redlist]
  self.fillcolor("red")

References

*

*How to draw a ring of colors using turtle module in python

*Python: Using Turtles for Drawing Circles

*Summary of Turtle Methods


text:
Q: ubuntu package dependency error Webmin was upgrading packages and something went wrong after that and now i cannot install anything. Even my apache server is down . When i type
apt-get install apache2

i get this error
The following packages have unmet dependencies:
 apache2 : Depends: apache2-mpm-worker (= 2.2.22-6ubuntu2.3) but it is not going to be installed or
                    apache2-mpm-prefork (= 2.2.22-6ubuntu2.3) but it is not going to be installed or
                    apache2-mpm-event (= 2.2.22-6ubuntu2.3) but it is not going to be installed or
                    apache2-mpm-itk (= 2.2.22-6ubuntu2.3) but it is not going to be installed
           Depends: apache2.2-common (= 2.2.22-6ubuntu2.3) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

then i ran apt-get dist-upgrade
and got this
The following packages have been kept back:
  libtiff4 libxml2 rpm-common
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.

please help


text:
Q: Replacing Placeholder text containing a variable Hi I have placeholder text in my content from the CMS like this:
$content = "blah blah blah.. yadda yadda, listen to this:
{mediafile file=audiofile7.mp3}
and whilst your here , check this: {mediafile file=audiofile24.mp3}"

and i need to replace the placeholders with some html to display the swf object to play the mp3.
How do i do a replace that gets the filename from my placeholder.
I think the regx pattern is {mediafile file=[A-Za-z0-9_]}  but then how do i apply that to the whole variable containing the markers?
Thanks very much to anyone that can help,
Will

A: Here is a quick example, using preg_replace_all, to show how it works :
if $content is declared this way :
$content = "blah blah blah.. {mediafile file=img.jpg}yadda yadda, listen to this:
{mediafile file=audiofile7.mp3}
and whilst your here , check this: {mediafile file=audiofile24.mp3}";

You can replace the placeholders with something like this :
$new_content = preg_replace_callback('/\{mediafile(.*?)\}/', 'my_callback', $content);
var_dump($new_content);

And the callback function might look like this :
function my_callback($matches) {
    $file_full = trim($matches[1]);
    var_dump($file_full);       // string 'file=audiofile7.mp3' (length=19)
                                // or string 'file=audiofile24.mp3' (length=20)
    $file = str_replace('file=', '', $file_full);
    var_dump($file);            // audiofile7.mp3 or audiofile24.mp3

    if (substr($file, -4) == '.mp3') {
        return '<SWF TAG FOR #' . htmlspecialchars($file) . '#>';
    } else if (substr($file, -4) == '.jpg') {
        return '';
    }
}

Here, the last var_dump will get you :
string 'blah blah blah.. yadda yadda, listen to this:
<SWF TAG FOR #audiofile7.mp3#>
and whilst your here , check this: <SWF TAG FOR #audiofile24.mp3#>' (length=164)

Hope this helps :-)

Don't forget to add checks and all that, of course ! And your callback function will most certainly become a bit more complicated ^^ but this should give you an idea of what is possible.
BTW : you might want to use create_function to create an anonymous function... But I don't like that : you've got to escape stuff, there is no syntax-highlighting in the IDE, ... It's hell with a big/complex function.

A: Read the regex docs carefully.
your pattern looks a little off.  {mediafile file=([^}]+)} might be ore like what you're looking for (the regex you gave doesn't allow for ".").

A: you do something like that
$content = preg_replace_callback(
        '|{mediafile file='([A-Za-z0-9_.]+)}|',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return "<embed etc ... " . ($matches[1]) ."more tags";'
        ),
        $content
    );

you can see the manual of preg_replace_callback. Normal preg_replace also work but might be a messy.

A: I originally was thinking you could use a function that involved json_decode, but strings need to be wrapped in quotes or json_decode doesn't handle them. So if your placeholders were written:
{"mediafile" : "file" : "blahblah.mp3"}

you could change my sample code from using explode($song) to json_decode($song, true) and have a nice keyed array to work with.
Either way, I went with using the strtok function to find the placeholders, and then a basic string replace function to change the instances of the found placeholders into html, which is just gibberish.
strtok, so far as PHP docs indicate, does not use regex, so this would be not only simpler but also avoid a call to the preg library.
One last thing. If you do go with json syntax, you will have to re-wrap the placeholders in{} as strtok removes the tokens it is searching by.
<?php
$content = "blah blah blah.. yadda yadda, listen to this:
{mediafile file=audiofile7.mp3}
and whilst your here , check this: {mediafile file=audiofile24.mp3}";

    function song2html($song) {
       $song_info = explode("=", $song);
       $song_url = $song_info[1];
       $song_html = "<object src=\"$song_url\" blahblahblah>blah</object>";
    return ($song_html);
    }

$tok = strtok($content, "{}");

while ($tok !== false) {
    if(strpos($tok, "mediafile") !== false) {
  $songs[] = $tok;
 }
 $tok = strtok("{}");
}

foreach($songs as $asong) {
 $content = str_replace($asong, song2html($asong), $content);
}

echo $content;
?>


text:
Q: My prison won't receive any food from deliveries and it says my prisoners won't come for 10,000 hours I only have one prisoner left for some reason and it says that the 9 prisoners won't come for 16,689 hours, I tried to open than close the prison intake and also went into the save and changed it into continuous and it still didn't work. Food also isn't being delivered and I made two deliveries and it didn't work. Does anyone know what is happening?

A: You can try to fix the next intake problem and see if that resolves the food deliveries (it's not going to deliver food when there are no prisoners to eat it).
Find your save game file and open it in a text editor. in the top section of the file you are looking for two values TimeIndex and Intake.next; edit the Intake.next value to be 100 more than TimeIndex. That should resolve the time to next intake issue.
Reload the save game and see, after the new prisoners have arrived, if you start to receive food deliveries again.


text:
Q: I am not able to go into my virtual environment I am new to programming. I recently started learning Django by following the tutorials on Mozilla. I created a python virtual environment by following the steps in the tutorial. However, I am not able to activate the virtual environment that I have created. As . a result, I am not able to progress on the tutorials. I have spent hours trying trying to find a solution on Google, but nothing seems to work. I have attached a picture of the terminal window where you can see the commands I am entering and the results.
hemantasundaray@Deepaks-MacBook-Pro ~ % source createdenv/bin/activate
source: no such file or directory: createdenv/bin/activate
hemantasundaray@Deepaks-MacBook-Pro ~ % ls virtualenv
ls: virtualenv: No such file or directory
hemantasundaray@Deepaks-MacBook-Pro ~ % workon
zsh: command not found: workon
hemantasundaray@Deepaks-MacBook-Pro ~ %

What am I doing wrong?

A: Basically virtual environment is to isolate your python packages so that they don't interfere with system wide packages.
My suggestion your question is, cd to the folder where you want your project to reside, and create the virtual environment. My suggestion is please go with pipenv to create virtual environment. It made by Kenneth Reitz and it's awesome, github link
If you want to install pipenv, simply install with pip or apt if you are on ubuntu, or with brew if you are on mac, You can also use the pip provided by python to install pipenv,
      sudo apt install python3-pipenv

or you could install it with pip,
      pip3 install pipenv

or for mac use, follow the answer
      brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/2c0bbfa297e2429cd6e080ad5231f3aa56ff4f65/Formula/pipenv.rb

To install django, simply activate the virtual environment with the above pipenv shell command and run
    pipenv install django

eg:
- If you want to create a new django django_project_you_fancy, I would do,
        mkdir my-django-project
        cd my-django-project
        pipenv shell

This would create a Pipfile, next time whenever you want to use the virtual environment, simple cd into the folder and type pipenv shell

Simple run the django-admin commands to creating project and get started with the fun.
     django-admin startproject django_project_you_fancy


text:
Q: Cursive Words not connecting in image OutPut Image /  Expected Image
I am generating images for cursive scripts through font and its unicode but in output image characters are separate not joined. i need joined characters same as expected image.
Please ask if question is not clear.
Images are linked above.
unicode_text = u"\u0627\u0628\u062A\u062B"
list_of_letters = list (unicode_text)
folder = 1
n=3
for i in range(1,n+1):
    for word in itertools.permutations( list_of_letters,i):
   char = ''.join(word)
   verdana_font = ImageFont.truetype("Nafees Naskh v2.01.ttf", 30, encoding="unic")
   text_width, text_height = verdana_font.getsize(''.join(word))
   canvas = Image.new('RGBA', (100, 100), (255, 255, 255),)
   draw = ImageDraw.Draw(canvas)
   canvas.save(path + '\\' + char[::-1]+'.png', "PNG")
   folder += 1

A: The docs say you should specify features. See http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.Draw.text
PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None,
    spacing=0, align="left", direction=None, features=None)

features should be a list with the feature(s) responsible of chaining this chars. I do not know enough about arbic script. But it is likely some ligature, positioning and/or substitution feature.
For a list of features see:
https://www.microsoft.com/typography/otspec/featurelist.htm
The docs also mention that this requires libraqm to be installed.


text:
Q: Need help debugging Bootstrap/CSS that renders fine everywhere but iPad My site renders fine on every browser I've tested on both desktop and iPhone. However, on iPad, it cuts off the content at the top, no matter which browser is being used. (Each browser shows a slightly different amount of the content.) Super simple, single page site built with Bootstrap 3.
Would appreciate any pointers about where I went wrong with the code. CSS is not my strong suit; I'm relearning it, so apologies for what I'm sure is a basic question.


text:
Q: WooCommerce - no confirmation after adding product to cart I'm not sure it's meant to be like this, but when I click the 'Add to cart' button on a product (when viewing a page of products), no visual confirmation is given to the user.
Am I missing a JS file? Or maybe I need a div with a specific ID in my HTML for the message to be displayed in? Or do I need to create my own JS callback method to handle when the product has been added?
I've researched this, and there's surprisingly little info on it (so maybe I broke something?).
I have WC's "Enable AJAX add to cart buttons on product archives" option ticked, and I can confirm that products are actually being added to the cart - the user just doesn't know anything about it!
Thanks in advance.

A: Problem solved - I had unticked WC's "Enable WooCommerce CSS styles". It should come with a warning in my opinion! :)


text:
Q: Seaborn plots in jupyter notebook showing in same cell I have multiple cells in a jupyter notebook each containing a plot. When I execute these cells I expect to see the plot below each cell however I am seeing the plots overwriting each other on each execution. Does anyone know if its a bug or am I doing something wrong?
First cell code
tips = pd.read_csv(r"D:\code_and_data\pydata-book-3rd-edition\examples\tips.csv")

party_counts = pd.crosstab(tips["day"], tips["size"])
party_counts = party_counts.reindex(index=["Thur", "Fri", "Sat", "Sun"])

party_pcts = party_counts.div(party_counts.sum(axis="columns"),axis="index")

party_pcts.plot.bar()

Second cell code
tips['tip_pct'] = tips['tip']/(tips['total_bill'] - tips['tip'])

tips.head()

tips["tip_pct"].plot.hist(bins=50)


text:
Q: Display dates on axes in R I have a data frame df contains 2 fields (Number and dates) as the following
Number  date
1496    Apr-08
3067    May-08
3049    Jun-08
3077    Jul-08
3237    Aug-08
3020    Sep-08
4990    Oct-08
4776    Nov-08
5140    Dec-08
5582    Jan-09
5743    Feb-09
5561    Mar-09
5974    Apr-09

I want to use plot() function in R to plot number vs. date
I've tried using axis.Date() function but it didn't work. Nothing displayed on the plotting area and I don't know why. My code was:
plot(df$Number)
axis.Date(1, at=seq(min(df$date), max(df$date), by="months"), format="%m-%Y")

Any help, please?

A: It seems that your biggest problem is creating an appropriate date structure for your data. It would be good to acquaint yourself to the different ways that R keeps the date structure. ?strptime has a rather good list of syntax commonly used.
In your question then, to convert your date to a form which axis.Date can work, you need to add an arbitrary day into your date field and then convert it with as.Date:
df$date <- as.Date(paste0("01-", df$date), format="%d-%b-%y")

This way, your axis.Date plot would work:
plot(df$date, df$Number, xaxt="n")
axis.Date(1, at=seq(min(df$date), max(df$date), by="months"), format="%m-%Y")

Input data:
df <- structure(list(Number = c(1496, 3067, 3049, 3077, 3237, 3020,
4990, 4776, 5140, 5582, 5743, 5561, 5974), date = c("Apr-08",
"May-08", "Jun-08", "Jul-08", "Aug-08", "Sep-08", "Oct-08", "Nov-08",
"Dec-08", "Jan-09", "Feb-09", "Mar-09", "Apr-09")), .Names = c("Number",
"date"), row.names = c(NA, -13L), class = "data.frame")

A: The likely source of your problem is that df$date is not a date, but e.g. a character.
Using
str(df)
'data.frame':   13 obs. of  2 variables:
 $ Number: int  1496 3067 3049 3077 3237 3020 4990 4776 5140 5582 ...
 $ date  : chr  "Apr-08" "May-08" "Jun-08" "Jul-08" ...
# note that date is a character vector here, as opposed to Date.

and
plot(df$Number)
axis(1, at=1:nrow(df), labels=df$date)

I get


text:
Q: WinForms Events for Inheriting Controls for UI Style Follow up to this question:
Winforms Style / UI Look and Feel Tips
So I have created my "base controls" from which other controls inherit from. For testing, I am trying to change one of the base label's font. But it is not propagating to the controls that inherit from it. On one of the forms, I can see the designer file is setting the properties for the control, so my base control's properties are getting overridden.
On the base control's I am using the Constructor to set the default properties. Should I be using a different event? If so, which one.
Here is the code for one of the base controls based on comment request...
Public Class InfoLabel
    Inherits Label

    Public Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.Font = New System.Drawing.Font("Tahoma", 14.25!)
        Me.ForeColor = System.Drawing.Color.FromArgb(CType(CType(49, Byte), Integer), CType(CType(97, Byte), Integer), CType(CType(156, Byte), Integer))
        Me.AutoSize = False

    End Sub
End Class

The base controls show on the projects toolbox on the winform editor. Controls are then drag/drop from the toolbox.

A: Your problem is your custom control's InitializeComponent() method. I have no idea why that is there. You would get that method automatically if you were implementing a UserControl, but inheriting from a standard control that method should not be there. With your base class having an InitializeComponent() method and your subclass also having one, someone is overwriting someone else.
I just subclassed a label in C#. I dragged this on my form and the font displayed as the new font, not the base (Label) class's font.
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class MyLabel : Label
    {
        public MyLabel()
        {
            Font = new Font("Candara", 14);
        }
    }
}

I then created a second label, called MySubLabel which inherited from the MyLabel class. When I changed the ForeColor on the MyLabel class, the MySubLabel automatically updated.
So this should work.
Caveat: in Visual Studio you need to recompile the assembly before trying to see updates in the designer.