text:
Q: componentsSeparatedByString for SFV files I'm having an NSString like this:

music that rocks.mp3 e99a65fb

The problem is that between the filename (musicthatrocks.mp3) and the CRC32 checksum (e99a65fb) there could be many more spaces then one. How can I split the line into an array?
I thought of using componentsSeparatedByString, but my problem is that the filename can also contain spaces.
Thanks in advance.

A: If you're OK with regular expressions, you could do it that way.  For example (using RegexKitLite):
NSString * fileName = [line stringByMatching:@"(.*)\\s" capture:1];

An explanation of the regex:  (.*) This will match as many characters as it can, until it finds a space character.  However, the capture is greedy, which means it's going to grab as many characters as it can before the last space character (in a nutshell).
Or you can use NSString methods to find the last occurrence of the space character and get a substring from the beginning of the line to the last space character.
Or you can split the string base on @" ", throw away the last object in the array, and then recombine the array with @" ".

A: *

*Use componentsSeparatedByString:.

*Get the lastObject, which is the CRC32.

*Use subarrayWithRange: to create a new array without the CRC32.

*Use componentsJoinedByString: to reconstitute the filename.

You may want to do step 4 in a loop, repeatedly deleting the last object until either the filename exists in the target directory or you run out of empty strings at the end of the array. This handles the case of multiple spaces between filename and CRC32, as well as the case of a filename ending in spaces (pathological but possible).


text:
Q: Acumatica Implementation and data entry Am supposed to do Acumatica implementation for a client but the client has requested that all the transactions from the start of their financial year, July, be added into the system. Is there a way to import the transactions in bulk instead of adding one transactions, SO/PR/IN, at a time.

A: Yes, you can create an import scenario to bulk upload records. YOu could also optionally use the Contract-Based API to programmatically push transactions through. This help article might also help. https://help-2021r2.acumatica.com/(W(2))/Help?ScreenId=ShowWiki&pageid=6ef1dca7-4ca7-47b4-9adc-b67de5231d4f

A: I would recommend you take a look at the online training(Acumatica's Open University). Import Scenarios are the tool you are most likely looking for.
https://openuni.acumatica.com/courses/reporting/i100-integration-scenarios/
The above covers how to setup bulk imports for a variety of scenarios. If you are struggling with a specific import scenario the community forums are a great place to get help with that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image formed when two imaginary rays are extended to meet at a point An object is placed at a finite distance from a concave lens. Given are the two ray diagrams. Is the second ray diagram possible? If yes, that must be an enlarged, virtual and inverted image; if no, why not?
Ray Diagram 1:-

Ray Diagram 2:-

A: No. The second diagram is not correct.
You did not diffract the ray away from the lens that is passing through F1 point. You just drew the ray along the normal to the surface which is where you got it wrong.
The ray will diffract from its path, away from the normal to the surface, and will probably pass somewhere from the lower plane surface of the lens.
If you connect that ray to the first ray of the second diagram, you will get the image formed at the same point in diagram 1.

A: In addition to the correct answer of @Spectra:
After removing the incorrect ray from $A$ to $F_1$, draw a ray from $A$ towards $F_2$.  When that ray hits the lens, then it is refracted moving to the right parallel to the axis...


text:
Q: Find child elements by missing attribute with jQuery Finding elements by attribute in jQuery is simple:
$(parentElement).find('[attribute]');

How do you find elements, that don't have a certain attribute?

A: You can use :not although filter is most likely faster:
$(parentElement).filter(function() {
    return !$(this).attr('attribute');
});

A: That's why the :not() is made for.
Try,
$(parentElement).find(':not([attribute])');


text:
Q: Mac Pro will not shut down after Lion upgrade I use Font Agent Pro as my font manager of choice. I just upgraded my 2007 Mac Pro from the latest OS X 10.6 to 10.7.5 lion.
I was having a problem with Postscript Type 1 fonts not being available to Adobe or other applications, so I cleared the font cache from Terminal.
sudo atsutil databases -remove

After doing so, my Mac will not shut down - when I try to shut down the screen goes gray but the cursor can still can be moved around
I have to hit the power button to shut down manually.
Any ideas as to why this is happening?

A: I've been working through the issue with Font Agent Pro Support. Evidently this is due to the Smasher Application having issues clearing the font cache if Adobe Acrobat is installed.
The solution for me was to remove Smasher. Shut down, reboot into safe mode, and restart.
That seems to have fixed the issue for now at least.

A: The first thing and easiest step is to reset the P-RAM by holding down, immediately at startup, Command-Option-P-R . Continue this key press for three startup chimes — and release.
The second might be an SMC reset, see this Apple Support doc for details and directions for your machine.
Force Shutdown = Hold Power button down for 10 seconds.


text:
Q: How to manage hardware cache usage I wonder if there is a way to directly manage which parts of the memory are loaded into (and kept in) the cache. I know that there is __builtin_prefetch() in gcc, but I would need a bit more (at least I think I would...).
Here is my problem:
I have a loop where I update a vector v (very pseudocode):
while (1) {
    update_an_entry_in_v;
}

The length of v is in the millions. The loop runs 100s of millions times, and it jumps around in v. Therefore my cache-hit ratio is really bad, and there is no way of getting all of v into L1 cache.
I can reorganize the code like this:
for (i=0; i < length_of_v; i+=1024) {
    while (1) {
        update_an_entry_in_v[i:i+1023];
    }
}

That is, first only work with those updates that I know will update only entries in v[0:1023], process all of those, then go to the next block, etc.
Now this is probably going to have a much better cache behaviour, but I wonder if it is possible to make it even better. Let's focus on the v[0:1023] block. I still will jump around within v[0:1023], so the hardware may think that there is no need to keep parts of that chunk of memory in L1 cache any longer, and then, boom!, I go back to that chunk again.
So the question becomes: is there a way to mark the whole v[0:1023] so that it gets loaded into L1 before the inner while loop, and then "unmark" it once the while loop is finished?
(Obviously, 1024 is just a convenient number that should be tuned. With doubles that's 8K memory, and given that these days most machines have at least 32-64K L1 data cache that should leave enough for everything else.)

A: Obviously I don't know what you're doing, and this somewhat sidesteps the issue, but if you know the indicies could you radix sort the indicies and then just run through the entire thing in order which would be cache efficient? Perhaps order they're updated matters but from the comment about reorganizing the code I guessed, on the off chance it didn't, I'd mention it. [Well, order is somewhat preserved doing this since radix sort is stable, but only when it's the same index].


text:
Q: How to trigger a function (to start processing) ONLY AFTER the form is loaded in WPF C#? I have try formloaded, it doesn't work.
   private void UserControl_Loaded_1(object sender, RoutedEventArgs e)
    {
          //This function call with begin the processing.
          EnrolFingerprint();
    }

I want the processing to take place only after the form has been loaded, so that the user can see what is going on. Currently, the processing take place and then only it loads the form.


text:
Q: Combining different geometry types in ArcGIS for Desktop? Two geodatabases have been created using split by attribute tool from CAD drawing file. One gdb is from polyline layer and another from polygon layer of input drawing file.
I want to combine contours which are polygons in one feature class and contours as polylines in another feature class.
Or
Is there a tool to import similar layers based on 'Layer' filed of CAD drawing irrespective of geometry type into a new output gdb ?

A: As commented by @Vince:

You cannot place polygons in a line feature class or lines in a
  polygon feature class. Period. This is one of the fundamental
  differences between CAD and GIS. It's easier to save polygons as lines
  than to build topology from line to polygon, but if you need polygons,
  that can't be avoided.

A: The ability to store multiple geometry types in the same feature is more of a storage format limitation.  Many GIS storage formats support different geometry types in the same geometry. For example you can store multiple geometry types in PostgreSQL/PostGIS "Geometry" data type.  Oracle and SQL Server can do the same row by row geometry type variations also.  Each GIS package may have it's own limitations on how it works with these multi-geometry type fields.


text:
Q: I have a querystring value which don't convert to right encoding? I pass actually Göte in the querystring parameter, which converts to G%F6te in the url field.
And in the page, actually a generic handler it displays:
G�te
How to fix it, so it displays Göte?
--------- EDIT ----------------
It actually works fine when I make a ajax-call to the page, but when I directly alter the querystring parameter it doesn't.

A: Make use of : HttpServerUtility.UrlEncode Method
Encoding:
String MyURL;
MyURL = "http://www.contoso.com/articles.aspx?title=" + Server.UrlEncode("ASP.NET Examples");

Response.Write("<a href=" + MyURL + "> ASP.NET Examples </a>");

Decoding:
decodedUrl = Server.UrlDecode(urlToDecode)


text:
Q: "Expected type parameter, found reference to type parameter" when implementing a generic cache struct In the Closures chapter of the second edition of The Rust Programming Language, the writer implements a Cache struct and leaves it with a few problems for the reader to fix up, such as:

*

*Accepting generic parameters and return values on the closure function

*Allowing more than one value to be cached

I've attempted to fix those problems but I am quite stuck and can't make it work.
use std::collections::HashMap;
use std::hash::Hash;

struct Cacher<T, X, Y>
where
    T: Fn(&X) -> &Y,
    X: Eq + Hash,
{
    calculation: T,
    results: HashMap<X, Y>,
}

impl<T, X, Y> Cacher<T, X, Y>
where
    T: Fn(&X) -> &Y,
    X: Eq + Hash,
{
    fn new(calculation: T) -> Cacher<T, X, Y> {
        Cacher {
            calculation,
            results: HashMap::new(),
        }
    }

    fn value<'a>(&'a mut self, arg: &'a X) -> &'a Y {
        match self.results.get(arg) {
            Some(v) => v,
            None => {
                let res = (self.calculation)(arg);
                self.results.insert(*arg, res);
                res
            }
        }
    }
}

Where T is the closure function type, X is the argument type and Y is the return value type.
The error I get:
error[E0308]: mismatched types
  --> src/main.rs:30:43
   |
30 |                 self.results.insert(*arg, res);
   |                                           ^^^ expected type parameter, found &Y
   |
   = note: expected type `Y`
              found type `&Y`

I understand this, but I can't think of an elegant solution for the whole ordeal.

A: You've stated that your closure returns a reference:
T: Fn(&X) -> &Y,

but then you are trying to store something that isn't a reference:
results: HashMap<X, Y>,

This is fundamentally incompatible; you need to unify the types.
In many cases, there's no reason to have a reference to a generic type because a generic type can already be a reference. Additionally, forcing the closure to return a reference means that a closure like |_| 42 would not be valid. Because of that, I'd say you should return and store the value type.
Next you need to apply similar logic to value, as it needs to take the argument by value in order to store it. Additionally, remove all the lifetimes from it as elision does the right thing: fn value(&mut self, arg: X) -> &Y.
Once you've straightened that out, apply the knowledge from How to lookup from and insert into a HashMap efficiently?:
fn value(&mut self, arg: X) -> &Y {
    match self.results.entry(arg) {
        Entry::Occupied(e) => e.into_mut(),
        Entry::Vacant(e) => {
            let res = (self.calculation)(e.key());
            e.insert(res)
        }
    }
}

Round it off with some tests that assert it's only called once, and you are good to go. Note that we had to make decisions along the way, but they aren't the only ones we could have chosen. For example, we could have made it so that the cached value is cloned when returned.

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::hash::Hash;

struct Cacher<F, I, O>
where
    F: Fn(&I) -> O,
    I: Eq + Hash,
{
    calculation: F,
    results: HashMap<I, O>,
}

impl<F, I, O> Cacher<F, I, O>
where
    F: Fn(&I) -> O,
    I: Eq + Hash,
{
    fn new(calculation: F) -> Self {
        Cacher {
            calculation,
            results: HashMap::new(),
        }
    }

    fn value(&mut self, arg: I) -> &O {
        match self.results.entry(arg) {
            Entry::Occupied(e) => e.into_mut(),
            Entry::Vacant(e) => {
                let res = (self.calculation)(e.key());
                e.insert(res)
            }
        }
    }
}

#[test]
fn called_once() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    let calls = AtomicUsize::new(0);

    let mut c = Cacher::new(|&()| {
        calls.fetch_add(1, Ordering::SeqCst);
        ()
    });

    c.value(());
    c.value(());
    c.value(());

    assert_eq!(1, calls.load(Ordering::SeqCst));
}


text:
Q: How to detect certain words from a given string in Python? I'm making a basic program to detect certain words from a string and mark the message as SPAM if the string contains the spam keywords but ran into a problem. The compiler doesn't detect it as spam unless I input the exact same strings.
Here's the code :
text = input("text : ")

if(text == 'make a lot of money' in text) or (text == 'buy now'in text) or (text == 'subscribe this 'in text) or (text =='click link' in text):
    print("SPAM")
else:
    print("OKAY")

A: That' because you're comparing with equals:
text == 'make a lot of money' in text

instead just use the in command:
'make a lot of money' in text

will yield True if the text contains that string

A: You're not using correct syntax for if statement, please use this:
text = input("text : ")

if 'make a lot of money' in text or 'buy now' in text or 'subscribe this' in text or 'click link' in text:
    print("SPAM")
else:
    print("OKAY")

A: text = input("text : ")

if('make a lot of money' in text) or ('buy now'in text) or ('subscribe this' in text) or ('click link' in text):
    print("SPAM")
else:
    print("OKAY")

OR
text = input("text : ")
spam_phrases = ['make a lot of money','buy now','subscribe this','click link']

for phrase in spam_phrases:
    if phrase in text:
        print("SPAM")
        break
else:
    print("OKAY")


text:
Q: Global errorHandling solution with RxJava only when onError is not implemented I have a general error handling solution in my app which should be invoked whenever onError is called. Instead of implementing onError for every subscribe I have done this inside the Application class:
RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
    @Override
    public void handleError(final Throwable throwable) {
        new ErrorHandler().call(throwable);
    }
});

However I would like to have the ability to override this by implementing onError, and according to:
https://github.com/ReactiveX/RxJava/wiki/Plugins#rxjavaerrorhandler

This plugin allows you to register a function that will handle errors that are raised by RxJava but that cannot be handled by the ordinary RxJava onError notification process (for instance, if RxJava tries to propagate an error to a subscriber that has not implemented an onError handler).

This should have been the case where I have implemented onError. However when running the code handleError inside RxJavaErrorHandler still gets invoked first, even though I have implemented onError.
Update:
According to zsxwing, the wiki has been updated with the correct description of RxJavaErrorHandler.

A: What we did at work was make a subclass of observer that has a default implementation of onError that you can still override if need be.  Seems to solve your use case.


text:
Q: how to swap image on click? i wnt to swap image on click,bt here if m clicking from down image to up but again its not coming on down image if m clicking on that image...
m geting some error-x.attr("src") is undefined
 $(document).ready(function () {
     $('#sortdivlink').click(function () {

        var x = $("img[src$='../Images/Sort_down.png'][name='stCodeDSC']");

        if (x.attr("SRC") == "../Images/Sort_down.png") {
            x.attr('src', x.attr('src').replace("../Images/Sort_down.png", "../Images/sort_up.png"));
        }
        else {
             x.attr('src',  x.attr('src').replace("../Images/sort_up.png", "../Images/Sort_down.png"));
        }
    });
});

A: I would imagine this is due to the selector you're using to assign x, which is likely returning null. I would consider maybe adding an Id or CSS class to the image, and then simplifying the selector to something like this:
var x = $('img.sortDirectionImage');

Alternatively, if you know that the sortdivlink element, will only have a single image, you could simply search for an img element within the context of that element, for example:
// within the click function scope
var x = $('img', this);

Edit
Additionally, I would recommend using more recognisable variable names; you might know what x is, but the next person that comes to read your code might not.

A: you could use a
 with a css class with a background-image and dimensions, and use $(div).toggleClass("new-image") to use the updated background-image
that will greatly simplify your code.
[EDIT]

A: Look at my script I wrote long time ago (without any jQuery):
function changeImg(element) {
        var img = document.getElementById(element);
        if (img.src == "../images/expand.png") {
            // collapse
            img.src = "../images/collapse.png";
        }
        else {
            // expand
            img.src = "../images/expand.png";
        }
    }

Normal HTML-Markup:
...

Maybe it will work for you...


text:
Q: como subir solamente el directorio "./build" y no todo el proyecto utilizando travis-ci tengo un proyecto en reactjs y quiero que cuando ejecute el comando $ git push --tags se suba en el apartado de release únicamente los archivos que se generan cuando hago un $ npm run build y no todo el proyecto.
Esta es mi configuración de travis.yml
sudo: required
language: node_js
env:
  global:
    - RELEASE_NAME=build
node_js:
  - "stable"
cache:
directories:
  - node_modules
before_install:
  - npm ci
script:
  - npm run build
deploy:
  provider: releases
  api_key: $GITHUB_TOKEN
  local_dir: ./build
  on:
    branch: master
    tags: true

Asi me sale cuando me descargo el archivo en el aportado de release en github

lo que necesito es que solo me muestre los siguientes archivos al momento de descargar la release
build:
--bundle.css
--bundle.js
--index.html

A: Encontré la solución, lo resolví de la siguiente forma:
sudo: required
language: node_js
env:
  global:
    - RELEASE_NAME=build
node_js:
  - "stable"
cache:
directories:
  - node_modules
before_install:
  - npm ci
script:
  - npm run build
before_deploy:
  - tar -czf $RELEASE_NAME-$TRAVIS_TAG.tar.gz $RELEASE_NAME
  - zip -r $RELEASE_NAME-$TRAVIS_TAG.zip $RELEASE_NAME
  - ls -al
deploy:
  provider: releases
  api_key: $GITHUB_TOKEN
  file:
    - $RELEASE_NAME-$TRAVIS_TAG.tar.gz
    - $RELEASE_NAME-$TRAVIS_TAG.zip
  skip_cleanup: true
  on:
    tags: true


text:
Q: tcsh script - Will not output simple ls -l command using cygwin I want to check whether or not the files in a directory A match the files in directory B, and that these matched files are not modified/changed.
I am very new to this new programming environment as I am used to Windows. This task is a part of a school project but I am trying to run tcsh scripts on my Windows using cygwin and bash(?). However, i specify the tcsh environment in my scripts.
This simple script:
#!/usr/bin/tcsh
echo Hello world;

set listing=`ls -l`

echo $listing

Gives me the following output:
Shawn@Shawn-PC /cygdrive/c/Users/Shawn/Desktop
$ ./lab3.sh
Hello world
Unknown user: $372.

However, I am able to run the "ls -l" command directly into the command line and it returns the appropriate result, so I don't know why it can't execute my "ls -l" command in the script. I don't know if there something wrong with my tcsh syntax in the script and why it returns the error message "Unknown user: #372."

A: You probably have a file or directory whose name is something like ~372, or that contains that as part of its name.
If you type
echo ~372

at the shell prompt, the shell will try to expand ~372 to the home directory of the user with the name 372. Almost certainly there is no such user -- thus the error message.
Your command:
set listing=`ls -l`

isn't likely to be very useful anyway. The output of ls -l, which is line-oriented with aligned columns, will be joined into a single line of text with multiple blanks replaced by single blanks. It will be a mess, difficult to read. (Perhaps the point is to demonstrate this.)
You can avoid the error on ~372 by adding double quotes around the backticks:
set listing="`ls -l`"

But now the string $listing contains that troublesome ~372, and if you try to echo it you'll have the same problem; $listing will expand to the string, and echo will try to expand the ~372 contained within it.
So you also need to add quotes (or a :q suffix) to theecho` command.
Here's what I got using tcsh on my system:
% touch foo bar '~372'
% ls -l
total 0
-rw-r--r-- 1 kst kst 0 Sep 19 14:06 bar
-rw-r--r-- 1 kst kst 0 Sep 19 14:06 foo
-rw-r--r-- 1 kst kst 0 Sep 19 14:06 ~372
% set listing = `ls -l`
Unknown user: 372.
% set listing = "`ls -l`"
% echo $listing
Unknown user: 372.
% echo "$listing"
total 0 -rw-r--r-- 1 kst kst 0 Sep 19 14:06 bar -rw-r--r-- 1 kst kst 0 Sep 19 14:06 foo -rw-r--r-- 1 kst kst 0 Sep 19 14:06 ~372
%

This is not a particularly useful thing to do, but that's how to do it.
Note that if you were using bash, then this:
listing="`ls -l`"
echo "$listing"

would preserve the multi-line formatting.
Obligatory link: http://www.perl.com/doc/FMTEYEWTK/versus/csh.whynot

A: If you just need it to print to terminal, then this is all you need.
#!/usr/bin/env tcsh

echo Hello world

ls -l

If you need to save it as an array or something it would be easier to output it to a text file and then read it in line by line as an array. (The spacing gets messed up for me to do it directly).
#!/usr/bin/env tcsh

echo Hello world

ls -l > output.txt

If this is what you need, read up on importing a text file as an array.
Also, this would be much easier in bash if you have the choice.


text:
Q: java code to get the difference between two timestamp stored in arraylist String sql = "SELECT  endtime FROM user_req";
ResultSet rs = stmt.executeQuery(sql);

ArrayList<Timestamp> list1= new ArrayList<Timestamp>();
while (rs.next()) {

    list1.add(rs.getTimestamp("endtime"));
}
System.out.println("\n the requested time is : ");
System.out.println(list1);

this gives me the result:-
the requested time is :
[2013-12-12 07:00:00.0, 2013-12-12 05:00:00.0]

this is the code which I've used that retrieves the timestamp data from MySQL and stores it in an aaraylist. but how to compare those dates and get the difference in terms of days and hours.
please help me and thanks in advance.

A: try this,
    Collections.sort(timeStampList);
    Timestamp tempStamp = timeStampList.get(0);
    for (Timestamp startstamp : timeStampList)
    {
        if (tempStamp != startstamp)
        {
                long diffTime = startstamp.getTime() - tempStamp.getTime();
                diffDays = diffTime / (1000 * 60 * 60);

                if(diffDays > 24)
                {
                    System.out.println(diffDays / 24 +"Day" + " "+diffDays % 24 + "hours");
                }
                tempStamp = startstamp;
        }
    }


text:
Q: Wagtail set additional permissions for MyPage Wagtail newbie here.
I am trying to add some additional permissions to specific models, but nothing shows up into the "wagtail admin". I can do this the "django" way but I have the impression that wagtail could handle this type of permissions. I could not find any hints in the wagtail documentation.
I have a new model named "MyPage":
class MyPage(Page):
    [...]

    class Meta:
        permissions = (
        ('view_restricted_document', 'can view restricted documents'),
    )

How do I make this permission available in the groups section of the wagtail admin?

A: It turns out that there is a wagtail hook which does just that: "register_permsissions".
Create a file named "wagtail_hooks.py" if it does not exist in your app and enter the following:
from wagtail.wagtailcore import hooks
from django.contrib.auth.models import Permission

@hooks.register('register_permissions')
def view_restricted_page():
    return Permission.objects.filter(codename="view_restricted_document")

That's it.
Now if I browse the groups section, under "Other Permissions" I can view the additional option "can view restricted document".


text:
Q: How to reference outside javascript in a Partial View called by ajax in MVC5? I've researched on answers on this topic for MVC 3 & MVC 4 and I was hoping to find a solution for MVC 5. I have a view which loads partial view via ajax. Within the view, I have all my javascript logic defined (@section Scripts) there as I can't have any in my partial view. The problem is, within my partial view, I wish to call a javascript function that is defined within the view upon success.
Below is my view and partial view
MyView.cshtml
@section Scripts
{
    @Scripts.Render("~/plugins/myplugins")
    <script>
        function callFunctionOutsideThisPartialView() {
        //... This doesn't get called
        }
    </script>
}

MyPartialView.cshtml
@using (Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "divForPartialView",
    OnSuccess = "callFunctionOutsideThisPartialView()"
}, new { @class = "form-inline" }))
{
    // Partial View here
}

What is the correct way to access javascript functions that are outside of the partial view in MVC 5?

A: If I'm remembering correctly, just render you partial view in a normal view and load that normal view via ajax call.Add you jquery's to normal view also.


text:
Q: Jacobson radical , projective module I am doing some question from (Mostly) Commutative Algebra by Loir and the following question is from Chapter 3.

Question: Let $A$ be a ring, let $J$ be its Jacobson radical and let $M$ be a right $A-$ module. Assume that there exists an $A-$ module N such that $M\oplus N$ is a free $A-$ module.
(a) Prove that $J_M =MJ$, where $J_M$ is the intersection of all maximal submodules of M.
(b) Prove that $M\neq MJ$.

Attempt: (b) I assumed that on the contrary let $M= MJ$ in the hope of finding some contradiction but I am not getting any ideas on how should I proceed.
(a) For proving (a), I assumed that let $x\in J_M$ but I am not able to prove that x also belongs to $MJ$. Converse part I have proved.
Please shed some light on the proof of it!


text:
Q: Disable scrolling in webview? Until now I have been an iPhone developer only and now I have decided to give Android a whirl. Something I haven't been able to figure out on Android is how to programmatically prevent scrolling in a WebView?
Something similar to iPhones prevention of the onTouchMove event would be great!

A: Set a listener on your WebView:
webView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return(event.getAction() == MotionEvent.ACTION_MOVE));
            }
        });

A: I haven't tried this as I have yet to encounter this problem, but perhaps you could overrive the onScroll function?
@Override
public void scrollTo(int x, int y){
super.scrollTo(0,y);
}

A: My dirty, but easy-to-implement and well working solution:
Simply put the webview inside a scrollview. Make the webview to be far too bigger than the possible content (in one or both dimensions, depending on the requirements). ..and set up the scrollview's scrollbar(s) as you wish.
Example to disable the horizontal scrollbar on a webview:
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="vertical"
>
    <WebView
        android:id="@+id/mywebview"
        android:layout_width="1000dip"
        android:layout_height="fill_parent"
    />
</ScrollView>

I hope this helps ;)

A: To Disable scroll use this
webView.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event)
    {
        return (event.getAction() == MotionEvent.ACTION_MOVE);
    }
});

A: I resolved the flicker and auto-scroll by:
webView.setFocusable(false);
webView.setFocusableInTouchMode(false);

However if it still does not work for some reason, simply make a class that extends WebView, and put this method on it:
// disable scroll on touch
  setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      return (event.getAction() == MotionEvent.ACTION_MOVE);
    }
  });

I am suggesting to extend WebView, in order to provide more effective control, like disable/enable swipes, enable/disable touches, listeners, control transitions, animations, define settings internally so on..

A: Making the WebView ignore motion events is the wrong way to go about it. What if the WebView needs to hear about these events?
Instead subclass WebView and override the non-private scroll methods.
public class NoScrollWebView extends WebView {
    ...
    @Override
    public boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY,
                                int scrollRangeX, int scrollRangeY, int maxOverScrollX,
                                int maxOverScrollY, boolean isTouchEvent) {
        return false;
    }

    @Override
    public void scrollTo(int x, int y) {
        // Do nothing
    }

    @Override
    public void computeScroll() {
        // Do nothing
    }
}

If you look at the source for WebView you can see that onTouchEvent calls doDrag which calls overScrollBy.

A: I don't know if you still need it or not, but here is the solution:
appView = (WebView) findViewById(R.id.appView);
appView.setVerticalScrollBarEnabled(false);
appView.setHorizontalScrollBarEnabled(false);

A: This may not be the source of your problem but I have spent hours trying to track down why my application that worked fine on the iphone cause the android browser to constantly throw up the vertical/horizontal scrollbars and actually move the page. I had an html body tag with height and width set to 100%, and the body was full of various  tags in different locations. No matter what I tried, the android browsers would show their scroll bars and move the page just a little bit, particularly when doing a fast swipe. The solution that worked for me without having to do anything in an APK was to add the following to the body tag:
leftmargin="0" topmargin="0"

It seems the default margins for body tag were being applied on the droid but ignored on the iphone

A: Here is my code for disabling all scrolling in webview:
  // disable scroll on touch
  webview.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      return (event.getAction() == MotionEvent.ACTION_MOVE);
    }
  });

To only hide the scrollbars, but not disable scrolling:
WebView.setVerticalScrollBarEnabled(false);
WebView.setHorizontalScrollBarEnabled(false);

or you can try using single column layout but this only works with simple pages and it disables horizontal scrolling:
   //Only disabled the horizontal scrolling:
   webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

You can also try to wrap your webview with vertically scrolling scrollview and disable all scrolling on the webview:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"    >
  <WebView
    android:id="@+id/mywebview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none" />
</ScrollView>

And set
webview.setScrollContainer(false);

Don't forget to add the webview.setOnTouchListener(...) code above to disable all scrolling in the webview. The vertical ScrollView will allow for scrolling of the WebView's content.

A: Adding the margin details to the body will prevent scrolling if your content properly wraps, as so:
<body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0">

Easy enough, and a lot less code + bug overhead :)

A: If you subclass Webview, you can simply override onTouchEvent to filter out the move-events that trigger scrolling.
public class SubWebView extends WebView {

    @Override
    public boolean onTouchEvent (MotionEvent ev)    {
        if(ev.getAction() == MotionEvent.ACTION_MOVE) {
            postInvalidate();
            return true;
        }
        return super.onTouchEvent(ev);
    }
    ...

A: studying the above answers almost worked for me ... but I still had a problem that I could 'fling' the view on 2.1 (seemed to be fixed with 2.2 & 2.3).
here is my final solution
public class MyWebView extends WebView
{
private boolean bAllowScroll = true;
@SuppressWarnings("unused") // it is used, just java is dumb
private long downtime;

public MyWebView(Context context, AttributeSet attrs)
{
    super(context, attrs);
}

public void setAllowScroll(int allowScroll)
{
    bAllowScroll = allowScroll!=0;
    if (!bAllowScroll)
        super.scrollTo(0,0);
    setHorizontalScrollBarEnabled(bAllowScroll);
    setVerticalScrollBarEnabled(bAllowScroll);
}

@Override
public boolean onTouchEvent(MotionEvent ev)
{
    switch (ev.getAction())
    {
    case MotionEvent.ACTION_DOWN:
        if (!bAllowScroll)
            downtime = ev.getEventTime();
        break;
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
        if (!bAllowScroll)
        {
            try {
                Field fmNumSamples = ev.getClass().getDeclaredField("mNumSamples");
                fmNumSamples.setAccessible(true);
                Field fmTimeSamples = ev.getClass().getDeclaredField("mTimeSamples");
                fmTimeSamples.setAccessible(true);
                long newTimeSamples[] = new long[fmNumSamples.getInt(ev)];
                newTimeSamples[0] = ev.getEventTime()+250;
                fmTimeSamples.set(ev,newTimeSamples);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        break;
    }
    return super.onTouchEvent(ev);
}

@Override
public void flingScroll(int vx, int vy)
{
    if (bAllowScroll)
        super.flingScroll(vx,vy);
}

@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt)
{
    if (bAllowScroll)
        super.onScrollChanged(l, t, oldl, oldt);
    else if (l!=0 || t!=0)
        super.scrollTo(0,0);
}

@Override
public void scrollTo(int x, int y)
{
    if (bAllowScroll)
        super.scrollTo(x,y);
}

@Override
public void scrollBy(int x, int y)
{
    if (bAllowScroll)
        super.scrollBy(x,y);
}
}

A: This should be the complete answer. As suggested by @GDanger .
Extend WebView to override the scroll methods and embed the custom webview within layout xml.
public class ScrollDisabledWebView extends WebView {

    private boolean scrollEnabled = false;

    public ScrollDisabledWebView(Context context) {
        super(context);
        initView(context);
    }

    public ScrollDisabledWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
    }
    // this is important. Otherwise it throws Binary Inflate Exception.
    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY,
                                   int scrollRangeX, int scrollRangeY, int maxOverScrollX,
                                   int maxOverScrollY, boolean isTouchEvent) {
        if (scrollEnabled) {
            return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
                    scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
        }
        return false;
    }

    @Override
    public void scrollTo(int x, int y) {
        if (scrollEnabled) {
            super.scrollTo(x, y);
        }
    }

    @Override
    public void computeScroll() {
        if (scrollEnabled) {
            super.computeScroll();
        }
    }
}

And then embed in layout file as follows
<com.sample.apps.ScrollDisabledWebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    tools:context="com.sample.apps.HomeActivity"/>

Then in the Activity, use some additional methods for disabling scrollbars too.
ScrollDisabledWebView webView = (ScrollDisabledWebView) findViewById(R.id.webView);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);


text:
Q: Convergence of $\max$ and $\min$ sequences of first $n$ terms of a convergent sequence Let $(x_n)$ be a sequence of real numbers converging to $x$.
Define sequences $y_n:=\max\{x_1,x_2,\ldots,x_n\}$ and $z_n:=\min\{x_1,x_2,\ldots,x_n\}$
Now do the sequences $(y_n),(z_n)$ converge? If $(x_n)$ is monotonic , then both  these sequences are convergent. What can we say in general case? Please help me with this. Thanks!

A: $(y_n)$ is monotically increasing. It is also bounded: There exists $N$ such that $\lvert x_n - x \rvert < 1$ for $n \ge N$. Thus $x_n < x + 1$ for $n \ge N$ and thefore $y_n \le \max(y_N,x+1)$ for all $n$. Thus $(y_n)$ converges to some $y \in \mathbb R$. Similarly $(z_n)$ converges to some $z \in \mathbb R$.
However, $z < y$ unless $(x_n)$ is constant: If $(x_n)$ is not constant, then $x_N \ne x_M$ for suitable $N, M$. Let $R = \max(N,M)$. Then $z_R < y_R$ and thus
$$z \le z_R < y_R \le y .$$


text:
Q: Animating word wrap in UILabel during animateAlongsideTransition I have a UILabel in a today widget extension that adjust the constraints of during animateAlongsideTransition. The UILabel uses NSLineBreakByTruncatingTail which allows for word wrapping when numberOfLines is set to 0. My problem is that while the constraints all animate properly, the text inside the UILabel does not change until the animation is finished, resulting in a jump of the text.
Example: UILabel is 100 wide, I animate it to be 130 wide. But the text itself does not fill up that width until the animation is complete.
Any suggestions?


text:
Q: Communicate with another program using subprocess or rpc / rest in python? I have a situation where there is a program which is written in c++. It is a kind of a server which you need to start first. Then from another konsole you can call the program passing commandline arguments and it does stuff. Also it provides rpc and rest based access. So you can write a rpc or rest based library to interface with the server.
So my question is, since the program can be managed using mere commandline arguments, isn't it better to use python's subprocess module and build a library (wrapper) around it? Or is there any problem with this method?
Consider another case. Say I wanted to build a GUI around any linux utility like grep which allows user to test regular expressions (like we have on websites). So isn't it easier to communicate to grep using subprocess?
Thanks.

A: I think I'd prefer to use any of the rpc or rest interfaces, because the results you can obtain from them are usually in a format that is easy to parse since those interfaces have been designed for machine interaction. However, a command line interface is designed for human interaction and this means that the output is easy to parse for the human eye, but not necessarily by another program that receives the output.


text:
Q: assign timestamp in jpa annotation is there a way to automatically assing a timestamp value in a Date variable on a enity EJB?
here is how my enity looks like.
package com.jr.entities;

import java.util.Date;

import javax.persistence.Column;

public class TransactionDAO {

    private String uid;

    private ProductDAO product;

    @Column(name="date")
    private Date date;

    private String customerId;

}

i could not find any examples how this is done or does this have to be done programatically?

A: What do you mean, have an initial value for new objects?
Just initialize it in the object's constructor, or in the field def.


text:
Q: C# Winform close opened window when call other window How can I close an opened window when I call a new window? That means I want only 1 child window at the time. I don't allow multi-window.
public partial class Main_Usr : Form
    {
        public Main_Usr()
        {
            InitializeComponent();
            this.IsMdiContainer = true;

            if (Program.IsFA) barSubItem_Ordre.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            Ordre_Liste f = new Ordre_Liste();
            f.MdiParent = this;
            f.Show();
   }

        private void barButtonItem_CreateOrdre_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Program.AllerRetour = "Ordre Aller";
            Ordre_Fiche f = new Ordre_Fiche();
            f.MdiParent = this;
            f.Show();
        }

        private void barButtonItem_OrdreListe_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Ordre_Liste f = new Ordre_Liste();
            f.MdiParent = this;
            f.Show();
        }

        private void barButtonItem_CreateOrdRet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Program.AllerRetour = "Ordre Retour";
            Ordre_Fiche f = new Ordre_Fiche();
            f.MdiParent = this;
            f.Show();
        }
    }

A: Create Form instances on a class level.
Then you can access to them from events or methods.
    Form1 f1;
    Form2 f2;

void OpenForm1()
{
    f1 = new Form1()
    f1.Show();
}

void OpenForm2()
{
    f1.Dispose(); //or Hide if you want to show it again later
    f2 = new Form2();
    f2.Show();
}

A: There are different ways to implement pseudo masterpage:

*

*You can create BaseForm form with desired layout. Then inherit other forms from this BaseForm and provide custom content.

*You can create MainForm form with desired layout. Then create content controls as UserControls and show them in panel.

*You can create MasterUserControl with desired layout. Then create content controls by inheriting from MasterUserControl (they will have same layout). Then use your main form as browser for displaying different content controls like pages.

EXAMPLE:

*

*Create desired layout on Main_Usr form.

*Do not set it as MdiContainer

*If you want to access some controls (e.g. footer or header from child forms, set property Modifiers of those controls to protected)

*Open Ordre_Liste form code and change it to inherit from Main_Usr form, instead of Form

*Add custom content to Ordre_Liste form

voila! you have 'masterpage'
UPDATE (for 3rd option)

*

*Create new user control with name MasterUserControl

*Create desired layout on this control, keeping space for custom content (btw don't use TableLayoutPanels - they have issue with designer inheritance).

*Create new user control with name HomeUserControl and change it to inherit from your MasterUserControl.

*Open HomeUserControl designer and add custom content. Also you can modify parent controls, which has protected modifier.

*On your main form place HomePageUserControl
There different ways to implement navigation between controls (aka pages). Simplest way - have menu on main form. Other way - define event 'Navigate' on master control, subscribe to that event on main form, and raise it from 'pages'.

A: Like:
List<Form> openForms = new List<Form>();

foreach (Form f in Application.OpenForms)
    openForms.Add(f);

foreach (Form f in openForms)
{
    if (f.Name != "Menu")
        f.Close();
}

Note, do NOT close them directly, becuase there will come to an error, if you would try to close (or dispose) them in the 1st foreach loop. Thats why you need to put them into a list and close them there.


text:
Q: Ubuntu 22.04 Black Screen after Login after clean install Recently upgraded to 22.04 on my desktop, it was running fine until the other morning. At the login screen I put in my password and the screen just goes black. I've tried leaving it for a few minutes to see if it was just being slow but nope.
Steps taken since then:

*

*change from xorg to Wayland and the reverse

*Tried reinstalling the login manager

*Checked to see if the issue was the xorg config

*Disconnected other drives (dual boot with windows and a storage hard drive)

*Tried updating/reinstalling graphics card drivers

I can get into a TTY shell using crtl+alt+F5and everything seems ok. The windows side of the machine is working fine.
Eventually I resolved to just doing full erase and clean install. This didn't work either so I'm fresh out of ideas.
Any help would be very much appreciated :)

A: This happened to me as well on both my old (10 years) Ubuntu machines. It seems that is a common problem with Ubuntu 22.04, the 5.15.0-52 kernel and some older machines, but don't quote me on that.
Some machines are affected at the login while others when waking from suspend. Upgrading to the 5.18.0 kernel seems to fix the issue (check the last message).
In the meantime, I managed to get my PCs back to work by disabling the GPU drivers via nomodeset, here's how to do that:
First, log into a TTY shell and access the GRUB configuration file
sudo nano /etc/default/grub

and replace the value of GRUB_CMDLINE_LINUX: from empty string "" to "nomodeset" as follows
GRUB_CMDLINE_LINUX=""

to
GRUB_CMDLINE_LINUX="nomodeset"

then save the file and update GRUB with
sudo update-grub

Finally, reboot and you should be able to login.


text:
Q: How to tell Wine that I have changed CD when mounting them virtually on a netbook with no CD drive? I have been trying to catch up with some of the old games from way back that are about right for my little Aspire One netbook through Wine.
I've run into a problem Baldurs Gate, however, which is that I can't change CD.
Obviously, I don't have a CD drive, so I have copied the CD content onto an external hard drive and I'm using a mount command with the loopback option to persuade the game that the CD is present. This allowed installation to work correctly and works fine to run it and to play the content from the first CD. However, when the game asks for CD2, I'm stuck.
If I mount the CD2 ISO to the CD Rom path it doesn't appear to respond, whether or not I have first unmounted CD1. When I ask Wine to show me the CD drive it contains the right data, but it seems as though whatever signal would be interpreted by Windows to mean the CD drive has been closed isn't being sent.
Does anyone know of a way to do this, or am I barking up the wrong tree and there is something else I need to do?

A: I found this thread because I was having the same issue. This may not work for everyone, but it did for me. (I made a folder in home called /virtualdrive/Drive0) Also, I had the problem with a different game, but I think it applies.
Mount iso # 1

sudo mount -o loop AOMG_D1.iso ~/virtualdrive/Drive0

Run game installer, hit install. It loads to 32% or something, then asks for iso # 2. Don't try to eject or unmount first iso, just use the same command to mount iso # 2. I think this creates a random drive letter and automatically maps the mount path in wine.
Mount iso # 2

sudo mount -o loop AOMG_D2.iso ~/virtualdrive/Drive0

You should wait 5-10 seconds at this point, and it should continue the installation. If not, try pressing "OK" to the prompt about inserting next disc.
I was actually QUITE surprised this worked.

A: I can't test it right now, but I think you need to use the wine eject command (http://wiki.winehq.org/eject)

A: There's a tutorial that covers this here:
http://wiki.winehq.org/Infinity_Engine_Games
You might try the solution at the bottom of the page first ("AnotherAlternativeToInstall"), as it seems to require fewer steps.
There are also specific things people did to install and run in the entries at winehq for Baldur's Gate.


text:
Q: How to pass data in post request using spread-operator here I am trying to send data to the server through Axios API
but the simple technique is working spread-operator not working
axios(
  method:'post',
  url:'xxx',
  header:{},
  data:{
    ...data // throw error Bad Request
    name:data.name,
    age:data.age // working fine
  }
)


text:
Q: Managing environments branches We have 3 branches development, staging and production. On development we develop our application and it is deployed on dev server, where rest of our department can test it.
When it is ok for them, then it is merged into branch staging, which is deployed on testing server, where our customer can test it and they can develop their testing API client connected to it. When it is ok for our customer, then it is merged into branch production, which is deployed on production server, where our application actually runs.
My questions are:
What to do, when commits B and C are in branch development, and for some reason commit B must be merged into branch staging earlier than commit C. For now we are doing interactive rebase, which cause us problems with local copies and I don't think it is right approach. Should we use cherry-pick, or anything else?
And second follow-up question, is it ok, when these three branches are different (in commits or order of commits)? I am affraid of chaotic log graph and merging with a lot of differences. For now they are absolutely same, but it is causing us some headache (written above).

A: Each feature should be developed in its own branch.
You merge (branch) B and C in develop, then branch B in staging.
That way, you can manage each feature lifecycle independently.
For a more complete workflow, see gitworkflow.


text:
Q: implementing codes in recursion i'm having problem with implementing codes in recursion.
i don't get the way of thinking in that way.
here's a code i wrote to find the 2 max numbers in an array in O(n+logn) Comparisons in inductive way and now i also want to implement recursively.
could you please give me guidelines?
thanks in advance.
here's my inductive code:
package MyPackage;

import java.util.Arrays;
import java.util.Stack;

public class BestIndSol {

    class NodeCircle{
        private int max;
        private Stack<Integer> max2;
        private NodeCircle next;
        private NodeCircle prev;

        public NodeCircle(int max,NodeCircle next, NodeCircle prev){
            this.max=max;
            this.max2 = new Stack <Integer>();
            this.next = next;
            this.prev = prev;
        }
        public void addmax2(int num){
            this.max2.add(num);
        }
        public int getMax() {
            return max;
        }
        public void setMax(int max) {
            this.max = max;
        }
        public int Max2(){
            int maxs = Integer.MIN_VALUE;
            if(!this.max2.isEmpty())
            maxs = (this.max2.pop());
            while(!this.max2.isEmpty()){
                if(maxs<this.max2.peek())
                    maxs = this.max2.pop();
                else
                    this.max2.pop();
            }
            return maxs;
        }
    }
    public NodeCircle Array2CircledLL(int[] arr){
        NodeCircle head  = new NodeCircle(arr[0],null,null);
        NodeCircle temp = head;
        NodeCircle Now=null;
        for(int i = 1;i<arr.length;i++){
            Now = new NodeCircle(arr[i], null,temp );
            temp.next = Now;
            temp=temp.next;
        }
        Now.next = head;
        head.prev = Now;
        return head;
    }
    public static int [] randarr(int size){
        int [] arr = new int[size];
        for(int i =0;i<size;i++){
            arr[i] = (int)(Math.random()*1000);
        }
        return arr;
    }
    public void TheSolution(){
        int[] a = randarr(100);
        int size = a.length;
        NodeCircle c = Array2CircledLL(a);
        System.out.println("Array is:" + Arrays.toString(a));
        NodeCircle temp1= c;
        NodeCircle temp2  = null;
        while(size>1){
            temp2 = temp1.next;
            if(temp1.max>temp2.max){
                temp1.max2.push(temp2.max);
                temp1.next = (temp2.next);
                temp2.next.prev = temp1;
                temp1=temp1.next;
                size--;

            }
            else{
                temp2.max2.push(temp1.max);
                temp2.prev = (temp1.prev);
                temp1.prev.next = temp2;
                temp1=temp1.next;
                size--;
            }
        }
        System.out.println("max is:" + temp1.max);

        System.out.println("Max2 is: "+temp1.Max2());
    }

    public static void main(String[] args) {
        BestIndSol s = new BestIndSol();
        s.TheSolution();

    }

}


text:
Q: refresh div after X seconds using jquery and ajax i found this code for refresh my div using jquery. this worked but i have any problem. this plugin always refreshed my div and print result. this bad idea. i need to print div and result when result != 0. in my i.e jquery print 0 in result div. any way for this solutions ? thanks
jquery code :
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000);
<body>
<div id="load_tweets"> </div>

record_count.php ( very simple ) result = 0
0

A: var auto_refresh = setInterval(function(){
    $.ajax({
        url:'record_count.php',
        sucsess:function(data){
        if(data!=0)
            $('#load_tweets').html(data).fadeIn("slow");
        }
    });
}, 10000);

A: Try with this:
var auto_refresh = setInterval(function () {
    $.get('record_count.php', null, function(data) {
        if (data != "0") {
            $('#load_tweets').html(data).fadeIn("slow");
        }
    }, "html")
}, 10000);


text:
Q: how to get the time after two minutes I have a to execute a command automatically after two minutes from the current date using shell scripting. Lets say my current time is in below format. The script should read the current time ,add two minutes to the existing time which will be 2014-09-10T09-23-34 and then execute the remaining script.
date +"%Y"-"%m"-"%d"T"%H"-"%M"-"%S"

2014-09-10T09-21-34

A: Use:
sleep(120)

the program will get to the line this command is in, wait 120 seconds (2 minutes), and continue its execution.
Next time please try googling first, you can find it easily through there.
EDIT: if for some reason you insist on not using sleep you can use:
import time
start = time.time()
while (time.time() - start) < 120:
    pass

A: To get the date-string in bash:
echo "Current: " $(date +"%Y"-"%m"-"%d"T"%H"-"%M"-"%S")
echo "+2 min : " $(date --date="@$(($(date +%s)+120))" +"%Y"-"%m"-"%d"T"%H"-"%M"-"%S")

prints
Current:  2014-09-10T15-58-15
+2 min :  2014-09-10T16-00-15

Read the time from string and print +2min string
str="2014-09-10T15-58-15"
new=$(date --date="@$(($(
        IFS="-T" read y m d H M S <<< "$str";date --date="$y-$m-${d}T$H:$M:$S" +%s
    )+120))" +"%Y"-"%m"-"%d"T"%H"-"%M"-"%S")
echo "From string: $str"
echo "String +2m : $new"

prints
From string: 2014-09-10T15-58-15
String +2m : 2014-09-10T16-00-15

Execute an command from the "current time", as others already says, use:
sleep 120 ; commands...

Execute a command 2 minute later as is specified in the string:
sec2date() { date --date="@$1"; }
countdown() { s="$1";while (($s)) ; do printf "%04d\r" $s; sleep 1; let s--; done; }

str="2014-09-10T16-55-10"

current=$(date +%s)
stringsec=$(IFS="-T" read y m d H M S <<< "$str";date --date="$y-$m-${d}T$H:$M:$S" +%s)
wanted=$(date --date="@$(($stringsec + 120))" +%s)

diffsec=$(($wanted - $current))
(( $diffsec > 0 )) || { echo "Can't execute in the past" ; exit 1; }

echo "time in the string :" $(sec2date $stringsec)
echo "+2min = execute at :" $(sec2date $wanted)
echo "current time       :" $(date)
echo "need wait          :" $diffsec
countdown $diffsec
echo "running at         :" $(date)

prints
time in the string : st sep 10 16:55:10 CEST 2014
+2min = execute at : st sep 10 16:57:10 CEST 2014
current time       : st sep 10 16:56:52 CEST 2014
need wait          : 18
running at         : st sep 10 16:57:10 CEST 2014

or, simply use the at command. :) :)

A: use (cmd is your command):
sleep 120 && cmd
eventually use this python 2.7 script (saved as cron.py):
import datetime
import os
import sys

d = datetime.datetime.now() + datetime.timedelta(minutes=2)
txt = "%s %s %s %s * %s " % (d.minute, d.hour, d.day, d.month, sys.argv[1])
print txt
os.system( "echo '" + txt + "' >> /var/spool/cron/crontabs/root")

and then run:
python cron.py cmd
In that case it won't be exactly 120s.


text:
Q: How can I find the value of $c$ given an odd function with these intervals? An odd function which is defined for all real numbers $x$ has these intervals: $(-3, 5)$, $(-2, -4)$, $(2, c)$.
How can I find the value of $c$? I have no idea on this one.

A: I assume you mean $(-2,-4)$ as the $(x,y)$ coordinates through which the odd function passes, since otherwise the question does not make any sense. If so, then since $f(-x)=-f(x)$ for an odd function, $f(2)=f(-(-2))=-f(-2)=-(-4)=4$, i.e., $f(2)=4$.


text:
Q: JavaScript code working fine on codepen but not working on fiddle. Couldn't able to find Codepen URL: https://codepen.io/pkprabu/pen/zmRqgZ

hi i'm new to JavaScript and working on some code. Problem is that the same code working fine on codepen but not working on fiddle and my page. I couldn't able to find that why its workig on codepen but not on fiddle & what is going on. I have given my codepen url above also. Please explain me & help me to fix this.

"use strict";

// vars
var result = document.querySelector(".result"),
  img_result = document.querySelector(".img-result"),
  img_w = document.querySelector(".img-w"),
  img_h = document.querySelector(".img-h"),
  options = document.querySelector(".options"),
  save = document.querySelector(".save"),
  cropped = document.querySelector(".cropped"),
  dwn = document.querySelector(".download"),
  upload = document.querySelector("#file-input"),
  cropper = "";
// on change show image with crop options
upload.addEventListener("change", function(e) {
  if (e.target.files.length) {
    // start file reader
    var reader = new FileReader();
    reader.onload = function(e) {
      if (e.target.result) {
        $(".modal").modal("show");
        // create new image
        var img = document.createElement("img");
        img.id = "image";
        img.src = e.target.result;
        // clean result before
        result.innerHTML = "";
        // append new image
        result.appendChild(img);
        // show save btn and options
        save.classList.remove("hide");
        options.classList.remove("hide");
        // init cropper
        cropper = new Cropper(img);
      }
    };
    reader.readAsDataURL(e.target.files[0]);
  }
});
// save on click
save.addEventListener("click", function(e) {
  e.preventDefault();
  // get result to data uri
  var imgSrc = cropper.getCroppedCanvas({
    width: img_w.value // input value
  }).toDataURL();
  // remove hide class of img
  cropped.classList.remove("hide");
  img_result.classList.remove("hide");
  // show image cropped
  cropped.src = imgSrc;
  dwn.classList.remove("hide");
  dwn.download = "imagename.png";
  dwn.setAttribute("href", imgSrc);
});
$(".upload-button").on("click", function() {
  $("#file-input").trigger("click");
});
i:hover {
  cursor: pointer;
}

.dashboard-hme-img {
  max-height: 100%;
  max-width: 100%;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
}
<link href="https://cdn.paperindex.com/bootstrap/css/font-awesome.min.css" rel="stylesheet">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css">

Update

<input id="file-input" class="hidden" type="file" accept="image/*" />

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

            <input type="hidden" class="img-w" value="200" min="200" max="1200" />

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button><button class="btn save hide">Save</button>

A: You forget CSS File cropper.min.css
https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css

https://jsfiddle.net/2gda1Lho/


text:
Q: Quotient group of free product of groups I am trying to understand this theorem from Munkres:
If $G$ is the free product $G_1*G_2$, and $N_1$,$N_2$ are some normal subgroups of $G_1$ and $G_2$, respectively, and $N$ is the least normal subgroup of $G$ containing $N_1$ and $N_2$, then
$G/N \cong  (G_1/N_1)*(G_2/N_2)$
I cannot convince myself that $G \longrightarrow  (G_1*G2)/N \space$ will map $N_1$ to identity.
Can anyone see why that holds ?

A: $N_1$ is contained in $N$, so since $G \to G/N$ maps $N$ to identity, it also sends $N_1$ to identity.


text:
Q: How to resize the buffered image n graphics 2d in java? int width = 175;
Graphics2D gb = (Graphics2D) g;

        bufferedimage = (BufferedImage) createImage(width, width);

        Graphics2D graphics = bufferedimage.createGraphics();
        graphics.setColor(/*this.getBackground()*/Color.red);
        graphics.fillRect(0, 0, width, width);

hi i have the the buffered with big size...i have to resize the bufferd image...plz can u anyone help me?

A: public BufferedImage scaleImage(BufferedImage img, int width, int height,
        Color background) {
    int imgWidth = img.getWidth();
    int imgHeight = img.getHeight();
    if (imgWidth*height < imgHeight*width) {
        width = imgWidth*height/imgHeight;
    } else {
        height = imgHeight*width/imgWidth;
    }
    BufferedImage newImage = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g = newImage.createGraphics();
    try {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setBackground(background);
        g.clearRect(0, 0, width, height);
        g.drawImage(img, 0, 0, width, height, null);
    } finally {
        g.dispose();
    }
    return newImage;
}

UPDATE: different algorithms
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

public enum Resizer {
    NEAREST_NEIGHBOR {
        @Override
        public BufferedImage resize(BufferedImage source,
                int width, int height) {
            return commonResize(source, width, height,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        }
    },
    BILINEAR {
        @Override
        public BufferedImage resize(BufferedImage source,
                int width, int height) {
            return commonResize(source, width, height,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
    },
    BICUBIC {
        @Override
        public BufferedImage resize(BufferedImage source,
                int width, int height) {
            return commonResize(source, width, height,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        }
    },
    PROGRESSIVE_BILINEAR {
        @Override
        public BufferedImage resize(BufferedImage source,
                int width, int height) {
            return progressiveResize(source, width, height,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
    },
    PROGRESSIVE_BICUBIC {
        @Override
        public BufferedImage resize(BufferedImage source,
                int width, int height) {
            return progressiveResize(source, width, height,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        }
    },
    AVERAGE {
        @Override
        public BufferedImage resize(BufferedImage source,
                int width, int height) {
            Image img2 = source.getScaledInstance(width, height,
                    Image.SCALE_AREA_AVERAGING);
            BufferedImage img = new BufferedImage(width, height,
                    source.getType());
            Graphics2D g = img.createGraphics();
            try {
                g.drawImage(img2, 0, 0, width, height, null);
            } finally {
                g.dispose();
            }
            return img;
        }
    };

    public abstract BufferedImage resize(BufferedImage source,
            int width, int height);

    private static BufferedImage progressiveResize(BufferedImage source,
            int width, int height, Object hint) {
        int w = Math.max(source.getWidth()/2, width);
        int h = Math.max(source.getHeight()/2, height);
        BufferedImage img = commonResize(source, w, h, hint);
        while (w != width || h != height) {
            BufferedImage prev = img;
            w = Math.max(w/2, width);
            h = Math.max(h/2, height);
            img = commonResize(prev, w, h, hint);
            prev.flush();
        }
        return img;
    }

    private static BufferedImage commonResize(BufferedImage source,
            int width, int height, Object hint) {
        BufferedImage img = new BufferedImage(width, height,
                source.getType());
        Graphics2D g = img.createGraphics();
        try {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
            g.drawImage(source, 0, 0, width, height, null);
        } finally {
            g.dispose();
        }
        return img;
    }
};


text:
Q: Python or Shell assistance: How to search for a word and replace only the value next to it I have a text file (list.txt) with the following format:
Apple 1
Banana 5.0
orange_1 0.5

The list can go on for many lines. I would like to ultimately search for the word "Apple" and only replace the value next to it. I know how to use a "sed" command that can search and replace a word but I don't know how I can search for a word and replace only the value next to it?
the sed command I use in my script is a s follows:
sed "s/Apple/$1/g" list.txt > newlist.txt

where $1 is defined in a run script and could be anything (e.g. grape). Again this would switch the word Apple and not the value next to it. I would like to be able to perform this action either by using a SHELL or Python command. Any help would be fantastic!

A: Here I show positive lookback way as @ryugie said:
content = '''Apple 1
Banana 5.0
orange_1 0.5'''

def my_replace(content, fruit, value):
    import re
    return re.sub(r'(?<=' + fruit + ' )([\d\.]+)', str(value), content)

print my_replace(content, 'Apple', 4.0)

print my_replace(content, 'Banana', 1.5)

And we can get:
Apple 4.0
Banana 5.0
orange_1 0.5

Apple 1
Banana 1.5
orange_1 0.5

A: Assuming that each line starts with the key and the value is the rest of the line after a space, you can use the following sed command to replace only the value:
sed "s/\(^Apple \)\(.*$\)/\1$1/"

Please note that this might be a fragile/insecure solution depending on the replacement value, e.g. if $1 contains /, it can be used for a command insertion like /;d;s//.
A more robust solution with awk:
awk -v new="$1" '{print ($1 == "Apple") ? ($1 " " new) : $0}'

UPD. Both commands can work with files either directly or via standard streams:
sed ... file.txt > new.txt
cat file.txt | sed ... | cat > new.txt

(do not use cat like this, it's here to show piped input/output). Additionally, some versions of sed have option -i to change file in place:
sed -i ... file.txt


text:
Q: Are python decorators invoke the returned callback immediately? I am trying to understand decorators behavior by doing some experiments. I am not able to find any doc on what I am seeing, so may be someone can point me to something.
Here is the code using a decorator:
def register():
    def func_wrapper(func):
        print 'registered'
    return func_wrapper

@register()
def main_page_func():
    pass

When you run this code, you will get the word "registered" printed out:
registered

This is presumably the equivalent(?) code without decorator:
def register(func):
    def func_wrapper():
        print 'registered'
    return func_wrapper

def main_page_func():
    pass

main_page_func = register(main_page_func)

When you run the above, nothing gets printed out. I understand this case: func_wrapper callback is returned.
However, I am still struggling with the first case that uses decorator: Why is print statement being invoked given that main_page_func is never being called?
Thanks.

A: When you say,
@register()

it actually calls the function register() and the return value is used there, which will be func_wrapper, which accepts a function object as input. So, what you have done is
@func_wrapper
def main_page_func():
    pass

And when you decorate it like this,
main_page_func = func_wrapper(main_page_func)

func_wrapper is invoked and that is why the registered is getting printed.
To actually fix this, you need to pass the function object to register itself, like in your second example,
def register(func):         # func should be here
    def func_wrapper():     # not here
        print 'registered'
    return func_wrapper

@register                   # no parens after `register`
def main_page_func():
    pass

Now, the evaluation is like this
main_page_func = register(main_page_func)

Since the func_wrapper is not yet executed, you will not see registered getting printed, yet.

A: Erase the parentheses after the decorator and it will work just as you expect it to.
Also, your register function should take the argument func, but not neccessarily your inner function.


text:
Q: yii - how to theming widgets in modules I have directory structure like:
   .
   |-config
   |-modules
   |---articles
   |---catalog
   |-----components
   |-----controllers
   |-----fixtures
   |-----migrations
   |-----models
   |-----views
   |-----widgets <----------------- MY WIDGETS
   |------ FooWidget.php
   |-------views
   |--------- foo.php <--- default view, not working
   |-runtime
   |-tests
   |-themes
   |---XXXX
   |-----assets
   |-----views
   |-------catalog <--------------- MODULE VIEWS
   |-------layouts
   |-------widgets
   |-views
   |-widgets

I call $this->widget('application.modules.catalog.widgets.FooWidget') - and catch exception CException - view not found.
How to theming widgets inside modules?

A: According to the manual
your widget views should be in /themes/XXXX/views/FooWidget/foo.php.


text:
Q: embedded image in textbox and email vb i try to display image in textbox then whatever is in textbox i am trying to send it in email.. all content is displayed and send in email but image is not displayed in textbox and also not send
txtEmailBody.Text = txtEmailBody.Text & "Tel:2345" & vbCrLf
    txtEmailBody.Text = txtEmailBody.Text & "Cell:435360 " & vbCrLf
    txtEmailBody.Text = txtEmailBody.Text & "Fax:3432456" & vbCrLf
    txtEmailBody.Text = txtEmailBody.Text & "Cell:+3456" & vbCrLf
    txtEmailBody.Text = "
Picture

"
    Dim avHtml As AlternateView = AlternateView.CreateAlternateViewFromString(txtEmailBody, Nothing, MediaTypeNames.Text.Html)
    Dim pic1 As New LinkedResource("../images/logo_deg.gif", MediaTypeNames.Image.Gif)
    pic1.ContentId = "Pic1"
    avHtml.LinkedResources.Add(pic1)

but this shows error
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files\images\logo_deg.gif'.
in this line
Dim pic1 As New LinkedResource("../images/logo_deg.gif", MediaTypeNames.Image.Gif)

when i add file in c drive this shows an error
A potentially dangerous Request.Form value was detected from the client (ctl00$ContentPlaceHolder1$txtEmailBody="...

A: Ok first things first:
Read the MSDN Textbox you will see TextBox do not support images. So either you can:

*

*Create a Custom Textbox control

*Show directly the HTML Render with the image in WebBrowser

*Add a PictureBox next to the TextBox

Secondly you can easily add Embeded Images to Email with the simple use of Base64 converstion
Add this as HTML:

And you can easily implement a function in your application to transform your images to Base64
Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
    Using ms As New MemoryStream()
        ' Convert Image to byte[]
        image.Save(ms, format)
        Dim imageBytes As Byte() = ms.ToArray()

        ' Convert byte[] to Base64 String
        Dim base64String As String = Convert.ToBase64String(imageBytes)
        Return base64String
    End Using
End Function

And then can just call it like this for example if have a local jpg file or can directly call it from My.Resources if take off the Image.FromFile
MyBody =


text:
Q: Find index of n biggest values I have a 2D ndarray as follows:
[[     0      0   1024   1024 572911]
 [     0      0    822   1024 316522]
 [   700      0     95     40   2189]
 [   986     72     38     37    648]
 [   933    158     50     51    823]
 [   720    172     39     85   1806]
 [   863    204    161    255  12329]
 [   407    275     55     34    838]
 [   522    414    234    161  12692]
 [   861    547     49     73   1373]
 [   972    564     52     49   1252]
 [   929    577     25     42    376]
 [   703    608     37     64   1082]
 [   565    612    106    152   6278]
 [   556    615    468    409 113116]
 [   114    674     43     44    478]
 [   155    733    150     53   3505]
 [    57    991     23     30    358]]

and I want to find the index of the n subarrays that maximize the last value in the subarray.
In this case, for n=2 the result would be [0, 1]. What means the arrays are [     0      0   1024   1024 572911] and [     0      0    822   1024 316522]. How can I achieve that?


text:
Q: How to assert that an Uni throws a given error? I have a reactive Quarkus project and I'm trying to test a method that returns Uni<User>. The method looks like this:
public Uni<User> searchUser(ObjectId userId) {
        return userRepository
            .findById(userId)
            .map(user -> {
                if (user != null) {
                    return user;
                } else {
                    throw new BusinessException("Could not find an user with the given id.");
                }
            });

So far, so good. Now I'm trying to test a method asserting that an error is thrown when the repository returns null on findById. According to mutiny's documentation, this is how you assert that an Uni throws an error:
Multi<Object> multi = Multi.createFrom().failure(() -> new IOException("Boom"));

AssertSubscriber<Object> subscriber = multi
        .subscribe().withSubscriber(AssertSubscriber.create(10));

subscriber.assertFailedWith(IOException.class, "Boom");

This is my adapted version:
        @Test
        public void shouldThrowAnErrorWhenUserIsNotFound() {
            Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Uni.createFrom().nullItem());

            AssertSubscriber subscriber = service.searchUser(new ObjectId()).subscribe().withSubscriber(AssertSubscriber.create());

            subscriber.assertFailedWith(BusinessException.class, "Could not find an user with the given id.");
        }

But it doesn't build. I get this error on the

.subscribe().withSubscriber()call:Inferred type 'S' for type parameter 'S' is not within its bound; should implement 'io.smallrye.mutiny.subscription.UniSubscriber<? super br.com

How can I fix this? Or is there another way to write such a test?

A: Removing the AssertSubscriber assignment fixed the type error, and now the test is working as expected.
        @Test
        public void shouldThrowAnErrorWhenUserIsNotFound() {
            Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Uni.createFrom().nullItem());

            service.searchUser(new ObjectId())
                    .subscribe()
                    .withSubscriber(UniAssertSubscriber.create())
                    .assertFailedWith(BusinessException.class, "Could not find an user with the given id.");
        }


text:
Q: xpages required property for a combobox There is a djContainer having multiple djtabPane(s).
A combobox is situated on the first djtabPane, having the property: required="true".
but, when I move to next djtabPane in order to complete some other fields, I get the notification that the combobox value is required.
Can I achieve this property of the combobox but only if I want to submit / save the doc.?
<xe:djTabContainer id="djContentPane1" tabPosition="top" doLayout="false">

and the djTabPane ( all are the same, only the title is different ) :
<xe:djTabPane id="djTabPane1" title="Title1">

A: You'll need to move the validation to your save/submit method. A validator runs whenever a partial refresh happens unless you set immediate="true" or processValidators="false". But I don't think there's a way to set that on any of the in-built tabbed containers.
The advantage of Greg's approach when moving towards an MVC pattern is that the same validation can be run whenever saving the data object, not just from a specific XPage / Custom Control. The down-side is more work coding what's effectively in-built, e.g. tying the validation message back to the relevant component, setting the component's valid property to false etc.


text:
Q: Ant exec task using cURL to POST a JSON body doesn't work, identical command works manually in Windows command prompt I'm running this task as part of a larger target in an Ant script. It executes a command in the Windows command prompt and routes the output to a text file in the temp directory. I've changed the URL argument to protect sensitive information.
<exec executable="cf.cmd" output="${java.io.tmpdir}/cmd_out.txt" failonerror="true" vmlauncher="false">
    <arg value="curl" />
    <arg value="POST" />
    <arg value="http://www.google.com/v2/routes" />
    <arg value="--body" />
    <arg value="'{"host": "${old.app.name}", "domain_guid": "${domain.guid}", "space_guid": "${space.guid}"}'" />
</exec>

From Ant's verbose logs, this task produces the following command:
Current OS is Windows 7
[exec] Output redirected to C:\Users\foo\AppData\Local\Temp\cmd_out.txt
[exec] Executing 'cf' with arguments:
[exec] 'curl'
[exec] 'POST'
[exec] 'http://www.google.com/v2/routes'
[exec] '--body'
[exec] ''{"host": "foo", "domain_guid": "4cc4c9b0-5b87-40f5-8ecc-6d6347a3236d", "space_guid": "6c3338e2-422d-46c0-a901-eda41b1fd968"}''
[exec]
[exec] The ' characters around the executable and arguments are
[exec] not part of the command.

When run, this task produces the following output in cmd_out.txt:
{
  "code": 1001,
  "description": "Request invalid due to parse error: lexical error: invalid char in json text.\n                                      {host: foo, domain_guid\n                     (right here) ------^\n
  "error_code": "CF-MessageParseError
  "types": [
    "MessageParseError
    "Error"
  ],
  "backtrace": []
}

However, if I execute this identical command manually in the Windows command prompt:
cf curl POST http://www.google.com/v2/routes --body '{"host": "foo", "domain_guid": "4cc4c9b0-5b87-40f5-8ecc-6d6347a3236d", "space_guid": "6c3338e2-422d-46c0-a901-eda41b1fd968"}'

Then I get the correct result. No point in posting it here, but it's a success message instead of an invalid parse error message.
If I run this command in the manual Windows command prompt (notice the lack of single quotes around the JSON body), then I get the same error as the Ant script:
cf curl POST http://www.google.com/v2/routes --body {"host": "foo", "domain_guid": "4cc4c9b0-5b87-40f5-8ecc-6d6347a3236d", "space_guid": "6c3338e2-422d-46c0-a901-eda41b1fd968"}

I'm at a loss here. From what I can see, Ant is running the same command as what I am doing manually. Yet the Ant version fails, and the manual version succeeds. Can anyone see what I'm doing wrong?

A: Looks like the spaces were causing the problem. Changing the exec task to the following works great:
<exec executable="cf.cmd" output="${java.io.tmpdir}/cmd_out.txt" failonerror="true" vmlauncher="false">
    <arg value="curl" />
    <arg value="POST" />
    <arg value="http://www.google.com/v2/routes" />
    <arg value="--body" />
    <arg value="'{"host":"${old.app.name}","domain_guid":"${domain.guid}","space_guid":"${space.guid}"}'" />
</exec>


text:
Q: Fast method to cycle through multiple lists of tuples to find max of each tuple list I have tens of thousands of lists of tuples, where each tuple within a list consists of an (int, float) pair. I want to be able to cycle through all the lists of tuples to find the (int, float) pair where the float is the maximum value of the float in the list of tuples. Consider several lists of tuples:
[
[(0, 0.3792), (3, 0.5796)],
[0, 0.9365), (1, 0.0512), (18, 0.0123),
[(13, 0.8642)],
[(0, 0.6249), (1, 0.01), (2, 0.01), (3, 0.01), (4, 0.01), (5, 0.01)]
]

For each list of tuples, I want to find the pair where the second number is maximized (e.g., for the first list, I want (3, 0.5796); for the 4th item, (0, 0.6249) should be returned). My current approach is to turn the tuples into numpy arrays and then find argmax and max:
def get_max(doc: List[Tuple[int, float]]) -> Tuple[int, float]:

   topic_prob_array = np.array(doc, dtype=np.dtype('int,float'))
   return topic_prob_array['f0'][np.argmax(topic_prob_array['f1'])], np.max(topic_prob_array['f1'])

I was hoping to turn this into a numpy vectorized function (via vec_func = np.vectorized(get_max, otypes=[int,float]) or numpy ufunc (via vec_func = np.fromfunc(get_max, nin=1, nout=1). I not sure if I am formatting the input and output correctly. My reasoning is that I am sending in a single list of tuples and return a single tuple, hence nin=1, nout=1. However, I have not been able to successfully get a vectorized version of this to run.
I also tried a solution without relying on numpy:
def get_max(doc: List[Tuple[int, float]]) -> Tuple[int, float]:

   ids, probabilities = zip(*doc)
   return ids[np.argmax(probabilities)], np.max(probabilities)

Both take about the same amount of time to run. For my list of about 80k, this takes about 1 minute, 10 seconds for both implementations. I'd really like to get this down if it's possible.

A: The optimized non-numpy solution to this is:
from operator import itemgetter

get1 = itemgetter(1)

all_lists = [...]  # Whatever your actual list of list of tuples comes from

all_maxes = [max(lst, key=get1) for lst in all_lists]

numpy isn't likely to gain you much, since the work done is relatively cheap, and if you're only converting to numpy arrays for a single operation, the scope of benefit is smaller.

A: Do you need to use numpy for this? We can take a functional approach and map the max function with a custom key across the whole data set.
from functools import partial
from operator import itemgetter

snd = itemgetter(1)
p = partial(max, key=snd)
list(map(p, data))
>>> [(3, 0.5796), (0, 0.9365), (13, 0.8642), (0, 0.6249)]

Then a quick timing across 80K random tuples from your original dataset.
from random import choice

result = []
for _ in range(80_000):
    result.append(choice(data))

%timeit list(map(p, result))
42.2 ms ± 686 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: Like @gold_cy mentioned, I'm not sure if you're looking for a numpy answer. A non-numpy answer could be:
list_tuple = [
    [(0, 0.3792), (3, 0.5796)],
    [(0, 0.9365), (1, 0.0512), (18, 0.0123)],
    [(13, 0.8642)],
    [(0, 0.6249), (1, 0.01), (2, 0.01), (3, 0.01), (4, 0.01), (5, 0.01)]
]

[sorted(tup, key=lambda x: x[1], reverse=True).pop(0) for tup in list_tuple]

>>> [(3, 0.5796), (0, 0.9365), (13, 0.8642), (0, 0.6249)]

A: In [462]: alist
Out[462]:
[[(0, 0.3792), (3, 0.5796)],
 [(0, 0.9365), (1, 0.0512), (18, 0.0123)],
 [(13, 0.8642)],
 [(0, 0.6249), (1, 0.01), (2, 0.01), (3, 0.01), (4, 0.01), (5, 0.01)]]
In [463]: blist = alist*10000    # bigger test list

Playing around with alternatives, I found this "brute force" function is fastest (though not by much):
def get_max3(doc):
    m = doc[0]
    for i in doc[1:]:
        if i[1]>m[1]: m=i
    return m

For the small list, the list comprehension is slightly faster, for the big list, the map version has the edge - but not by much.
In [465]: [get_max3(i) for i in alist]
Out[465]: [(3, 0.5796), (0, 0.9365), (13, 0.8642), (0, 0.6249)]

In [466]: timeit [get_max3(i) for i in alist]
1.9 µs ± 51.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [467]: timeit list(map(get_max3,blist))
15 ms ± 7.77 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Versions using numpy are all much slower; it takes time to convert the list of tuples into a numpy array (even structured array).


text:
Q: Receiving error I don't understand using Smartadmin Bootstrap Datatables Hi I'm trying to implement a Datatable to a webpage that is rendered using Perl and Template Toolkit.
I'm receiving a pop-up error from the data table when it is rendered
This is the error:
DataTables warning: table id=datatable_tabletools - Requested unknown
parameter '1' for row 1. For more information about this error, please see
http://datatables.net/tn/4

I've read the documentation on this error but I'm still unsure as to why I'm receiving it
Here is the code I believe it is related to.

                    ID
                    thing
                    otherthing
                    anotherthing
                    morething
                    something

                  [% FOREACH item IN list%]

                    [% item.var%]
                    [% item.var1%]
                    [% item.var2%]
                    [% item.var3 FILTER currency %]
                    [% item.var4%]
                    [% item.var5%]
                       View

A: The documentation provided in the error, explains it very well.https://datatables.net/manual/tech-notes/4
Each cell in DataTables requests data, and when DataTables tries to obtain data for a cell and is unable to do so, it will trigger a warning, telling you that data is not available where it was expected to be

DataTables warning: table id={id} - Requested unknown parameter '{parameter}' for row {row-index}, column{column-index}`

where:
{id} is replaced with the DOM id of the table that has triggered the error
{parameter} is the name of the data parameter DataTables is requesting
{row-index} is the DataTables internal row index (row().index()API) for the row that has triggered the error.
{column-index} is the column data index (column().index()API) for the column that has triggered the error. The column index information was added in DataTables 1.10.10.
So to break it down, DataTables has requested data for a given row, of the {parameter} provided and there is no data there, or it is null or undefined (DataTables doesn't know, by default how to display these parameters - see below if your data does contain these values).
id in your case being datatable_tabletools
parameter in your case being 1
row-index in your case being row 1
Finally, to give you a short answer, column 1 row 1 in datatable_tabletools does not contain the data it is expecting, it is either null or empty or incorrect format.
So have a look at what the code is requesting and see what is not in the table.


text:
Q: How to use _spawn or _exec for bootstrapping? After writing the following program, it does not appear to pass arguments to the called application. While researching _spawnv and what it can do, _execvp was found as what appeared to be a suitable alternative. Does anyone see the problem in the source code and know what needs to be done to fix it?
#include <stdio.h>
#include <stdlib.h>
#include <process.h>

int main(int argc, char** argv)
{
    int index;
    char** args;
    args = (char**) malloc((argc + 1) * sizeof(char*));
    args[0] = "boids.py";
    for (index = 1; index < argc; index++)
    {
        args[index - 1] = argv[index];
    }
    args[argc] = NULL;
    return _execvp("python", args);
}

A: The first argument in the argv vector is conventionally the fully qualified name of the executable to be started:

The _spawnv, _spawnve, _spawnvp, and
  _spawnvpe calls are useful when there is a variable number of arguments to
  the new process. Pointers to the
  arguments are passed as an array,
  argv. The argument argv[0] is usually
  a pointer to a path in real mode or to
  the program name in protected mode,
  and argv1 through argv[n] are
  pointers to the character strings
  forming the new argument list. The
  argument argv[n +1] must be a NULL
  pointer to mark the end of the
  argument list.

(From MSDN)
Likewise:

The _execv, _execve, _execvp, and
  _execvpe calls are useful when the number of parameters to the new
  process is variable. Pointers to the
  parameters are passed as an array,
  argv. The parameter argv[0] is usually
  a pointer to cmdname. The parameters
  argv1 through argv[n] point to the
  character strings forming the new
  parameter list. The parameter
  argv[n+1] must be a NULL pointer to
  mark the end of the parameter list.

(MSDN)


text:
Q: How to organize angular workspace to share some components between subprojects? I have Angular CLI workspace that contains 4 UI application and 1 library which is API consumer.
Now there is a need to share some components between UI applications. I don't want to create separate library project because every change in shared component will require developer to rebuild the library in order to see the changes in the UI.
Are there any good practices on that topic?
Options that I think of are:

*

*As the last resort - create library project and build it everytime

*Dont care about separation, just import components between projects eg in project A do import ../../projects/B/app/src/ComponentFromB

*Create library project, but never build it but rather split components in that project into separate modules - like Angular Material components - and import modules directly

3 is kind of mix of 1 and 2 with addition on creating module per component/utility. Maybe module/component is not needed and I could directly import components and redelare them in "local" shared modules whenever it is needed?
Any other alternatives?

A: There are different approaches to this.
First of all, it's usually required to create a library or separate project due to versioning.
If you intend to use this components in two different projects there will be times where you wouldn't want to use latest component version on both sides. For example - new version of component works on one project, but breaks layout on the other one. Or it's just broken, incompatible, etc.
To work with multiple projects there are numerous tools already, one of the most popular is lerna https://github.com/lerna/lerna though it can be an overkill for your task.
If you're worried about building new version very time - other solution would be to build this library and serve prebuilt version via internal CDN. For example gitlab provides NPM registry out of the box, so CI/CD could be building a new version and publishing there. This way you can use prebuilt version of the library and not rebuild it every time.
The easy way here is to use a git submodule and include in two different project repos. This is very easy to do, but be wary that submodules aren't very nice to work with in a longer term.


text:
Q: Scaling Figure side by side with tkz-euclide I am trying to put two figures side by side but the right one should be scaled by a certain factor to appear bigger than the one left figure. My progress so far is the following code. I tried looking at the manual but I cannot read French.
\documentclass[tikz]{standalone}
\usepackage{tkz-euclide}
\usetkzobj{all}

\begin{document}
    \begin{tikzpicture}
        %Define Points
        \tkzDefPoint (0,0){A}
        \tkzDefPoint (4,0){B}
        \tkzDefPoint (5,1){C}
        \tkzDefPoint (3,2){D}
        \tkzDrawPolygon[fill=blue!40, very thick](A,B,C,D)

        %Label Points
        \tkzLabelPoint[left](A){A}
        \tkzLabelPoint(B){B}
        \tkzLabelPoint(C){C}
        \tkzLabelPoint[above](D){D}
        %Shift the Points
        \tkzDefShiftPoint[A](3 in, 0in){A'}
        \tkzDefShiftPoint[B](3 in, 0in){B'}
        \tkzDefShiftPoint[C](3 in, 0in){C'}
        \tkzDefShiftPoint[D](3 in, 0in){D'}
        \tkzDrawPolygon[fill=green!40, very thick,scale=3](A',B',C',D')
    \end{tikzpicture}
\end{document}

A: You could scale the points prior to translation:
\documentclass[tikz]{standalone}
\usepackage{tkz-euclide}
\usetkzobj{all}

\begin{document}
    \begin{tikzpicture}
        %Define Points
        \tkzDefPoint (0,0){A}
        \tkzDefPoint (4,0){B}
        \tkzDefPoint (5,1){C}
        \tkzDefPoint (3,2){D}
        \tkzDrawPolygon[fill=blue!40, very thick](A,B,C,D)

        %Label Points
        \tkzLabelPoint[left](A){A}
        \tkzLabelPoint(B){B}
        \tkzLabelPoint(C){C}
        \tkzLabelPoint[above](D){D}

        %Scale the points about A with ratio 3
        \tkzDefPointBy[homothety=center A ratio 3](A)\tkzGetPoint{A};
        \tkzDefPointBy[homothety=center A ratio 3](B)\tkzGetPoint{B};
        \tkzDefPointBy[homothety=center A ratio 3](C)\tkzGetPoint{C};
        \tkzDefPointBy[homothety=center A ratio 3](D)\tkzGetPoint{D};

        %Shift the Points
        \tkzDefShiftPoint[A](3 in, 0in){A'}
        \tkzDefShiftPoint[B](3 in, 0in){B'}
        \tkzDefShiftPoint[C](3 in, 0in){C'}
        \tkzDefShiftPoint[D](3 in, 0in){D'}
        \tkzDrawPolygon[fill=green!40, very thick](A',B',C',D')
    \end{tikzpicture}
\end{document}

Disclaimer: I don't read French either and this is the first time I've looked at tkz-euclide. What I have seems to work, but I find the argument structure for \tkzDefPointBy very odd. I'd recommend using straight tikz (see cfr's answer) for something like this.

A: The answer of Guho is fine but there are other methods :
 \documentclass[tikz]{article}
 \usepackage{tkz-euclide}
 \usetkzobj{all}

 \begin{document}
 \begin{tikzpicture}
    %Define Points
    \tkzDefPoint (0,0){A}
    \tkzDefPoint (4,0){B}
    \tkzDefPoint (5,1){C}
    \tkzDefPoint (3,2){D}
    \tkzDrawPolygon[fill=blue!40, very thick](A,B,C,D)
 \end{tikzpicture}
 \begin{tikzpicture}[scale=2]
    %Define Points
    \tkzDefPoint (0,0){A}
    \tkzDefPoint (4,0){B}
    \tkzDefPoint (5,1){C}
    \tkzDefPoint (3,2){D}
    \tkzDrawPolygon[fill=green!40, very thick](A,B,C,D)
\end{tikzpicture}

\begin{tikzpicture}
    %Define Points
    \tkzDefPoint (0,0){A}
    \tkzDefPoint (4,0){B}
    \tkzDefPoint (5,1){C}
    \tkzDefPoint (3,2){D}
    \tkzDrawPolygon[fill=blue!40, very thick](A,B,C,D)

\begin{scope}[xshift=5cm,x=2cm,y=2cm]
    %Define Points
    \tkzDefPoint (0,0){A}
    \tkzDefPoint (4,0){B}
    \tkzDefPoint (5,1){C}
    \tkzDefPoint (3,2){D}
    \tkzDrawPolygon[fill=red!40, very thick](A,B,C,D)
\end{scope}
    \end{tikzpicture}
\end{document}

A: I don't read French either. People who can say the examples make it all clear. But not to me, apparently.
\documentclass[border=5pt, multi, tikz, italian]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
  \path [draw, very thick, fill=blue!40] (0,0) \foreach \i/\j/\k in {(0,0)/A/left,(4,0)/B/right,(5,1)/C/right,(3,2)/D/above}
  {
    -- \i coordinate (\j) node [\k] {\j}
  } -- cycle;
  \path [draw, very thick, fill=green!40] (3in,0) -- +($3*(B)$) -- +($3*(C)$) -- +($3*(D)$) -- cycle;
\end{tikzpicture}
\end{document}

A: This is much simpler in Metapost because you can apply a transformation to a whole path instead of having to do it one point at a time.

prologues:=3;outputtemplate:="%j%c.eps";
beginfig(1);

path poly, small_poly, big_poly;

poly = origin -- (4,0) -- (5,1) -- (3,2) -- cycle;
small_poly = poly scaled 30;
big_poly   = poly scaled 50 shifted 200 right;

fill small_poly withcolor .6[blue,white];
draw small_poly;

fill big_poly withcolor .6[green,white];
draw big_poly;

label.lft("A", point 0 of small_poly);
label.lrt("B", point 1 of small_poly);
label.rt ("C", point 2 of small_poly);
label.top("D", point 3 of small_poly);

endfig;
end