text:
Q: Making one part polyline from multipart polyline? I have a polyline which is divided into multiparts and these parts are not well ordered so that the vertex's ID are not following the polyline's plotting.
This polyline is a representing a bus line and I need to have the plotting following the driving way of the bus. I would like to know how to merge the multiparts of this polyline?
I have already tried to Split and Unsplit, as well as Multipart to Single Part, Union, Merge, etc. but no one is giving me the result I want.

A: I see from your tags that you are running ArcGIS 10. I've used the following method for a similar task:
1) Use Multipart to Single Part
2) Use Unsplit
In order for this to work (i.e. so that you have the lines in the proper order) you may need to break the line into the constituent end points and then change the direction based on an attribute (e.g. 1 = start, 2 = end) - you can use this to conditionally connect only those points that are different (If 1 + 2 then create connecting lines).
If you're working with an IDE the code for doing this is quite lengthy, but I will do my best to help if you have specific questions.

A: I had to do exactly the same  quite a while back using AV 3.x and Avenue. I had a quick look for the code but couldn't find it. If I remember correctly the logic went something like this: (I also had the bus stops and terminals as a different point shapefile so I was able to determine the start and end parts):

*

*Create an empty polyline to receive the sorted parts. Lets call it the 'sorted polyline'

*To get the first part:
2a. Get the part that is closest to start terminal
2b. Get the distances of the start and end node of this part to the start terminal. If the start vertex is the closest one add this part to the 'sorted polyline'. If its the end- FLIP it and then add it.

*To get the middle and end parts, start with the part (polyline) that you created in the previous step and within a while(true) loop, start comparing the distance between the end node of the first part to the other parts in the input polyline. The one that is closest is the 'next part'. Compare the distance of the start and end node of the next part to determine whether to flip it or not before adding it to the 'sorted polyline'

*Exit the loop when the number of part in the 'sorted polyline' is the same as in the input polyline.

... or something like that! :-)
Let me know if this makes sense to you and I can have another go finding my original Avenue code.

A: I worked in a project something similar of this, I used ArcObjects. My goal was connecting two adjacent polylines if one of it's end point is another one's starting point to make two short polylines into a single polyline. My process was:
1. Dictionary<PointKey, FeatureDataList> polylineDictionary;

*

*PointKey is a class that contains a point.

*FeatureDataList is a class that contains List of IFeatures.

*Both classes overrides "Equals" and "GetHashCode" methods.
Dictionary<PointKey, FeatureDataList> ToPointDictionary;
Dictionary<PointKey, FeatureDataList> FromPointDictionary;
public void CreateDictionary(IFeatureLayer featureLayer)
{
    var featureFunctionality = new FeatureFunctionality();
    List<IFeature> features = GetAllFeatures(featureLayer.FeatureClass);

    foreach (var feature in features)
    {
        IPolyline polyline = GetPolylineFromFeature(feature);
        AddFeatureInDictionary(ToPointDictionary, feature, polyline.ToPoint);
        AddFeatureInDictionary(FromPointDictionary, feature, polyline.FromPoint);
    }
}

void AddFeatureInDictionary(Dictionary<PointKey, FeatureDataList> polylineDictionary, IFeature feature, IPoint point)
{
    FeatureDataList featureDataList;
    PointKey key = PointKey.GetKey(point);
    if (!polylineDictionary.ContainsKey(key))
    {
        featureDataList = new FeatureDataList();
        featureDataList.Add(feature);
        polylineDictionary.Add(key, featureDataList);
    }
    else
    {
        featureDataList = polylineDictionary[key];
        featureDataList.Add(feature);
    }
}

By these processes I made two dictionaries. After creating dictionaries, I check for if both dictionaries contain same point and in both dictionaries, that key has only one feature in feature list, then I created a new polyline with those two polylines and delete two short polylines.
To join two polylines into one:
   private IPolyline GetJoinedPolylineFromFeatures(List<IFeature> features)
   {
        IPolyline newPolyline = null;
        if (features.Count == 2)
        {
            IPolyline polyline1 = feature1.Shape as IPolyline;
            IPolyline polyline2 = feature2.Shape as IPolyline;
            if (PointKey.GetKey(polyline1.ToPoint).Equals(PointKey.GetKey(polyline2.FromPoint)))
            {
                var topoOperator2 = polyline1 as ITopologicalOperator2;
                if (topoOperator2 != null)
                    newPolyline = topoOperator2.Union(polyline2) as IPolyline;
            }
            else if (PointKey.GetKey(polyline1.FromPoint).Equals(PointKey.GetKey(polyline2.ToPoint)))
            {
                var topoOperator2 = polyline2 as ITopologicalOperator2;
                if (topoOperator2 != null)
                    newPolyline = topoOperator2.Union(polyline1) as IPolyline;
            }
        }
        return newPolyline;
  }

A: I had exactly the same problem due to updates I made to bus routes using the "Reshape Feature" Tool. Dissolve, Merge and Unsplit were not working because the multipart features were not coincident.
If you haven't noticed this by now, take a closer look at the vertices that must coincide between your multipart features. Extend, trim or reshape as necessary and then use any of the tools stated above.


text:
Q: How to pass a list of arguments to a function so that it performs it in order (not simultaneously on all elements of the list) in python? This is a function that counts numbers on a txt. First, it navigates through directories. For that, I have to use os.path.join.
def checkmove(subject):
    os.chdir(os.path.join(directory, subject, 'func', 'run 1'))
    print("Check for volumes repaired in " + subject+ ":")
    try:
        f = open('art_repaired.txt', 'r')
    except:
        print("'art_repaired.txt' not found")
    tot_vols = 0
    for line in f:
        parts = line.split()
        tot_vols += len(parts)
    print("Volumes repaired in run 1: "+ str(tot_vols))
    del f, tot_vols, parts

The problem is I would need to pass a list of arguments (subjects) to the function, so that the function is performed on each element of the list in order, one by one.
Of course, if I try, it gives me the error:
TypeError: join() argument must be str, bytes, or os.PathLike object, not 'list'
How could I do this??

A: def checkmove(*subject):
    for foobar in subject:
        os.chdir(os.path.join(directory, subject, 'func', 'run 1'))
        whatyouwanthere

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect UNICODE characters when trapping WM_CHAR messages? So, my window procedure is currently trapping all WM_CHAR messages, it works fine with ASCII characters but when I try something like:
case 'ф':
    MessageBox(NULL, TEXT("Ф detected"), TEXT("key"), MB_OK);

it fails for some reason.
What's wrong with my approach and how do I fix this?
EDIT: source-code:
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     switch (message)
     {

          case WM_CHAR:
               switch(wParam)
               {

                  case '3':
                    MessageBox(NULL, TEXT("'3' was pressed"), TEXT("key detected"), MB_OK);
                    return 0;
                  case 'ф':
                    MessageBox(NULL, TEXT( "ф was pressed"), TEXT("key detected"), MB_OK);
                    return 0;

                  default:
                      return 0;
               }

          case WM_DESTROY :
               PostQuitMessage (0) ;
               return 0 ;

     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}

A: Non-Unicode characters need to be replace as Unicode characters in switch-case:
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     switch (message)
     {

          case WM_CHAR:
               switch(wParam)
               {

                  case L'3':
                    MessageBox(NULL, TEXT("'3' was pressed"), TEXT("key detected"), MB_OK);
                    return 0;
                  case L'ф':
                    MessageBox(NULL, TEXT( "ф was pressed"), TEXT("key detected"), MB_OK);
                    return 0;

                  default:
                      return 0;
               }

          case WM_DESTROY :
               PostQuitMessage (0) ;
               return 0 ;

     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}

The values of 'ф' and L'ф' are different. The values of 'ф' and other characters not in the ASCII table are often resolved to '?' (63)


text:
Q: Ubuntu 13.10 Symfony installation date time issue I'm installing Symfony on my Ubuntu system, everything was going fine until the very last moment when I was met with a screen that said:
ContextErrorException: Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /var/www/symfony-test/app/cache/dev/classes.php line 5107

    in /var/www/symfony-test/app/cache/dev/classes.php line 5107
    at ErrorHandler->handle('2', 'date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.', '/var/www/symfony-test/app/cache/dev/classes.php', '5107', array('level' => '100', 'message' => 'Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException".', 'context' => array()))
    at date_default_timezone_get() in /var/www/symfony-test/app/cache/dev/classes.php line 5107
    at Logger->addRecord('100', 'Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException".', array()) in /var/www/symfony-test/app/cache/dev/classes.php line 5193
    at Logger->debug('Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException".') in /var/www/symfony-test/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Debug/TraceableEventDispatcher.php line 246
    at TraceableEventDispatcher->preListenerCall('kernel.exception', array(object(ProfilerListener), 'onKernelException')) in /var/www/symfony-test/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Debug/TraceableEventDispatcher.php line 448
    at TraceableEventDispatcher->Symfony\Component\HttpKernel\Debug\{closure}(object(GetResponseForExceptionEvent))
    at call_user_func(object(Closure), object(GetResponseForExceptionEvent)) in /var/www/symfony-test/app/cache/dev/classes.php line 1667
    at EventDispatcher->doDispatch(array(object(Closure), object(Closure)), 'kernel.exception', object(GetResponseForExceptionEvent)) in /var/www/symfony-test/app/cache/dev/classes.php line 1600
    at EventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in /var/www/symfony-test/app/cache/dev/classes.php line 1764
    at ContainerAwareEventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in /var/www/symfony-test/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Debug/TraceableEventDispatcher.php line 139
    at TraceableEventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in /var/www/symfony-test/app/bootstrap.php.cache line 2870
    at HttpKernel->handleException(object(ContextErrorException), object(Request), '1') in /var/www/symfony-test/app/bootstrap.php.cache line 2823
    at HttpKernel->handle(object(Request), '1', true) in /var/www/symfony-test/app/bootstrap.php.cache line 2947
    at ContainerAwareHttpKernel->handle(object(Request), '1', true) in /var/www/symfony-test/app/bootstrap.php.cache line 2249
    at Kernel->handle(object(Request)) in /var/www/symfony-test/web/app_dev.php line 28

After many hours of trying ideas in other threads, editing php.ini and classes.php to something that might work, I have gotten absolutely nowhere!  Has anyone else had this problem
EDIT! The plot thickens!
So I cleared the cache via the terminal, and I got an error relating to classes.php, which apparently is to do with permissions, so I sorted that as per the instructions on Symfony's site, and now guess what's happened?  We're back to square one, only this time I can't clear my cache to make it go away.  Yet, after I do clear the cache instead of it being php.ini, it's instead Logger.php, locating in /vendor/monolog/monolog/src/Monolog, but then after a refresh it's back to php.ini
SOLVED
I feel like a bit of an idiot here! I didn't realise .ini files used ';' to indicate a comma, therefore every line in my php.ini file was a comment.  I removed the semi-colon and now it all works

A: Set the timezone string in the php.ini.  I strongly recommend that your server be configured to use UTC and then your setting should be:
date.timezone = UTC

Restart your web server
Just to be double safe:
php app/console cache:clear

You might also have an issue finding the right php.ini.  Check these directories:
/etc/php5/apache2
/etc/php5/cli

Ubuntu tends to separate out php.ini's for the command line vs mod_php, vs cgi, and there are directories for each. If you're not sure which php.ini is being loaded, there is php -i for the cli and the phpinfo(); program you can put in a quick script under your webroot.  Each will provide you information on the location of the php.ini that is being loaded.

A: Set the date/timezone in php.ini but make sure you clear your cache before running your code again.
Symfony 2 cache clear is required as the classes.php is created by Symfony.
From the main project dir
    app/console cache:clear --env=dev


text:
Q: creating a custom label for axis y in ASP.Net chart as a string I have a 3 point axis for axisY in a chart for ASP.NET.  Right now it shows 1, 2, and 3. I need to assign string values to the points. I have found that it is somewhere in here:
Chart1.ChartAreas[0].AxisY.CustomLabels.Add(??????);

Not sure how to get it not to have to take a double value and be able to assign a string to the point.

A: You have to create a custom label, set its properties, then add it to the axis
What about this?
    CustomLabel label = new CustomLabel();

    label.FromPosition = -1.0;
    label.ToPosition = 1.0;
    label.Text = "0";
    label.RowIndex = 0;

    Chart1.ChartAreas[0].AxisY.CustomLabels.Clear();
    Chart1.ChartAreas[0].AxisY.CustomLabels.Add(label);

This will render a 0 where the Y-axis meets the X-axis.


text:
Q: AJAX : undefined index after serialize I have a problem with AJAX. I want to send a value I get with a form, and then do something with this value on my PHP script.
But I have always "undefined index" and I don't understand why.
My form :
<form target="../app/DisplayController.php" method="post" class="form-group month-chose col-6 mx-auto" id="form-month">
        <select class="form-control" id="month" name="month">
            <option value=''>Chose :</option>
            <?php foreach($viewVars[2] as $result): ?>
                <option value='<?=$result->getId();?>'><?=$result->getMonth();?></option>
            <?php endforeach; ?>
        </select>
        <button class="btn btn-success mt-3">Ok</button>
</form>

Here you have my JS code :
$('.month-chose').on('submit', function(){
            event.preventDefault();
            var answers = $('#form-month').serialize();
            console.log(answers);
            $.ajax({
                method : 'POST',
                url : '../app/inc/chose-month.php',
                data: answers,
                success: $('.month-chose').load('../app/inc/chose-month.php')
            });
        })

My data are OK, my consol.log return "month=2".
And here my PHP test script (chose-month.php) :
<?php
echo 'Hi I'm ' . $_POST['month']; ?>

When I load the template, I have this famous "month: undefined index".
Thx for ur help !


text:
Q: Displaying the correct price I'm struggling with the problem on this website (http://duledo.co.uk/product-category/self-healing-mat-cutting-mat/). I used WooCommerce Currency Switcher. The prices are updated except English version of this site. What's the problem with this?
Thanks in advance for any help.

A: Check woocommerce settings. There must be a tab name currency. Check the currency, symbol, price etc from one you have choosen to show under english language.
Even after this if you are getting this issue then you can also override plugin.


text:
Q: ssl handshake failure when using getpage() with python26-twisted I am getting handshake failure problem with getPage() with twisted.
I am using Amazon Linux AMI release 2015.03. It ships with Python 2.6.9 and twisted version I am using is:
python26-twisted-web-8.2.0-3.2.3.amzn1.x86_64
python26-twisted-core-8.2.0-4.7.amzn1.x86_64
python26-twisted-words-8.2.0-3.2.3.amzn1.x86_64

The code is here:
from twisted.web import client
from twisted.internet import reactor

if __name__ == "__main__":
    def do( ):
        df = client.getPage(
            url = "https://ui2web1.apps.uillinois.edu/BANPROD1/bwskfcls.P_GetCrse",
            followRedirect = True,
        )
        def printOnError( error ):
            print 'E', error
        def printOnSuccess( page ):
            print 'S', page
        df.addErrback( printOnError )
        df.addCallback( printOnSuccess )
        return df
    reactor.callWhenRunning( do )
    reactor.run()

The error I am getting is:
E [Failure instance: Traceback (failure with no frames): <class 'OpenSSL.SSL.Error'>: [('SSL routines', 'SSL3_READ_BYTES', 'sslv3 alert handshake failure'), ('SSL routines', 'SSL3_READ_BYTES', 'ssl handshake failure')]
]
S

Any help will be highly appreciated.


text:
Q: sklearn SVM custom kernel I need to implement a custom kernel in sklearn.
This would be a custom linear kernel:
def my_kernel(x, y):
    return np.dot(x, y.T)

But I am having trouble doing something like RBF kernel. Is it possible to do that in sklearn  a custom kernel?
I have tried this:
def my_kernel(x, y):
    gamma = 0.01
    return np.exp((gamma* np.power(np.linalg.norm(x-y),2)))`

But did not work.
(I know that there is a pre-implementation of RBF, but I need to manually implement it, because I need to add some parameters)

A: Your function looks good. Just use
clf = svm.SVC(kernel=my_kernel)
clf.fit(X, Y)

There is an example related to your application.

A: I have implemented somthing like this
import numpy as np
from sklearn.metrics.pairwise import euclidean_distances
def gaussian_kernel(X, Y):
    kernel = euclidean_distances(X, Y) ** 2
    kernel = kernel*(-1/(self.gamma**2))
    kernel = np.exp(kernel)
    return kernel

and then have called svm with my defined kernel
from sklearn import svm
clf = svm.SVC(kernel=gaussian_kernel, max_iter = 10000)
clf.fit(X_train, y_train)

this seemed to work fine. The only this that I failed to do was pass a hyperparameter from svm to my implementation of kernel, so I started defining the hyper-parameter globally instead as a work around.
As you would see I have defined a self.gamma which I wanted to tune but the gamma defining while initializing svm was not passing to my function.


text:
Q: Adding a view on top of a AVCapturesession I am trying to add a button on top of my AVCapturesession preview layer. this button is to capture images (fire the capture function)..however i can not seem to set one up.
func configureCaptureSession() {

    captureSession.sessionPreset = AVCaptureSession.Preset.photo

    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaType.video, position: .unspecified)

    for device in deviceDiscoverySession.devices {
        if device.position == .back {
            rearCam = device
        } else if device.position == .front {
            frontCam = device
        }
    }
currentDevice = rearCam
    guard let captureDeviceInput = try? AVCaptureDeviceInput(device: currentDevice) else {
        return
    }
   // wheelOverlay.image = UIImage(named: "wheel")
  //  wheelOverlayLayer.contents = wheelOverlay
    stillPhotoOutput = AVCapturePhotoOutput()

    captureSession.addInput(captureDeviceInput)

    captureSession.addOutput(stillPhotoOutput)

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cameraPreviewLayer?.frame = view.layer.frame
    print("Capture session setup")
   // view.layer.addSublayer(wheelOverlayLayer)
   // view.layer.insertSublayer(wheelOverlayLayer, above: cameraPreviewLayer)
    captureSession.startRunning()

}

where abouts do i need to add the subview?

A: You need to add it to the view after you add the cameraLayer like this
view.layer.addSublayer(cameraPreviewLayer)
let bt = UIButton(type:.system)
bt.setTitle("Record",for:.normal)
bt.frame = /////
view.addSubview(bt)


text:
Q: My new database stop adding new documents when reach 25000 I was creating a DB from a flat file with millions of data, using pymongo. Everything was running perfectly until the database reached 25000 documents. Now, my script is waiting (I don't know why) and my database is not growing more. This is the first time I use MongoDB (I'm already a newbie in NoSQL databases). It's very curious that DB growing stopped just in a rounded number (25000), it's like a limitation or something, maybe some miss-configuration on MongoDB (I'm using free version), but I couldn't find any information about this problem. Any suggestion?
I'm using Python 3.7.2, PyMongo 3.9.0, MongoDB 4.2.0 Community Edition and MongoDB Compass Community 1.19.6
My Python script (example of code):
class Save2DB:
    def __init__(self):
        self.connect()

    def connect(self):
        self.collection = pymongo.MongoClient()[db_name][collection_name]

    def write(self, info):
        self.coll_id = self.collection.insert_one(info.__dict__).inserted_id

class User:
    def __init__(self, line):
        self.name = line[10:125].strip()
        self.address = line[125:225].strip()
        self.phone = line[225:234].strip()
        self.email = line[234:275].strip()

if __name__ == "__main__":
    print('\nFile: ' + fileName)
    fr = open(dirPath + os.sep + fileName, 'r', encoding='mbcs')
    lines = 0
    for line in fr:
        lines += 1
        line.strip()
        user = User(line)
        db = Save2DB()
        savedId = db.write(user)
        if lines % 1000 == 0:
            print('Users: ' + str(lines), end='\r')
    print()


text:
Q: Iterate dictionary inside list which is inside string I have a string as :-
    '[{
                  "@context": "http://database.org",
                  "mainEntityOfPage":"https://www.nyttimes.com/world/world_army.html",
                  "@type": "NewsArticle",
                  "text": "Now, eight months later, the $23,000 he invested in several digital tokens is worth about $4,000,
and he is clearheaded about what happened.

    "I got too caught up in the fear of missing out and trying to make a quick buck," he said last week. "The losses have pretty much left me financially ruined.""}]'

In order to iterate dictionary inside string. I first tring to remove quotes from  string as:
string=eval(string)

It gives me the error as
    "text": "Now, eight months later, the $23,000 he invested in several digital tokens is worth about $4,000,
        and he is clearheaded about what happened.
                                                   ^
        SyntaxError: EOL while scanning string literal

what does it exactly means?

A: You are probably getting the error because of the new line character.
Try:
import re
import json
s = '''[{
                  "@context": "http://database.org",
                  "mainEntityOfPage":"https://www.nyttimes.com/world/world_army.html",
                  "@type": "NewsArticle",
                  "text": "Now, eight months later, the $23,000 he invested in several digital tokens is worth about $4,000, and he is clearheaded about what happened.

    "I got too caught up in the fear of missing out and trying to make a quick buck," he said last week. "The losses have pretty much left me financially ruined.""}]'''

print( json.loads(re.sub(r"\n", "", s)) )   #or  json.loads(s.replace('\n', ''))

Output:
[{u'@context': u'http://database.org',
  u'@type': u'NewsArticle',
  u'mainEntityOfPage': u'https://www.nyttimes.com/world/world_army.html',
  u'text': u'Now, eight months later, the $23,000 he invested in several digital tokens is worth about $4,000, and he is clearheaded about what happened.    \u201cI got too caught up in the fear of missing out and trying to make a quick buck,\u201d he said last week. \u201cThe losses have pretty much left me financially ruined.\u201d'}]

A: Here string evaluation facing EOL - End of Line in the given string. Below code may solve your issue.
string=string.rstrip()

Python String rstrip() The rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). The rstrip() removes characters from the right based on the argument (a string specifying the set of characters to be removed).

A: The main issue you are facing is new line. You need to replace the newline character first, then do eval. Check the below example.
from pprint import pprint

b = '''[{
                  "@context": "http://database.org",
                  "mainEntityOfPage":"https://www.nyttimes.com/world/world_army.html",
                  "@type": "NewsArticle",
                  "text": "Now, eight months later, the $23,000 he invested in several digital tokens is worth about $4,000,
and he is clearheaded about what happened.
    "I got too caught up in the fear of missing out and trying to make a quick buck," he said last week. "The losses have pretty much left me financially ruined.""}]'''
x= eval(b.replace('\n', ' '))
print(type(x))
pprint(x)

output:
<class 'list'>
[{'@context': 'http://database.org',
  '@type': 'NewsArticle',
  'mainEntityOfPage': 'https://www.nyttimes.com/world/world_army.html',
  'text': 'Now, eight months later, the $23,000 he invested in several digital '
          'tokens is worth about $4,000,  and he is clearheaded about what '
          'happened.     "I got too caught up in the fear of missing out and '
          'trying to make a quick buck," he said last week. "The losses have '
          'pretty much left me financially ruined."'}]

As mentioned by FHTMitchell :
You should not use eval because of the points mentioned here
UPDATE CODE WITHOUT EVAL:
import json
from pprint import pprint

b = '''[{
                  "@context": "http://database.org",
                  "mainEntityOfPage":"https://www.nyttimes.com/world/world_army.html",
                  "@type": "NewsArticle",
                  "text": "Now, eight months later, the $23,000 he invested in several digital tokens is worth about $4,000,
and he is clearheaded about what happened.
    "I got too caught up in the fear of missing out and trying to make a quick buck," he said last week. "The losses have pretty much left me financially ruined.""}]'''
x= json.loads(b.replace('\n', ' '))
print(type(x))
pprint(x)

Output:
<class 'list'>
[{'@context': 'http://database.org',
  '@type': 'NewsArticle',
  'mainEntityOfPage': 'https://www.nyttimes.com/world/world_army.html',
  'text': 'Now, eight months later, the $23,000 he invested in several digital '
          'tokens is worth about $4,000,  and he is clearheaded about what '
          'happened.     "I got too caught up in the fear of missing out and '
          'trying to make a quick buck," he said last week. "The losses have '
          'pretty much left me financially ruined."'}]


text:
Q: Unity C# Base/Child variable call In the code below, The player will click on a item within the inventory, and the code's purpose is IF the item is a item(base) type of food(type of item), then I want to call a method within the Food script. I want to be able to call a function from within another class passing in a float from (food).
public void UseItem(){
    if (item != null) {
        if (item is Food) {//checking when i click to see if item is of type food
            PHH.Heal(hpToHealWhenAte);//here is where the problem is
        } else {
            item.Use ();
        }
    }
}

Food
public class Food : Item {
    public float healthHealedOnUse;
}

A: Cast item to Food type then call the function with the healthHealedOnUse variable: PPH.Heal(((Food)item).healthHealedOnUse)
This is called Down-Casting (casting from a base-class to a child-class)
public void UseItem(){
        if (item != null) {
            if (item is Food) { //checking if item is Food type..
                PHH.Heal(((Food)item).healthHealedOnUse); //Cast item to Food..
            } else {
                item.Use ();
            }
        }
    }

Another way of casting would also look like:  (item as Food).healthHealedOnUse..
The ((Food)item) (C-Style cast) would throw an exception if item cannot be casted to Food.. (item as Food) as style cast is known as a safe-cast and will return null if item cannot be casted to Food.

A: Method Overrides
Your base Item class:
public class Item {
    public virtual void Use(Player PHH) {
    }
}

And your Food class:
public class Food : Item {
    public float healthHealedOnUse;

    public override void Use(Player PHH) {
        PHH.Heal(healthHealedOnUse);
    }
}

Your UseItem method:
public void UseItem(){
    if (item != null) {
        item.Use(PHH);
    }
}


text:
Q: personal messaging system not working I'm adding a Personal messaging system to my site. I have 2 tables: one for users and one for messages. I have 3 php files, one to see the list of your messages, one to make a new one and one to read the file.
The databases are working well, but the list does not show anything (0 messages). can anybody see the error? I guess it should be in one of my queries. Thanks
First file list_pm.php:
 <?php
    //We check if the user is logged
    if(isset($_SESSION['id']))
{
//We list his messages in a table

//Two queries are executes, one for the unread messages and another for read messages

$req1 = mysqli_query($link,'select m1.id, m1.title, m1.timestamp, count(m2.id) as reps, users.id as userid, users.email from pm as m1, pm as m2,users where ((m1.user1="'.$_SESSION['userid'].'" and m1.user1read="no" and users.id=m1.user2 ) or (m1.user2="'.$_SESSION['userid'].'" and m1.user2read="no" and users.id=m1.user1)) and m1.id2="1" and m2.id=m1.id group by m1.id order by m1.id desc');

$req2 = mysqli_query($link,'select m1.id, m1.title, m1.timestamp, count(m2.id) as reps, users.id as userid, users.email from pm as m1, pm as m2,users where ((m1.user1="'.$_SESSION['userid'].'" and m1.user1read="yes" and users.id=m1.user2) or (m1.user2="'.$_SESSION['userid'].'" and m1.user2read="yes" and users.id=m1.user1)) and m1.id2="1" and m2.id=m1.id group by m1.id order by m1.id desc');

?>

This is the list of your messages:

New PM

Unread Messages(<?php echo intval(mysqli_num_rows($req1)); ?>):

        Title
        Nb. Replies
        Participant
        Date of creation

<?php

//We display the list of unread messages

while($dn1 = mysqli_fetch_array($req1))
{
?>

        <a href="read_pm.php?id=<?php echo $dn1['id']; ?>"><?php echo htmlentities($dn1['title'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo $dn1['reps']-1; ?>
        <a href="profile.php?id=<?php echo $dn1['userid']; ?>"><?php echo htmlentities($dn1['email'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo date('Y/m/d H:i:s' ,$dn1['timestamp']); ?>

<?php
}
//If there is no unread message we notice it
if(intval(mysqli_num_rows($req1))==0)
{
?>

        You have no unread message.

<?php
}
?>

Read Messages(<?php echo intval(mysqli_num_rows($req2)); ?>):

        Title
        Nb. Replies
        Participant
        Date or creation

<?php
//We display the list of read messages
while($dn2 = mysqli_fetch_array($req2))
{
?>

        <a href="read_pm.php?id=<?php echo $dn2['id']; ?>"><?php echo htmlentities($dn2['title'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo $dn2['reps']-1; ?>
        <a href="profile.php?id=<?php echo $dn2['userid']; ?>"><?php echo htmlentities($dn2['email'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo date('Y/m/d H:i:s' ,$dn2['timestamp']); ?>

<?php
}
//If there is no read message we notice it
if(intval(mysqli_num_rows($req2))==0)
{
?>

        You have no read message.

<?php
}
?>

<?php
}
else
{
        echo 'You must be logged to access this page.';
}
?>

//Second file to make a new pm : new_pm.php
<?php
//We check if the user is logged
if(isset($_SESSION['id']))
{
$form = true;
$otitle = '';
$orecip = '';
$omessage = '';
//We check if the form has been sent
if(isset($_POST['title'], $_POST['recip'], $_POST['message']))
{
        $otitle = $_POST['title'];
        $orecip = $_POST['recip'];
        $omessage = $_POST['message'];

        //We remove slashes depending on the configuration

            if(get_magic_quotes_gpc())
        {
                //$otitle = stripslashes($otitle);
                //$orecip = stripslashes($orecip);
                //$omessage = stripslashes($omessage);
        }

        //We check if all the fields are filled

        if($_POST['title']!='' and $_POST['recip']!='' and $_POST['message']!='')
        {
                //We protect the variables

               // $title = mysqli_real_escape_string($otitle);
                //$recip = mysqli_real_escape_string($orecip);
               // $message = mysqli_real_escape_string(nl2br(htmlentities($omessage, ENT_QUOTES, 'UTF-8')));

                //We check if the recipient exists

                $dn1 = mysqli_fetch_array(mysqli_query($link,'select count(id) as recip, id as recipid , (select count(*) from pm) as npm from users where email ="'.$orecip.'"'));

                if($dn1['recip']==1)

                {
                        //We check if the recipient is not the actual user

                        if($dn1['recipid']!=$_SESSION['id'])
                        {
                                $id = $dn1['npm']+1;

                                //We send the message

                                if(mysqli_query($link,'insert into pm (id, id2, title, user1, user2, message, timestamp, user1read, user2read)values("'.$id.'", "1", "'.$otitle.'", "'.$_SESSION['id'].'", "'.$dn1['recipid'].'", "'.$omessage.'", "'.time().'", "yes", "no")'))
                                {
?>

The message has successfully been sent.

List of my Personal messages

<?php
                                        $form = false;
                                }
                                else
                                {
                                        //Otherwise, we say that an error occured
                                        $error = 'An error occurred while sending the message';
                                }
                        }
                        else
                        {
                                //Otherwise, we say the user cannot send a message to himself
                                $error = 'You cannot send a message to yourself.';
                        }
                }
                else
                {
                        //Otherwise, we say the recipient does not exists
                        $error = 'The recipient does not exists.';
                }
        }
        else
        {
                //Otherwise, we say a field is empty
                $error = 'A field is empty. Please fill of the fields.';
        }
}
elseif(isset($_GET['recip']))
{
        //We get the username for the recipient if available
        $orecip = $_GET['recip'];
}
if($form)
{
//We display a message if necessary
if(isset($error))
{
        echo '
'.$error.'
';
}
//We display the form
?>

New Personal Message

    <form action="new_pm.php" method="post">
                Please fill the following form to send a Personal message.

        Title<input type="text" value="<?php echo htmlentities($otitle, ENT_QUOTES, 'UTF-8'); ?>" id="title" name="title" />

        Recipient(UserEmail)<input type="text" value="<?php echo htmlentities($orecip, ENT_QUOTES, 'UTF-8'); ?>" id="recip" name="recip" />

        Message<textarea cols="40" rows="5" id="message" name="message"><?php echo htmlentities($omessage, ENT_QUOTES, 'UTF-8'); ?></textarea>

        <input type="submit" value="Send" />
    </form>

<?php
}
}
else
{
        echo '
You must be logged to access this page.
';
}
?>

and the last one to read the message read_pm.php:
<?php
//We check if the user is logged
if(isset($_SESSION['id']))
{
//We check if the ID of the discussion is defined
if(isset($_GET['id']))
{
$id = intval($_GET['id']);

//We get the title and the narators of the discussion

$req1 = mysqli_query($link,'select title, user1, user2 from pm where id="'.$id.'" and id2="1"');
$dn1 = mysqli_fetch_array($req1);

//We check if the discussion exists

if(mysqli_num_rows($req1)==1)
{
//We check if the user have the right to read this discussion

if($dn1['user1']==$_SESSION['id'] or $dn1['user2']==$_SESSION['id'])
{
//The discussion will be placed in read messages

if($dn1['user1']==$_SESSION['id'])
{
        mysqli_query($link,'update pm set user1read="yes" where id="'.$id.'" and id2="1"');
        $user_partic = 2;
}
else
{
        mysqli_query($link,'update pm set user2read="yes" where id="'.$id.'" and id2="1"');
        $user_partic = 1;
}

//We get the list of the messages

$req2 = mysqli_query($link,'select pm.timestamp, pm.message, users.id as userid, users.username, users.avatar from pm, users where pm.id="'.$id.'" and users.id=pm.user1 order by pm.id2');

//We check if the form has been sent

if(isset($_POST['message']) and $_POST['message']!='')
{
        $message = $_POST['message'];

        //We remove slashes depending on the configuration

        if(get_magic_quotes_gpc())
        {
                $message = stripslashes($message);
        }
        //We protect the variables

        $message = mysqli_real_escape_string(nl2br(htmlentities($message, ENT_QUOTES, 'UTF-8')));

        //We send the message and we change the status of the discussion to unread for the recipient

        if(mysqli_query($link,'insert into pm (id, id2, title, user1, user2, message, timestamp, user1read, user2read)values("'.$id.'", "'.(intval(mysqli_num_rows($req2))+1).'", "", "'.$_SESSION['userid'].'", "", "'.$message.'", "'.time().'", "", "")') and mysqli_query($link,'update pm set user'.$user_partic.'read="yes" where id="'.$id.'" and id2="1"'))
        {
?>

Your message has successfully been sent.

<a href="read_pm.php?id=<?php echo $id; ?>">Go to the discussion

<?php
        }
        else
        {
?>

An error occurred while sending the message.

<a href="read_pm.php?id=<?php echo $id; ?>">Go to the discussion

<?php
        }
}
else
{
//We display the messages
?>

<?php echo $dn1['title']; ?>

        User
        Message

<?php
while($dn2 = mysql_fetch_array($req2))
{
?>

        <?php
if($dn2['avatar']!='')
{
        echo '';
}
?>
<a href="profile.php?id=<?php echo $dn2['userid']; ?>"><?php echo $dn2['email']; ?>

Sent: <?php echo date('m/d/Y H:i:s' ,$dn2['timestamp']); ?>

        <?php echo $dn2['message']; ?>

<?php
}
//We display the reply form
?>

Reply

    <form action="read_pm.php?id=<?php echo $id; ?>" method="post">
        Message

        <textarea cols="40" rows="5" name="message" id="message"></textarea>

        <input type="submit" value="Send" />
    </form>

<?php
}
}
else
{
        echo '
You dont have the rights to access this page.
';
}
}
else
{
        echo '
This discussion does not exists.
';
}
}
else
{
        echo '
The discussion ID is not defined.
';
}
}
else
{
        echo '
You must be logged to access this page.
';
}
?>

the table structure:
CREATE TABLE `pm` (
  `id` bigint(20) NOT NULL,
  `id2` int(11) NOT NULL,
  `title` varchar(256) NOT NULL,
  `user1` bigint(20) NOT NULL,
  `user2` bigint(20) NOT NULL,
  `message` text NOT NULL,
  `timestamp` int(10) NOT NULL,
  `user1read` varchar(3) NOT NULL,
  `user2read` varchar(3) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Really appreciate the help guys


text:
Q: Write Xpath to select field based on upper field I am not xpath expert and tried many solution from internet but still unable to select particular field.
Html :

                Category

Category

                            <input type="text" class="gwt-TextBox WKWP" autocomplete="off" placeholder="search" tabindex="0" aria-invalid="false" aria-labelledby="56$383927--uid80-formLabel" aria-required="true">
<svg viewBox="0 0 24 24" role="presentation" focusable="false" class="wd-icon-x wd-icon" height="24" width="24" xmlns="http://www.w3.org/2000/svg">
    <g class="wd-icon-container" fill-rule="evenodd">
        <g>
            <path class="wd-icon-fill" d="M5.996 4.582a.5.5 0 0 0-.717-.003l-.7.7a.504.504 0 0 0 .003.717L10.586 12l-6.004 6.004a.5.5 0 0 0-.003.717l.7.7c.197.197.514.2.717-.003L12 13.414l6.004 6.004a.5.5 0 0 0 .717.003l.7-.7a.504.504 0 0 0-.003-.717L13.414 12l6.004-6.004a.5.5 0 0 0 .003-.717l-.7-.7a.504.504 0 0 0-.717.003L12 10.586 5.996 4.582z"/>
        </g>
    </g>
</svg>

<svg viewBox="0 0 24 24" role="presentation" focusable="false" class="wd-icon-prompts wd-icon" height="24" width="24" xmlns="http://www.w3.org/2000/svg">
    <g class="wd-icon-container" fill-rule="evenodd">
        <g>
            <path class="wd-icon-fill" d="M4 6.505C4 6.226 4.214 6 4.505 6h.99c.279 0 .505.214.505.505v.99A.497.497 0 0 1 5.495 8h-.99A.497.497 0 0 1 4 7.495v-.99zm0 5c0-.279.214-.505.505-.505h.99c.279 0 .505.214.505.505v.99a.497.497 0 0 1-.505.505h-.99A.497.497 0 0 1 4 12.495v-.99zm0 5c0-.279.214-.505.505-.505h.99c.279 0 .505.214.505.505v.99a.497.497 0 0 1-.505.505h-.99A.497.497 0 0 1 4 17.495v-.99zm4-10C8 6.226 8.229 6 8.5 6h11c.276 0 .5.214.5.505v.99a.506.506 0 0 1-.5.505h-11a.495.495 0 0 1-.5-.505v-.99zm0 5c0-.279.229-.505.5-.505h11c.276 0 .5.214.5.505v.99a.506.506 0 0 1-.5.505h-11a.495.495 0 0 1-.5-.505v-.99zm0 5c0-.279.229-.505.5-.505h11c.276 0 .5.214.5.505v.99a.506.506 0 0 1-.5.505h-11a.495.495 0 0 1-.5-.505v-.99z"/>
        </g>
    </g>
</svg>

                                <svg viewBox="0 0 24 24" role="presentation" focusable="false" class="wd-icon-search wd-icon" height="24" width="24" xmlns="http://www.w3.org/2000/svg">
                                    <g class="wd-icon-container" fill-rule="evenodd">
                                        <g fill-rule="nonzero">
                                            <path class="wd-icon-background" d="M16.896 14.775l3.643 3.642a.995.995 0 0 1-.004 1.418l-.7.7c-.39.39-1.032.39-1.418.004l-3.642-3.643a7 7 0 1 1 2.121-2.121zM11 16a5 5 0 1 0 0-10 5 5 0 0 0 0 10z" />
                                            <path class="wd-icon-fill" d="M17.32 15.906l2.859 2.858a.5.5 0 0 1 .003.717l-.7.7a.5.5 0 0 1-.718-.002l-2.858-2.86a8 8 0 1 1 1.414-1.414zM11 17a6 6 0 1 0 0-12 6 6 0 0 0 0 12z" />
                                        </g>
                                    </g>
                                </svg>

search input

<svg viewBox="0 0 24 24" role="presentation" focusable="false" class="wd-icon-prompts wd-icon" height="24" width="24" xmlns="http://www.w3.org/2000/svg">
    <g class="wd-icon-container" fill-rule="evenodd">
        <g>
            <path class="wd-icon-fill" d="M4 6.505C4 6.226 4.214 6 4.505 6h.99c.279 0 .505.214.505.505v.99A.497.497 0 0 1 5.495 8h-.99A.497.497 0 0 1 4 7.495v-.99zm0 5c0-.279.214-.505.505-.505h.99c.279 0 .505.214.505.505v.99a.497.497 0 0 1-.505.505h-.99A.497.497 0 0 1 4 12.495v-.99zm0 5c0-.279.214-.505.505-.505h.99c.279 0 .505.214.505.505v.99a.497.497 0 0 1-.505.505h-.99A.497.497 0 0 1 4 17.495v-.99zm4-10C8 6.226 8.229 6 8.5 6h11c.276 0 .5.214.5.505v.99a.506.506 0 0 1-.5.505h-11a.495.495 0 0 1-.5-.505v-.99zm0 5c0-.279.229-.505.5-.505h11c.276 0 .5.214.5.505v.99a.506.506 0 0 1-.5.505h-11a.495.495 0 0 1-.5-.505v-.99zm0 5c0-.279.229-.505.5-.505h11c.276 0 .5.214.5.505v.99a.506.506 0 0 1-.5.505h-11a.495.495 0 0 1-.5-.505v-.99z"/>
        </g>
    </g>
</svg>

                Comment

Comment

                        <textarea class="gwt-TextArea WMMY WANY WBNY" data-automation-id="textAreaField" role="textbox" aria-label="Process Comment" id="56$383068--uid81-input" aria-invalid="false" tabindex="0"></textarea>

Screenshot about how field display in webpage :

I want to select Comment based on it's upper box called Category.
I have separate xpath of both :
Category :
//label[text()='Category']/../following-sibling::div//span[contains(@data-automation-id,'promptIcon')]

Comment : //label[text()='Comment']
I can not use alone xpath of Comment to select it as webpage has some other comment fields and I am getting multiple values.
So I want to select only that comment field which is following Category dropdown.
I tried some tricks with following-sibling with both fields but it did not work.

A: The idea is to check what is the common thing about both elements, and they are both li with label tags inside them, this xpath should do the work:
//li[.//label[text()="Category"]]/following-sibling::li//label[text()="Comment"]


text:
Q: Scheduled tasks invalid filter using XML I try to make a trigger using XML on the Window's task scheduler, but the tool tells me a filter is invalid and i was unable to find what is wrong.
My current XML is
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
      *[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and (Level=4 or Level=0) and Task = 12801 and (EventID=4656) ]] and
      *[EventData[Data[@Name='SubjectUserSid' and (Data='S-1-5-18')]] and
       [Data[@Name='ObjectType' and (Data=Key) ]]]

   </Select>
  </Query>
</QueryList>

When I remove
and
           [Data[@Name='ObjectType' and (Data=Key) ]]

The XML is accepted without error. As I don't understand what is wrong on my last line I'm stuck.

A: There are some missing closing square brackets around the SubjectUserSid and ObjectType attributes, the "*[EventData" missing from the last query line, and missing quotes around the Data value "Key". This works in my EventViewer:
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
      *[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and (Level=4 or Level=0) and Task = 12801 and (EventID=4656) ]] and
      *[EventData[Data[@Name='SubjectUserSid'] and (Data='S-1-5-18') ]] and
      *[EventData[Data[@Name='ObjectType'] and (Data='Key') ]]
   </Select>
  </Query>
</QueryList>


text:
Q: Log file locking issues in Batch scripting I have a batch file which starts a Java server class. The output of the Java is redirected to a log file. This batch file is stared via a windows service. Problem is this log file is becoming very huge. Since the Java server is running, it is not possible to do any modification in the Log file as it is locked. How can I create a new log file for every day?
My idea was to write another batch file which will stop the service, backup the existing log file, delete and start the service file again. Is this approach correct?
java -Xms32m -Xmx256m gtServer >> abclog.txt

Above is the code in the batch file which starts the sever
Any tips on how we could back up the file without stopping the java server?
Thanks in advance
Karthik

A: Heard about log4j?
Ok, seriously, would it be possible to use some proper logging facility? It usually provides something for this purpose like RollingFileAppender.


text:
Q: How to replace a file in the upgrade process I'm trying to build a new "update tool" for one of my programs.
Delphi XE5.
Firebird 2.5
how to replace a UDF (the file is in use)?
how to replace a file (the file is in use)?

A: You can replace a file which is in use by renaming it to a temporary name and then copying the new file. Applications having the file opened will not be affected by the rename (the file handle still pointing to the original file). Of course, once an application close the file and reopen it, it will actually close the old file and open the freshly copied file. This mays affect the application depending on what it does.


text:
Q: Isn't Kirchhoff's junction law a violation of conservation of charge? As a beginner of classical electrodynamics I am quite confused in understanding Kirchhoff's junction law or it may be the reason that I misunderstood the law of conservation of charge.Please correct me if I am wrong:-
I understood the law of  conservation of charge as follows:-
The net charge of an isolated system will always remain constant.
By isolated system I think  that it is a system in which we can't take out any charge from it as well as we can't add any charge to it.
Now considering Kirchhoff's junction law, Imagine a junction of wires at  $J$ which is a part of an electric circuit. When the switch is open then no current passes through $J$. I consider $J$ as my system. My teacher told me that the junction law is just the other form of law of conservation of charge taking junction as the system. When the switch is closed then current flows through it and when we apply the law of conservation of charge at $J$ then we arrive at the junction law.
Now my question is how can we apply law of conservation of charge at $J$ because $J$ is not an isolated system?
I don't think that it is an isolated system as when switch is turned on then we can't write the equation using law of conservation of charge. So I think that Kirchhoff's junction law violates the law of conservation of charge!  Am I correct or totally wrong?

A:
I understood the law of conservation of charge as follows:-
The net charge of an isolated system will always remain constant.

You're missing a crucial distinction between local conservation of charge and global conservation of charge. The statement as you have given it is a correct encapsulation of the global version of the principle, but electromagnetism is also subject to the local conservation of electric charge. Local conservation can hold for any arbitrary volume, whether it is isolated or not, and it says that for the total charge within the volume to change, there needs to be a flux of charge into or out of that volume.
As you correctly note, Kirchhoff's junction law does not follow from the global conservation of electric charge, which would be completely untouched if electric charge could instantaneously teleport from one part of the circuit to another. Instead, it is an expression of the local version, i.e., it embodies the principle that to get from A to B, electric charge actually needs to move along a path that joins the two.
For some more detailed explanations, see this section in Wikipedia.

And finally, it seems that you're strongly misusing the word "violation" here. There's a difference between "A does not follow from B" and "A is in direct conflict from B": the fact that B does not imply A does not mean that they're incompatible. The fact that Kirchhoff's junction law does not follow from global charge conservation doesn't mean that it represents a violation of it. (Similarly, Kirchhoff's junction law cannot be derived from relativistic invariance ─ but that doesn't mean that it is a violation of the latter!)

A: Conservation of charge is better understood as a special case of the continuity equation:
$$ \frac{\partial Q_{system}}{\partial t} = \dot{Q}_{incoming} - \dot{Q}_{outgoing} $$
This formula becomes a conversation law if $Q_{incoming}=Q_{outgoing}=0$ (i.e. the system is isolated),
$$ \frac{\partial Q_{system}}{\partial t} = 0. $$
As to not confuse the students who are new to these concepts, introduction level materials doesn't name the continuity equation, but rather talk about its results as the conversation laws. So, in this example, $J$ is indeed is not an isolated system. But, it still must obey the continuity equation.
Since there is no element capable of storing charge (i.e. a capacitive element) in $J$, $$Q_{system}=0,\ \therefore\ \frac{\partial Q_{system}}{\partial t} = 0.$$
From this, substituting into the original equation we get the Kirchhoff's junction law:
$$ I_{incoming}=I_{outgoing} $$
(since $\dot{Q} = \frac{dQ}{dt}=I$)
Your idea that this junction is not isolated is correct, but this system cannot violate conservation of charge since it is not isolated in the first place.

TL;DR: Conservation laws apply only to isolated systems. There are other laws for general (isolated or non-isolated) systems from which these can be deduced.

A: The junction is not an isolated system.  It is connected to a circuit.  Your professor may have been a little sloppy with the choice of words if they said isolated.  If we assume that no charge accumulates in the junction then what goes in must come out.  Conservation of charge is $\text{div}(\vec J) = -\frac{\partial \rho}{\partial t}$.  We are assuming that the r.h.s = 0 in the absence of any evidence to the contrary so the l.h.s = 0 and this is the junction rule.  The junction is still a "system", it's just a system that is interacting with the rest of the circuit.  The point is that it is an idealization of nature.
My small contribution to this comes in the form of addressing the assumption.  It is reasonable considering the idealizations at work.
In the 80s there was a lot of interest in a few areas of "Exotic Systems in QM".  I was working on some of these problems in graduate school with a few professors.  Two of these are of interest here.  Solving Schrodinger's equation on a graph, and solving Schrodinger's equation on curved 1-dim and 2-dim spaces where the electron is effectively trapped by a boundary condition by a limiting process.  In these cases you find effective potential wells can emerge due to the geometry of the bends and the graph loops.  I'm not trying to say that this contradicts the assumption that charge in not trapped in the junction as that is a fair idealization.  And large scale circuits probably do not exhibit this type of trapping.  I just this this question is a nice place to bring it up.  In reality some defect in the circuitry could create an effective capacitance in a junction.  Charge would probably grow a bit then break away.  This would be observable as a small instability in the measured current on small (I'm assuming it would happen fast) time scales.
Rarely does nature follow these ideal system models.  But we study them to understand the basic principles in the laws of physics and they are useful for building up an idea of what is happening in real systems.

A: Kirchhoff's current law can be stated that the algebraic sum of the currents flowing into a node (junction) is zero, or
$$\sum i_{in}=\sum i_{out}$$
Electric current $i(t)$ through a surface of a conductor is defined as the rate of charge transport through that surface of the conductor, or
$$i(t)=\frac {dq(t)}{d(t)}$$
Where $dq(t)$ denotes instantaneous charge.
Therefore Kirchhoff's current law is a statement of conservation of charge since it is saying that charge cannot increase or decrease at a node.
Hope this helps.

A: Conceptual answer.
Actually you are somewhat wrong in taking your system.
You have just taken the junction but you forgot the battery that is supplying power.
So when the battery is supplying power to the junction your idea of just considering 'Junction' as a isolated system is flawed. Because there is an external intervention in your system via the battery
If you want a fully isolated system you will have to consider the whole electric circuit. *Including your source.

After answering a comment I got another way to explain this.
In case you still want to consider junction as a system then you must look at basics of conduction.
When a metal is conducting the number of electrons it has is still the same (it is just the motion of electrons that you recognise as current).
Hence I would like to say that as number of electrons in the conductor is constant the charge is still constant, it is just moving.
As the conservation of charge specifies that there is no creation or destruction of charge hence the law still holds.


text:
Q: Close a Window Using pyatspi Is there anyway to close a window using accessibility in pyatspi? Using accerciser, I can't seem to find a component for the top bar with the maximize, minimize, and close buttons. Is this possible?
I'm currently working on Ubuntu. I want this to work on any Linux system where the GNOME desktop is used.
Note: I want to tag this with either atspi or pyatspi, but I don't have enough reputation to do that. Can someone do it for me?
Right now, it seems that Alt+F4 closes any window on the GNOME desktop. So I'm trying to simulate the Alt+F4 key combination using pyatspi. I can simulate key strokes by looking at the values in keysymdef.h in Xlib, but I can't seem to use any modifiers.
Is there anyway to generate Alt+F4 using at-spi? Will this solution even work?

A: I am new to AT-SPI, so please do not treat it as a reference. I didn't find an AT-SPI method either and I send ALT+F4. First line grabs focus (getChildAtIndex() is to traverse from Application to a window). Then goes: ALT down, F4 press, ALT up.
app.getChildAtIndex(0).getChildAtIndex(0).queryComponent().grabFocus()
pyatspi.Registry.generateKeyboardEvent(64, None, pyatspi.KEY_PRESS)
pyatspi.Registry.generateKeyboardEvent(70, None, pyatspi.KEY_PRESSRELEASE)
pyatspi.Registry.generateKeyboardEvent(64, None, pyatspi.KEY_RELEASE)


text:
Q: simplest way to produce a video of a sequence of plots with python? I would like to start with a sequence of arrays of 1s and 0s (each array representing a 2 dimensional pattern of on off pixels) and create a simple black and white video of this sequence.  controling pixel size and image size and length of time per frame would be good too.
basically it would be a video of a program to execute a cellular automaton.
is there a way to do this without first creating 100 or so image files and then constructing the video from them? (say with avconv?)
if not, what is the simplest way to create each image file?
i would like to use the simplest tools possible without a 1000 bells and whistles.  (i'd like to avoid having to wade through matplotlib or pygame or pil etc..i have trouble wading through the documentation)
adding text and audio would be a later step.  i just want the bare bones first  thanks.

A: The easiest way is probably to create an animated gif.

*

*Write each sequence to a jpeg.

*Use the ImageMagick convert function as mentioned in this post:

how to create gif animation from a stack of jpgs
When you write the image, let 1 = white (r=255, g=255, b=255) and 0 = black (r=0, g=0, b=0).
You'll have to go through a little documentation, but it's not as bad as you think.  Besides, if it was easy, we wouldn't be asking questions on S.O. ;-)

A: Unfortunately, matplotlib and Pillow (the replacement for PIL) are two of the best modules that come to mind for creating images and animating them. Combine them with a NumPy array of your pixels, and you have a very straightforward way of proceeding. Assuming you already know how to program in Python, the learning curve isn't too steep, once you grasp how everything is laid out.
I haven't delved as deeply into Pillow yet, but I know from personal experience that the matplotlib documentation actually isn't too bad, and there are a ton of examples on their website. It has interfaces for ffmpeg, avconv, and other converters, so if you're already familiar with them you're halfway there. And remember, if you have specific questions along the way, StackOverflow is always here :)
Good luck!


text:
Q: the BST search method ((iteratively)) returning the node containing the searched value and its predecessor Okay, I've already written several methods related to my problem. Right now I have two methods that are written using recursion (addBSTRecursion (int element) and searchBSTRecursion (int element)). And now I need implement (iteratively) the BST search method (Pair<BinaryTreeNode, BinaryTreeNode> searchBST(int element)) returning the node containing the searched value and its predecessor.

*

*if the searched element is not in the tree, the first element of the pair is null.

*if the first element of the pair is a root (it has no predecessor), then the second element of the pair is null.
Here is my class Pair:

public class Pair<T1, T2> {
    public T1 first;
    public T2 second;

    public Pair(T1 a, T2 b) {
        first = a;
        second = b;
    }
}

This is how I managed to implement method (Pair<BinaryTreeNode, BinaryTreeNode> searchBST(int element)), but unfortunately it does not work as expected.
@Override
public Pair<BinaryTreeNode, BinaryTreeNode> searchBST(int element) {
    int current = 0;
    while (element != data) {
        if (element < data) {
            current = left.data;
        } else {
            current = right.data;
        }
    }
    Pair pair = new Pair(element, current);
    return pair;
}

To be honest, I don't know yet how to correctly implement this method, I will be glad to any hints. And also at the bottom I add all my previous classes.
public abstract class BinaryTreeNode {
    protected int data; // value stored in the node
    protected BinaryTreeNode left, right; // left and right sub-trees

    // constructor
    public BinaryTreeNode(int data) {
        this.data = data;
    }

    // recursively adds an item to the BST
    // @param new data to be stored in the new node
    public abstract void addBSTRecursion(int element);

    // prints the tree
    // for example, for a tree:
    //        7
    //    6        8
    // 2     7  4     9
    //
    // write:
    //
    //      2
    //   6
    //      7
    // 7
    //      4
    //   8
    //      9

    // method pseudocode
    // if there is a left subtree then print the left one (recursive call)
    // write out gaps (depending on level), write out data, go to new line
    // if it is right, print the right one (recursive call)
    // @param level the distance of the node from the root. We start from 0.
    public abstract void print(int level);

    // recursive searches the BST.
    // returns true if it finds an element with the given value
    // @param searched value searched
    // @return true if the given value is in the tree, false otherwise
    public abstract boolean searchBSTRecursion(int element);

    // iterative lookup of values in the BST
    // returns a pair: node containing the searched element and its predecessor.
    // if the searched element is not in the tree, the first element of the pair is null.
    // if the first element of the pair is a root (it has no predecessor), then the second element of the pair is null.
    // @param searched value searched
    // @return pair of nodes: the first is the node containing the value searched for, or null if not found;
    // the second element of the pair is the parent of the node (or null if the value is at the root of the tree)
    public abstract Pair < BinaryTreeNode, BinaryTreeNode > searchBST(int element);
}

public class Node extends BinaryTreeNode {
    public Node(int data) {
        super(data);
    }

    @Override
    public void addBSTRecursion(int element) {
        Node node = new Node(element);
        if (element < data) {
            if (left != null) {
                left.addBSTRecursion(element);
            } else {
                left = node;
            }
        } else {
            if (right != null) {
                right.addBSTRecursion(element);
            } else {
                right = node;
            }
        }
    }

    @Override
    public void print(int level) {
        if (left != null) {
            left.print(level + 4);
        }
        for (int i = 0; i < level; i++) {
            System.out.print(" ");
        }

        System.out.print(data + "\n");

        if (right != null) {
            right.print(level + 4);
        }
    }

    @Override
    public boolean searchBSTRecursion(int element) {
        if (element == data) {
            return true;
        } else if (element < data) {
            if (left != null && left.searchBSTRecursion(element)) {
                return true;
            } else {
                return false;
            }
        } else {
            if (right != null && right.searchBSTRecursion(element)) {
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public Pair<BinaryTreeNode, BinaryTreeNode> searchBST(int element) {
        int current = 0;
        while (element != data) {
            if (element < data) {
                current = left.data;
            } else {
                current = right.data;
            }
        }
        Pair pair = new Pair(element, current);
        return pair;
    }

}

public class Main {

    public static void main(String[] args) {
        Node node = new Node(8);

        node.addBSTRecursion(3);
        node.addBSTRecursion(10);

        node.addBSTRecursion(1);
        node.addBSTRecursion(6);

        node.addBSTRecursion(14);

        node.addBSTRecursion(4);
        node.addBSTRecursion(7);

        node.addBSTRecursion(13);

        node.print(0);

        System.out.print(node.searchBSTRecursion(15));
    }
}


text:
Q: How to filter out objects that do not have a relationship with another form in Django? I have two samples in an application built using Django:
class User(models.Model):
    email = models.EmailField()

class Product(models.Model):
    user = models.ForeignKey(User)

I want to filter out all users who don't have any products in the store.
How do I do this?

A: User's model can access Product's objects,  for this situation you can filter all users that product_set is null,
User.objects.filter(product__isnull=True)

A: This seems the simplest:
user_ids_with_product = [product.user_id for product
                         in Product.objects.all()]
Users.objects.exclude(id__in=user_ids_with_product)


text:
Q: preflight check with SCNetworkReachabilityCreateWithAddress using a zero IPv6 address I have a library that mimics Apple's own Reachability.m and its method reachabilityForInternetConnection to do a preflight check like this:
struct sockaddr_in zeroSockaddrin;
bzero(&zeroSockaddrin, sizeof(zeroSockaddrin));
zeroSockaddrin.sin_len = sizeof(zeroSockaddrin);
zeroSockaddrin.sin_family = AF_INET;

SCNetworkReachabilityRef networkReachabilityRef = SCNetworkReachabilityCreateWithAddress(allocator, (const struct sockaddr *)&zeroSockaddrin);

SCNetworkReachabilityFlags flags = 0;
SCNetworkReachabilityGetFlags(networkReachabilityRef, &flags);

Now I'm trying to comply with Apple's new guideline to support IPv6 only networks.
https://developer.apple.com/library/prerelease/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/UnderstandingandPreparingfortheIPv6Transition/UnderstandingandPreparingfortheIPv6Transition.html#//apple_ref/doc/uid/TP40010220-CH213-SW25
According to the above, I should

*

*Avoid preflighting network reachability

*Use SCNetworkReachabilityCreateWithName instead of SCNetworkReachabilityCreateWithAddress.

However For backward-compatibility reasons I would like to keep my preflight check, and I'd also like to keep using SCNetworkReachabilityCreateWithAddress to avoid the lag introduced by the DNS lookup of SCNetworkReachabilityCreateWithName.  So I simply changed the sockaddr_in to sockaddr_in6 like this:
struct sockaddr_in6 zeroSockaddrin;
bzero(&zeroSockaddrin, sizeof(zeroSockaddrin));
zeroSockaddrin.sin6_len = sizeof(zeroSockaddrin);
zeroSockaddrin.sin6_family = AF_INET6;

SCNetworkReachabilityRef networkReachabilityRef = SCNetworkReachabilityCreateWithAddress(allocator, (const struct sockaddr *)&zeroSockaddrin);

SCNetworkReachabilityFlags flags = 0;
SCNetworkReachabilityGetFlags(networkReachabilityRef, &flags);

If I do this then I would only get 0 in "flags" regardless of whether my device is already connected via 4G or wifi.
I tried replacing sockaddr_in6 with sockaddr_storage - same results.  It seems like I can only get valid SCNetworkReachabilityFlags via using sockaddr_in or by using SCNetworkReachabilityCreateWithName with a proper host name.
Is there any reason why I'm not getting correct SCNetworkReachabilityFlags with an zero IPv6 address?


text:
Q: how to call a java class method to return an excel file in Apache OFBiz? I am planning to do this implementation from a widget. User would input an ID to the controller, then to the java class which would generate a report and send an excel file to the user.
But ofbiz seems to be a bit overwhelming. Can you please give me some ideas to implement this?

A: There are different ways for doing that, and it really depends on what you want to do exactly.
The simplest way of doing that would be:
on the ofbiz UI create a link/button pointing to the controller. That is simple if you already have a screen created with widgets.
Then add a java event to the controller. Your event method will get as parameters servlet request and response objects. Inside that method create your excel file, prepare it, and write it to response object's output stream.
The response type in your controller entry should be "none" because you are manually writing the response in your event. So you don't need to render a new screen or anything.
The effect will be that, whenever the user clicks on the button, it will call the controller, which in turn will return the excel file.
HTH


text:
Q: How to programmatically start an application on a specific monitor on Windows 10? I want to write a program that needs sometimes to start processes of another applications (mainly Sumatra PDF) on Windows 10, version 1803 (April 2018 Update).
These applications should be started on a specific monitor. I also want to be able to close the processes when needed.
The preferred languages are C# and Java, but any help is appreciated.
EDIT
I've tried to use the ShellExecuteExW function suggested by IInspectable in C++ code directly, but it doesn't work, as applications appear on the main monitor. I must have certainly made a mistake as I am absolutely new to WinAPI and know very little C++.
#include <Windows.h>

HMONITOR monitors[2]; // As it's only a test and I have currently only two monitors.
int monitorsCount = 0;

BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdc, LPRECT lprect, LPARAM lparam)
{
    monitors[monitorsCount] = hMonitor;
    monitorsCount++;

    return TRUE;
}

int main()
{
    EnumDisplayMonitors(NULL, NULL, Monitorenumproc, 0);

    _SHELLEXECUTEINFOW info;
    ZeroMemory(&info, sizeof(info));
    info.cbSize = sizeof(info);
    info.fMask = SEE_MASK_HMONITOR;
    //info.lpVerb = L"open";
    info.lpFile = L"C:\\Windows\\System32\\cmd.exe";
    info.nShow = SW_SHOW;
    info.hMonitor = monitors[1]; // Trying to start on the second monitor.

    ShellExecuteExW(&info);

    return 0;
}

A: As suggested by others, this is intended behavior of Windows and for the good reasons.
Also, you can not rely on default window placement atleast for SumatraPDF, since it surely does not use CW_USEDEFAULT, and instead stores these values in :

%USERPROFILE%\AppData\Roaming\SumatraPDF\SumatraPDF-settings.txt

There are multiple options though:

*

*Use third party tools that monitor top level windows and based on pre-configured rules moves them to specified display. E.g. DisplayFusion, etc.

*Use ligher weight solutions like AutoHotkey/AutoIt.

*Try and do this in code itself. Following is a working solution. I smoke tested on my box.

Disclaimer: I have not written the entire code, for saving time I pulled it up from couple of sources, tweaked it, glued it together, and tested with SumantraPDF. Do also note, that this code is not of highest standards, but solves your problem, and will act as a can-be-done example.
C++ code: (scroll down for C# code)
#include <Windows.h>
#include <vector>

// 0 based index for preferred monitor
static const int PREFERRED_MONITOR = 1;

struct ProcessWindowsInfo
{
    DWORD ProcessID;
    std::vector<HWND> Windows;

    ProcessWindowsInfo(DWORD const AProcessID)
        : ProcessID(AProcessID)
    {
    }
};

struct MonitorInfo
{
    HMONITOR hMonitor;
    RECT rect;
};

BOOL WINAPI EnumProcessWindowsProc(HWND hwnd, LPARAM lParam)
{
    ProcessWindowsInfo *info = reinterpret_cast<ProcessWindowsInfo*>(lParam);
    DWORD WindowProcessID;

    GetWindowThreadProcessId(hwnd, &WindowProcessID);

    if (WindowProcessID == info->ProcessID)
    {
        if (GetWindow(hwnd, GW_OWNER) == (HWND)0 && IsWindowVisible(hwnd))
        {
            info->Windows.push_back(hwnd);
        }
    }

    return true;
}

BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdc, LPRECT lprect, LPARAM lParam)
{
    std::vector<MonitorInfo> *info = reinterpret_cast<std::vector<MonitorInfo>*>(lParam);

    MonitorInfo monitorInfo = { 0 };

    monitorInfo.hMonitor = hMonitor;
    monitorInfo.rect = *lprect;

    info->push_back(monitorInfo);
    return TRUE;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{

    // NOTE: for now this code works only when the window is not already visible
    // could be easily modified to terminate existing process as required

    SHELLEXECUTEINFO info = { 0 };
    info.cbSize = sizeof(info);
    info.fMask = SEE_MASK_NOCLOSEPROCESS;
    info.lpFile = L"C:\\Program Files\\SumatraPDF\\SumatraPDF.exe";
    info.nShow = SW_SHOW;

    std::vector<MonitorInfo> connectedMonitors;

    // Get all available displays
    EnumDisplayMonitors(NULL, NULL, Monitorenumproc, reinterpret_cast<LPARAM>(&connectedMonitors));

    if (ShellExecuteEx(&info))
    {
        WaitForInputIdle(info.hProcess, INFINITE);

        ProcessWindowsInfo Info(GetProcessId(info.hProcess));

        // Go though all windows from that process
        EnumWindows((WNDENUMPROC)EnumProcessWindowsProc, reinterpret_cast<LPARAM>(&Info.ProcessID));

        if (Info.Windows.size() == 1)
        {
            // only if we got at most 1 window
            // NOTE: applications can have more than 1 top level window. But at least for SumtraPDF this works!

            if (connectedMonitors.size() >= PREFERRED_MONITOR)
            {
                // only move the window if we were able to successfully detect available monitors

                SetWindowPos(Info.Windows.at(0), 0, connectedMonitors.at(PREFERRED_MONITOR).rect.left, connectedMonitors.at(PREFERRED_MONITOR).rect.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
            }
        }

        CloseHandle(info.hProcess);
    }

    return 0;
}

To emphasize one of my comments in code. This code will only work if the process in question is not already running. You can tweak the code as per your requirements otherwise.
Update: Added C# code below, as I realized OP prefers C#. This code also has the termination logic cooked in.
C# code:
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

private const int SWP_NOSIZE = 0x0001;
private const int SWP_NOZORDER = 0x0004;

private const int PREFERRED_MONITOR = 1;

static void Main(string[] args)
{

    // NOTE: you will have to reference System.Windows.Forms and System.Drawing (or
    // equivalent WPF assemblies) for Screen and Rectangle

    // Terminate existing SumatraPDF process, else we will not get the MainWindowHandle by following method.
    List<Process> existingProcesses = Process.GetProcessesByName("SumatraPDF").ToList();

    foreach (var existingProcess in existingProcesses)
    {
        // Ouch! Ruthlessly kill the existing SumatraPDF instances
        existingProcess.Kill();
    }

    // Start the new instance of SumantraPDF

    Process process = Process.Start(@"C:\Program Files\SumatraPDF\SumatraPDF.exe");

    // wait max 5 seconds for process to be active
    process.WaitForInputIdle(5000);

    if (Screen.AllScreens.Length >= PREFERRED_MONITOR)
    {
        SetWindowPos(process.MainWindowHandle,
            IntPtr.Zero,
            Screen.AllScreens[PREFERRED_MONITOR].WorkingArea.Left,
            Screen.AllScreens[PREFERRED_MONITOR].WorkingArea.Top,
            0, 0, SWP_NOSIZE | SWP_NOZORDER);
    }
}

A: SEE_MASK_HMONITOR is only a request. Applications can choose their own window placement. SEE_MASK_HMONITOR only works when the executed application relies on default window placement, i.e. it creates its first top-level window with CW_USEDEFAULT
So what you want is not generally possible. Your code is as good as you can get, if you don't control the launched application.


text:
Q: mongodump stdout for a collection not working so im trying to dump a collection on mongodump through stdout so i can directly pipe it and gzip it.  But it's  giving me errors.
When i do:
mongodump --db test -u username -p Password -h mymongodatabase.onthecloud:12888 -vvvvv --collection posts --out -

it displays these errors:
Wed Feb 29 21:48:13 creating new connection to:mymongodatabase.onthecloud:12888
Wed Feb 29 21:48:13 BackgroundJob starting: ConnectBG
Wed Feb 29 21:48:13 connected connection!
connected to: mymongodatabase.onthecloud:12888
Wed Feb 29 21:48:13 nextSafe(): { $err: "unauthorized db:test lock type:-1 client:10.3.55.10", code: 10057 }
Wed Feb 29 21:48:13 User Assertion: 13106:nextSafe(): { $err: "unauthorized db:test lock type:-1 client:10.3.55.10", code: 10057 }
assertion: 13106 nextSafe(): { $err: "unauthorized db:test lock type:-1 client:10.3.55.10", code: 10057 }

but when i dunt include '--out -' it dumps the collection fine (doesn't give me aunauthorized error).  What's going on?

A: it was a bug, issued and fixed:
https://jira.mongodb.org/browse/SERVER-5233


text:
Q: Pattern Matching in Python - Extract and Store strings from file I have the following log file:
*** 2018-09-14T12:36:39.560671+02:00 (DB_NAME)
*** SESSION ID:(12345) 2018-09-14T12:36:39.560750+02:00
*** CLIENT ID:() 2018-09-14T12:36:39.560774+02:00
*** SERVICE NAME:(DB_NAME) 2018-09-14T12:36:39.560798+02:00
*** MODULE NAME:(mod_name_action (TNS V1-V3)) 2018-09-14T12:36:39.560822+02:00
*** ACTION NAME:() 2018-09-14T12:36:39.560848+02:00
*** CLIENT DRIVER:() 2018-09-14T12:36:39.560875+02:00
*** CONTAINER ID:(1) 2018-09-14T12:36:39.560926+02:00

I would like to store the MODULE_NAME value, extracted from this line:
*** MODULE NAME:(mod_name_action (TNS V1-V3)) 2018-09-14T12:36:39.560822+02:00

i.e. just this:
mod_name_action (TNS V1-V3)

I have to do that using python. I am trying with something like:
log_i=open(logname,"r")
    for line_of_log in log_i:
       #search the MODULE
       module = "MODULE NAME:("
       str_found_at = line_of_log.find(module)
       if str_found_at != -1:
          regex = r"MODULE NAME:([a-zA-Z]+)"
          MODULE = re.findall(regex, line_of_log)
          print "MODULE_A==>", MODULE

    log_i.close()

But it doesn't work. Can someone help me?

A: Using Regex.
Demo:
import re

s = """*** 2018-09-14T12:36:39.560671+02:00 (DB_NAME)
*** SESSION ID:(12345) 2018-09-14T12:36:39.560750+02:00
*** CLIENT ID:() 2018-09-14T12:36:39.560774+02:00
*** SERVICE NAME:(DB_NAME) 2018-09-14T12:36:39.560798+02:00
*** MODULE NAME:(mod_name_action (TNS V1-V3)) 2018-09-14T12:36:39.560822+02:00
*** ACTION NAME:() 2018-09-14T12:36:39.560848+02:00
*** CLIENT DRIVER:() 2018-09-14T12:36:39.560875+02:00
*** CONTAINER ID:(1) 2018-09-14T12:36:39.560926+02:00"""

res = []
for line in s.splitlines():
    m = re.search(r"(?<=MODULE NAME:\()(.*?)(?=\)\))", line)
    if m:
        res.append(m.group()+")")
print(res)

Output:
['mod_name_action (TNS V1-V3)']

A: You can do this without regex. I'll put your log data into a list of lines (retaining the newlines) using the .splitlines method so we can loop over it like it was a file.
We can use in to find lines containing "MODULE NAME:", and then we just need to search for the first '(' and the last ')' on that line so we can slice out the substring containing the name.
log_i = '''\
*** 2018-09-14T12:36:39.560671+02:00 (DB_NAME)
*** SESSION ID:(12345) 2018-09-14T12:36:39.560750+02:00
*** CLIENT ID:() 2018-09-14T12:36:39.560774+02:00
*** SERVICE NAME:(DB_NAME) 2018-09-14T12:36:39.560798+02:00
*** MODULE NAME:(mod_name_action (TNS V1-V3)) 2018-09-14T12:36:39.560822+02:00
*** ACTION NAME:() 2018-09-14T12:36:39.560848+02:00
*** CLIENT DRIVER:() 2018-09-14T12:36:39.560875+02:00
*** CONTAINER ID:(1) 2018-09-14T12:36:39.560926+02:00
'''.splitlines(True)

for line_of_log in log_i:
    #search for the MODULE NAME line
    if "MODULE NAME:" in line_of_log:
        # Find the location of the first '('
        start = line_of_log.index('(')
        # Find the location of the last ')'
        end = line_of_log.rindex(')')
        modname = line_of_log[start+1:end]
        print "MODULE_A==>", modname

output
MODULE_A==> mod_name_action (TNS V1-V3)

If there is only one "MODULE NAME:" line in the log (or you only want to print the first one if there are multiples) then you should put a break after the print statement so that you don't waste time checking all the following lines in the file.

A: It doesn't work because your regex pattern is incorrect: special characters like '_' and '-' aren't matched by the pattern '[a-zA-Z]+'. Plus, if you want to get rid of the parenthesis you have to include them in your pattern using the '\' escape character. Finally, instead of using
 str_found_at = line_of_log.find(module)

you can search directly a substring in a string in python.
Finally, I would recommend the following code:
log_i=open(logname,"r")
for line_of_log in log_i:
   #search the MODULE
   module = "MODULE NAME:("
   if module in line_of_log:
      regex = r"MODULE NAME:\((.+)\)"
      MODULE = re.findall(regex, line_of_log)
      print "MODULE_A==>", MODULE[0]
log_i.close()


text:
Q: Preloading content with grey bars like youtube can anyone explain me, how I can add a content preloader to my site so that's look like this:

How is this done?
Many thanks.

A: This is called a Loading placeholder.
You can find some examples on many sites.
Here is an example on Codepen. As you can see, you can do it only with HTML and CSS.
If you want other examples, you can find a lot of tutorials on YouTube with keywords Loading placeholder tutorial. If you want to make it more easily, you can use this library.
Good luck.

A: You can get better per loader from https://icons8.com/preloaders/


text:
Q: CTE is a Best Practice instead of temp table? "Common.XXX" datatable is creating into temp table. But it creates some performance issue. How can I remove temp table ? OR what is your advise? What is the best practice? Using CTE is better that temp table. Am I right? How can I improve below the performance of query?
CREATE PROCEDURE [Common].[GetXYZ]
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRAN;
    DROP TABLE IF EXISTS #xxx;

    SELECT TOP (1)
        *
    INTO #xxx
    FROM Common.Import WITH (UPDLOCK)
    WHERE State = 1
    ORDER BY Id;

    UPDATE Common.Import
    SET State = 2
    WHERE Id IN (
                    SELECT Id FROM #xxx
                );

    UPDATE #xxx
    SET State = 2;

    SELECT *
    FROM #xxx;
    COMMIT;
END;

A: The better way would be as below. This avoids a load of unnecessary operations in your current code (I am assuming Id is unique)
WITH CTE AS
(
  SELECT TOP (1) *
    FROM Common.XXX WITH (UPDLOCK)
    WHERE State = 1
    ORDER BY Id
)
UPDATE CTE
SET  State = 2
OUTPUT INSERTED.*;


text:
Q: How to access Model object in ActionFilterAttribute.OnResultExecuted? I am working with a WEB API application in ASP .NET Core 2.0 where I have a custom filter attribute that inherits from ActionFilterAttribute.
How can I access the Model object passed to a controller action in POST call, in ActionFilterAttribute.OnResultExecuted()
The mentioned method is passed a ResultExecutedContext object but I could not find an easy and reliable way to get Model object from it.
The filter I have, looks like the following:
public sealed class MyCustomFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext context)
    {
        base.OnActionExecuted(context);
    }
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        var model = ?????????????
    }

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        base.OnResultExecuting(context);
    }
}

and the controller looks like the following:
[Route("api/[controller]")]
public class MyController : Controller
{
    [ServiceFilter(typeof(MyCustomFilter))]
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] List<MyModel> data)
    {
        // my logic to process model here. In my filter, I want to access data, which is passed into this Post method

        return Ok();
    }
}

A: I set a private var in the controller and assign the posted model to it on the controllers action
 private YourModel _yourModel;

 public ActionResult MyAction(YourModel model)
 {
      _yourModel = model;
       return View();
 }

 protected override void OnResultExecuted(ResultExecutedContext filterContext)
 {
       //Access _yourModel here
 }

To access the model from the filterContext parameter passed in, you can use the below
var model = ((Controller)filterContext.Controller).ViewData.Model;

Try using TempData. Set tempdata to the model in your action.
 TempData["Model"] = myModel;

Then access using the TempData on the context.
var x = ((Controller)filterContext.Controller).TempData["Model"];

Hope that's what you meant.
thanks


text:
Q: Get all rows where a match is found I'm creating a simple blogging system with the following database tables:
Posts
    PostId
    Title
    PostDate
    Body
    Draft

Categories
    CategoryId
    CategoryName

PostCategories
    PostId
    CategoryId

Authors
    AuthorId
    AuthorName

PostAuthors
    AuthorId
    PostId

Tags
    TagId
    TagName

PostTags
    PostId
    TagId

Here's the query I have so far (using LINQ):
 var results = from p in posts
               join pc in postcategories on p.PostId equals pc.PostId
               join c in categories on pc.PostId equals c.CategoryId
               join a in authors on pc.PostId equals a.AuthorId
               select new BlogViewModel {
                                          Post = p,
                                          Category = c,
                                          Author = a
                                        };

This successfully returns all posts, the category the post belongs to, and the post author. My issue is how to get all associated tags for each post. I used Entity Framework to generate models and BlogViewModel contains:
public Post Post { get; set; }
public Category Category { get; set; }
public Author Author { get; set; }
public IEnumerable<Tag> Tags { get; set; }

My gut tells me that I need a new query within the select new BlogViewModel statement, something like:
... Tags = //new LINQ statement?

Can someone help point me in the right direction?
Thanks

A: You have to do join with tags and posttags and then group data on PostId:
var results = from p in posts
              join pc in postcategories on p.PostId equals pc.PostId
              join c in categories on pc.PostId equals c.CategoryId
              join ap in authorposts on pc.PostId equals ap.PostId
              join a in authors on ap.AuthorId equals a.AuthorId
              join tp in tagposts on p.PostId equals tp.PostId
              join t in tags on tp.TagId equals t.TagId
              group new { t, p, c, a } by tp.PostId into g

              select new BlogViewModel
                        {
                          Post = g.First().p,
                          Category = g.First().c,
                          Author = g.First().a,
                          Tags = g.Select(x=>x.t)
                        };

See working fiddle example

A: Though I'm not expert in LinQ, but what you need is Left / Right join. You can achieve the same in LinQ using DefaultIfEmpty().
Please take a look at Entity framework - right join to a view and http://forums.asp.net/t/1728935.aspx?left+right+join+in+linq+or+lambda


text:
Q: How do I sort database data in mongodb javascript? ( node.js ) I was creating bot in Discord.js. It has level system ( which you gain by writing things in the chat ) and I wanted to make a leaderboard, but I have to somehow sort the database out to do that, for example this is how it looks like now ( this is an example )
userId:"347707015956791297"
level:3
xp:231

userId:"267229922693611520"
level:1
xp:36

userId:"124575187579568129"
level:1
xp:81

userId:"466944003674472482"
level:4
xp:468

How do I make it look like this ( and if the person has same level, then it sorts it through xp ):
userId:"347707015956791297"
level:4
xp:468

userId:"267229922693611520"
level:3
xp:231

userId:"124575187579568129"
level:1
xp:81

userId:"466944003674472482"
level:1
xp:36

A: To sort by two fields just call sort after find and indicate necessary fields and ascending/descending order:
db.users.find({ }).sort( { level: -1, xp: -1 } )


text:
Q: How do I extract the first characters from files names? I want to email every file from a Google Drive folder that starts with the same name to the same person.
I have a list of emails and a list of words related to them - so

*

*'person1@mail.com' works at 'Unit 1'

*'person2@mail.com' at 'Building 2'

*'person3@mail.com' at 'Department ABC'

*and so on.

Note that the units' names have different sizes, and they don't follow a pattern. I have a list of files on Drive with names such as

*

*'Unit 1 - FileA.pdf'

*'Building 2 - FilesMarch.pdf'

*'Building 2 - FileB.pdf'

*and so on.

Once again, the rest of the files don't follow a pattern either, and some units have 1 file, while some others have up to 5.
So I have to email all files that start with, say, 'unit 1' to Person1@gmail, but I can't seem to figure how to extract the first letters of the files. Below I show you how I solved the problem with only one file with a fixed name per email, with the units' names on column B and the emails on column C:
  var ws = SpreadsheetApp.openById('ID goes here')
  var sheet = ws.getSheetByName('Sheetname goes here')

  var message = 'messagegoeshere'
  var files = DriveApp.getFolderById('Folder ID')

    for (var i = 2 ; i < 500 ; ++i) {
  var name = sheet.getRange(i, 2).getValue()
  var recipient = sheet.getRange(i, 3).getValue()

  //some units have more than one recipient
  if (sheet.getRange(i, 4).getValue() != '') {
  var recipient = recipient + ', ' + sheet.getRange(i, 4).getValue()
  }

  var attach = files.getFilesByName(name + '.PDF')
  var title = 'title'
  MailApp.sendEmail(recipient, title, message, {attachments: [attach.next()]})
  }
  }

A: You should get the FileIterator for the folder:
var files = DriveApp.getFolderById('Folder ID').getFiles();

and then iterate over it in a while loop
while (files.hasNext()) {
  var file = files.next();
  // work with the file
}

For better performance, don't call getValue in a long loop: get all the values you need from a sheet before entering the loop.
To check whether a file name begins with a given string, one can use a regular expression since the convenient startsWith method is not yet supported by Apps Script. Here is how it  can look like.
function answer() {
  var ws = SpreadsheetApp.openById('ID goes here')
  var sheet = ws.getSheetByName('Sheetname goes here')
  var data = sheet.getRange(2, 1, 500, 2).getValues();   // all we need
  var files = DriveApp.getFolderById(' Id here ').getFiles();

  while (files.hasNext()) {
    var file = files.next();
    var name = file.getName();
    var recipients = [];             // using an array to collect recipients
    for (var i = 2; i < data.length; i++) {
      var re = new RegExp('^' + data[i][0]);    // check for data[i][0] at the beginning
      if (re.test(name)) {
        recipients.push(data[i][1]);
      }
    }
    if (recipients.length > 0) {
      MailApp.sendEmail(recipients.join(', '), 'My Subject', 'My Message', {attachments: [file]});
    }
  }
}


text:
Q: GatherBy first entry of data Assume I have data(sim) below. How can I extract first point on each horizontal line?
sim={{0.0123645, 10}, {0.0315618, 10}, {0.0349631, 10}, {0.0602517,
  10}, {0.110052, 10}, {0.125536, 10}, {0.126541, 10}, {0.126872,
  10}, {0.153006, 10}, {0.157659, 10}, {0.158335, 10}, {0.172981,
  10}, {0.186542, 10}, {0.200192, 10}, {0.214166, 10}, {0.2161,
  10}, {0.223926, 10}, {0.244128, 10}, {0.27395, 10}, {0.287663,
  10}, {0.295087, 10}, {0.317831, 10}, {0.331263, 10}, {0.338285,
  10}, {0.347775, 10}, {0.358619, 10}, {0.381334, 10}, {0.383822,
  10}, {0.387735, 10}, {0.402114, 10}, {0.450075, 10}, {0.468865,
  11}, {0.48508, 11}, {0.502013, 11}, {0.51136, 11}, {0.517392,
  11}, {0.523373, 11}, {0.541651, 11}, {0.543816, 11}, {0.604502,
  11}, {0.60608, 11}, {0.662307, 11}, {0.664964, 11}, {0.692087,
  11}, {0.754625, 11}, {0.782756, 11}, {0.792393, 11}, {0.795388,
  11}, {0.818549, 11}, {0.827898, 11}, {0.838457, 11}, {0.864839,
  11}, {0.886406, 11}, {0.91586, 12}, {0.933204, 12}, {0.947947,
  12}, {0.950653, 12}, {0.953183, 12}, {0.97591, 11}, {1.01709,
  10}, {1.05193, 10}, {1.09514, 10}, {1.12728, 10}, {1.14659,
  10}, {1.20052, 10}, {1.22754, 11}, {1.24561, 11}, {1.27093,
  11}, {1.27265, 11}, {1.28367, 11}, {1.28511, 11}, {1.2877,
  11}, {1.29041, 11}, {1.31259, 12}, {1.31415, 12}, {1.31774,
  12}, {1.32675, 12}, {1.33307, 12}, {1.34072, 12}, {1.39716,
  14}, {1.41142, 14}, {1.42015, 14}, {1.42476, 14}, {1.43117,
  14}, {1.43567, 14}, {1.43754, 14}, {1.45814, 14}, {1.46465,
  14}, {1.4666, 14}, {1.46877, 14}, {1.47267, 14}, {1.47754,
  14}, {1.4838, 14}, {1.48614, 14}, {1.51368, 14}, {1.51374,
  14}, {1.52088, 14}, {1.53724, 14}, {1.5483, 14}, {1.55711, 14}};

ListLinePlot[sim, Epilog -> {Red, PointSize[Small], Point[sim]},
 Frame -> True, PlotTheme -> "Detailed",
 FrameLabel -> {"Time", "Population"}, ImageSize -> Large,
 InterpolationOrder -> 0]

A: First /@ SplitBy[sim, Last]

{{0.0123645, 10}, {0.468865, 11}, {0.91586,12}, {0.97591, 11}, {1.01709, 10},{1.22754, 11}, {1.31259, 12}, {1.39716, 14}}

ListLinePlot[sim,
 Epilog -> {Red, PointSize[Large], Point[First /@ SplitBy[sim, Last]],
  Green, PointSize[Small], Point[sim]},
 Frame -> True, FrameLabel -> {"Time", "Population"},
 ImageSize -> Large, InterpolationOrder -> 0]


text:
Q: Проблема с кодировкой при записи в файл Записываю данные из буфера в текстовый файл(русский текст). Сначала пробовал так
public static void WriteFinalInfoInFile()
{
    string finalInfo = postTrack + "  " + location + "\n";
    File.AppendAllText("finalResult.txt", finalInfo); //write in file
}

потом так
public static void WriteFinalInfoInFile()
{
    string finalInfo = postTrack + "  " + location + "\n";
    File.AppendAllText("finalResult.txt", finalInfo, Encoding.GetEncoding(1251)); //write in file
}

В обоих случаях, русские слова записываются как ????????????? ???????. С латиницей проблем с записью нет.


text:
Q: I want common header and footer all over pages I have included following  to make it done. But Javascript elements on page are not working due to this.

<content>
</content>

A: If you can manage to setup a virtual server like XAMPP on your machine, then using PHP, you can include header and footer on just any page you want with a single line of code.
<?php include 'header.php';?>

and footer with
<?php include 'footer.php';?>


text:
Q: How can I fix this code segment to run AP CSP pseudocode? I'm attending an AP CSP class and I'm trying to turn this pseudocode:

into runnable Python code.
This is what I've coded:
words = ["song", "book", "video", "book"]
index = 1
n = len(words)

for i in range (n):
  if words[index] == "book":
    words.insert(index, "read")
    index = index + 1
  else:
    index = index + 1

print(words)

And this is the intended result:
["song", "read", "book", "video", "read", "book"]

But after running the code segment I coded, this is what I got:
['song', 'read', 'read', 'read', 'read', 'book', 'video', 'book']

Can anyone help me?

A: You should delete the "else" sentence, and pull the indentation of the below line.
like this
words = ["song", "book", "video", "book"]
index = 1
n = len(words)

for i in range (n):
  if words[index] == "book":
    words.insert(index, "read")
    index = index + 1
  index = index + 1

print(words)


text:
Q: How is com.solacesystems.jms.SolConnection.mClientID field set by default? How is com.solacesystems.jms.SolConnection.mClientID field set by default?
The string consists of 3 parts. The first part is the hostname. What's the logic for setting the 2nd and 3rd parts?
Where can I find Solace JMS driver code?

A: The private member mClienID isn't accessible. You can read it's value with method SolConnection.getClient().
You can overwrite its default value with the method SolConnectionFactory.setClientID() or from the Solace Admin GUI.
It is the 'client ID' for this connection and it uniquely identifies this client from others. If your client crashes and restarts, the appliance will know it's the same App continuing it's session or not by looking at this client ID. For many scenarios, Client ID doesn't matter, but just in case, the API and appliance automatically assign a unique ID to this connection: hostname (internal) (internal)
For downloads, try here: https://solace.com/downloads/