text:
Q: VS Code Python Setup
I am trying to set up VS Code for running python and I have installed Python 3.9.6 , the Python extension in vs code, coderunner extension in vs code, and also added the python interpreter path in Environment Variables. Still when I run the simple print code, it gives no output.
Also the pip command gives an error.

Can someone explain how to fix this and keep in mind I am a beginner.

A: Two problems:
First one:
You have not saved your python file, as it has a white circle on the left in the python file name.

You can add this in the settings.json file:
  "files.autoSave": "afterDelay",
  "files.autoSaveDelay": 1000,

Second one:
You probably have not select pip when you install the python. You can try to install the pip whit this command:
python -m ensurepip

A: Navigate to the correct directory using this command:
cd "path/..."

and then directly try using:
python vscode.py

A: You probably haven't added pip to your system path. But still, you can use pip as python -m pip. Just to ensure pip is installed properly, type python -m pip --version. If you get the correct version info, you can refer to the link below to add it to your system path.
Add pip to your system path


text:
Q: How to UPDATE DATABASE in Code First approach automatically after check-in and Publish code in Continuous deployment In our Web API application, Continuous deployment need a following scenario.
User will check in code in VS, Code will get automatically build, Code will be Published, Code will be deployed.
But If we are using Entity Framework Code First approach, How can we update database without manual commands (Add-Migration/Update Database)and make database up to date with that check-in.

A: You can try to run Add-Migration/Update Database commands in the build/deploy process.
Assume you are using vNext build,

*

*Add a "Nuget Installer" task in your build definition first to
restore the Entity Framework during the build. Migrate.exe will be
installed in \packages\EntityFramework.\tools folder.

*Then add a "Command Line" task to run the migrate.exe. Enter
"\packages\EntityFramework.\tools\migrate.exe" in "Tool" area and
the arguments in "Arguments" field.

Reference this thread : How can I run Entity Framework's migrate.exe from Visual Studio Online?
You can also try the extension "Entity Framework Migrations" which contains a set of tasks which allow you to work with Entity Framework code first migrations:

Method 1: Generating SQL script
The first method allows you to generate a SQL script containing all
  migrations. This script can be obtained by manually running
  Update-Database -SourceMigration 0 -Script in the NuGet package
  manager console in Visual Studio. You can then either manually run
  this script after the release or automatically during the release
  using a extension that allows you to run SQL scripts.
Task name: Generate migration SQL script

Other articles may helps:

*

*Deploying an Entity Framework Database into Production

*Using TFS Build to Deploy Entity Framework Database Migrations with
Migrate.exe

*Continuous Delivery with TFS: Our Sample Application

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOS: error in HomeDirectory I have this code
NSString *nextSequentialFile =
    [filePath stringByReplacingOccurrencesOfString:photoNumber
    withString:[NSString stringWithFormat:@"%d", (index + 1)]
    options:NSBackwardsSearch
    range:[filePath rangeOfString:photoNumber options:NSBackwardsSearch]];

but I have this error and I don't understand beacuse it happens.
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString replaceOccurrencesOfString:withString:options:range:]: Range or index out of bounds'

A: Try:
NSString *nextSequentialFile =
[filePath stringByReplacingOccurrencesOfString:photoNumber
withString:[NSString stringWithFormat:@"%d", (index + 1)]
options:NSBackwardsSearch
range:NSMakeRange(0, filePath.length)];

A: It's likely that rangeOfString:photoNumber is out-of-range.  I would recommend logging each of the values you pass to this method in order tell which is at fault.

A: Never assume that methods like rangeOfString:options: return a valid range. From the docs:

Return Value
An NSRange structure giving the location and length in
  the receiver of the first occurrence of aString, modulo the options in
  mask. Returns {NSNotFound, 0} if aString is not found or is empty (@"").
[Emphasis added]

So obtain the range first and check for NSNotFound before attempting to use it.


text:
Q: How do you explicitly destroy an object in Perl? Let's say I have a Perl class that has a DESTROY method. This method is used to implicitly release an external resource, such as a file handle or database transaction.
Given an instance of this class, I would like to explicitly destroy it. The primary purpose of this is to cause the DESTROY method to be called so the external resource can be released. However, having the "object" itself released from memory would be an added benefit.
How can I do this? I have considered directly calling the DESTROY method and undefining any variables that reference the object.

A: You can use undef to explicitly destroy an object. The below code illustrates it.
package MyPackage;

sub new {
    print "In new\n";
    return bless {};
}

sub DESTROY {
    print "In DESTROY\n";
}

package main;

my $Obj = MyPackage->new();
<STDIN>;
undef $Obj;
<STDIN>;

A: Perl5 objects get destructed as soon as the last reference to them disappears, unless you have self-referential structures (see Destructors and the Two phase garbage collection paragraph after that for some interesting information).
If you don't have self-references, you don't need to worry about anything, the DESTROY method will be called when it needs to be; trying to destruct the object yourself would not be safe (how can you be sure the object isn't references somewhere else), unless you're also doing reference counting yourself (if that's actually possible, and that would be duplicating perl's efforts, which isn't such a good idea).
So I'd say, as long as you don't have cyclic references:

*

*If you want to release external resources at a specific point in your code, do so explicitly with a release/close/dispose/whatever method (that your DESTROY code could call too).

*If you don't really care that that release happens exactly at that point in your code, just that it does get called eventually, don't worry about it.

*Don't worry about the perl object itself.

If you do have cyclic references, you'll need to be much more careful, and use weak references (see Scalar::Util) to break the cycles.
(In other words, I don't know of a way to explicitly delete a perl object. That doesn't work well with a reference-counted garbage collection system.)


text:
Q: Hybrid graphics Intel/Radeon HD 6630M I bought a Dell Vostro 3450 with hybrid GPU and I don't know how to configure properly, I think the fan is running at full speed, also I'm really new in this OS, so I would appreciate all the help you can give me.
Thanks a lot!.
Hardware

*

*2nd generation Intel®Core™ i5-2450M 2.50GHz

*6 GB2 Dos canales SDRAM DDR3 a 1333 MHz

*AMD Radeon™ HD 6630M (128-bit) 1GB VRAM

since I'm new, i can't post images :(

A: follow the instructions here:
https://help.ubuntu.com/community/BinaryDriverHowto/ATI
under
Manually installing Catalyst 12.1
do everything there step by step until
"sudo amdcccle
To read more about the AMD/ATI Catalyst Control Center click here. Keep in mind that all configuration options for the ATI Catalyst Control Center mentioned there may not be available for your Ubuntu system. "
works with hybrid graphics card (intel / radeon)
you might have to change the filename of the .run file to the filename of the more recent file you downloaded.  (when typing in the terminal, you can use the tab key on your keyboard to autocomplete)
tested in Xubuntu 11.10

A: Making procedures for the link
https://help.ubuntu.com/community/BinaryDriverHowto/ATI
the cooler is still in full swing.


text:
Q: How in insert dynamic JavaScript tag into iframe FINAL UPDATE: The second code block is working--I just miss-typed the URL.
I'm trying to place a dynamically created script into an iframe. I can access the head of the iframe, but it doesn't seem to accept the append request. The console log call returns the head tag, and the following append of text into the body works fine. I've also tried appending the script tag to the body. (note: the script tag is not on the same domain, so I've avoided using getScript or ajax).
$(document).ready(function() {
  $('', {
      name:"contentFrame"
      ,id:"contentFrame"
  }).css("height", 300).css("width", 500).load(function() {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "//cross-domain.com/script.js";
      console.log($(this).contents().find("head")); // outputs: []
      $(this).contents().find("head").append(script); // doesn't work
      $(this).contents().find("body").append(script); // doesn't work
      $(this).contents().find("body").append("Test"); // works
  }).appendTo("#content");
});

Here is the new version that successfully appends the script based upon the suggestion below, but the script doesn't evaluate (as tested by a simple alert). Plus, another oddity: the "working" icon displays for about 15 seconds and the status (in chrome) says "retrieving..." Eventually it stops, but nothing happens.
    $(document).ready(function() {
  $('', {
      name:"contentFrame"
      ,id:"contentFrame"
  }).css("height", 300).css("width", 500).load(function() {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "//cross-domain.com/script.js";
      console.log($(this).contents().find("head"));
      $(this).contents().find("head")[0].appendChild(script);
      $(this).contents().find("body").append("Test");
  }).appendTo("#content");
});

Update: When the cursor icon finally finishes working (about 10 seconds, which is odd because it's a local server with one line of code), I get this message in the Chrome console (it's in all red with a red circle "X" icon next to it):
GET http://cross-domain.com/script.js
(anonymous function)temp.html:16
jQuery.event.dispatchjquery-1.7.1.js:3261
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2880
jQuery.fn.extend.appendjquery-1.7.1.js:5771
jQuery.fn.extend.domManipjquery-1.7.1.js:5973
jQuery.fn.extend.appendjquery-1.7.1.js:5769
jQuery.each.jQuery.fn.(anonymous function)jquery-1.7.1.js:6162
(anonymous function)temp.html:18
jQuery.Callbacks.firejquery-1.7.1.js:1049
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1167
jQuery.extend.readyjquery-1.7.1.js:435
DOMContentLoaded

A: See this answer https://stackoverflow.com/a/3603496/220299
It may in fact be working, but the script tag is just not visible.

A: Try this.
$(document).ready(function() {
  $('', {
      name:"contentFrame"
      ,id:"contentFrame"
  }).css("height", 300).css("width", 500).load(function() {
      $(this).contents().find("head").append('<scr' + 'ipt type="text/javascript" src="//cross-domain.com/script.js"></scr' + 'ipt>');
  }).appendTo("#content");
});


text:
Q: Draw round corner image ios I have a button that is custom drawn using Core Graphics, and I want to change it so it is drawn with rounded corners and with white stroke round borders. I'm also setting a background image.
func imagePickerController(picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    if  let  pickedImage  = info[UIImagePickerControllerOriginalImage] as? UIImage {

        myButton.layer.cornerRadius =  // Nothing Give me here circle
        myButton.clipsToBounds = true
        myButton.layer.borderWidth = 12.0
        myButton.layer.borderColor = UIColor.whiteColor().CGColor
        myButton.setBackgroundImage(pickedImage, forState: .Normal)
        myButton.setNeedsDisplay()
    }

    dismissViewControllerAnimated(true, completion: nil)

}

This is what I get when I apply myButton.layer.cornerRadius = myButtonrect.size.height/2


text:
Q: Problem with unset in "Post" array using timber I'm creating a Wordpress blog application using timber and twig.
The problem is that i want to select all post except for one
This is what I have now:
$context = Timber::get_context();
$context['post'] = new Timber\Post(); //the one we don't want

$args = array(
    'posts_per_page' => 2,
    'post_tag' => $context['post']->post_tag
);

$context['relevant'] = Timber::get_posts($args);//the ones we want

Timber::render(array('single-' . $post->post_type . '.twig', 'single.twig'), $context);

context['post']: contains one single post.
context['relevant'] contains all the posts with te same tag as context['post']
what i exactly want is: if the context['post'] element, is included in the context['relevant'], I want it removed and put in an other post in it instead.
Is there any way to do this?
Any help is much appreciated and thanks in advance.
SOVED
actually really easy,
the only thing I had to do was to get het index of the array and then unset is.
$a = array_search($context['post'], $context['relevant']);

unset($context['relevant'][$a]);

A: use isset function to not throwing errors
if(isset($context['relevant'][$context['post']])){
    unset($context['relevant'][$context['post']]);
}


text:
Q: Android: Capturing Images and sending them via Socket to an Applet I want to implement a simple video streaming vor Android. I can send single image shots via TCP Socket, but I have problems to send several images quickly. I use the common Camera functionality with preview, surfaceholder etc.
http://developer.android.com/reference/android/hardware/Camera.html
Is my approach wrong, to use this functionality? How can I implement such kind of video streaming?

A: Maybe you should give more details, such as how quickly do you want, or what kind of and how large the data is.
Generally speaking, send single image is okay, even several images are still no big problem. However, vedio streaming requires a large amount of bandwidth and CPU speed. And the video should not be sent as images, it could be either a vedio file or vedio streaming, deponds on your requirment.

A: I did play around with MJPEG for a while. This may give you a hint for a simple way to send video.


text:
Q: C++ strncpy parameters "optimized out"; overwrites random memory First of all, I want to apologize for not being able to narrow down the problem enough to be able to share a short program that reproduces the bug.
An external library (FUSE) call to strncpy "randomly" overwrites a shared_ptr<mutex> in my code, which causes a segfault when I try to lock that mutex. I ran my program with valgrind and it didn't catch any memory errors (valgrind flags below). When I run my code in gdb and set a watchpoint on that shared_ptr, it breaks on the call to strncpy. gdb says that all of strncpy's parameters (dest, src, and nbytes) have been "optimized out", which makes me think it's using uninitialized memory for that call. Am I interpreting this correctly? Any idea what the cause could be?
Here's the stack trace from gdb when the pointer is overwritten:
#0  __strncpy_ssse3 () at ../sysdeps/x86_64/multiarch/strcpy-ssse3.S:2482
#1  0x0000003245809094 in strncpy (__len=<optimized out>, __src=<optimized out>, __dest=<optimized out>) at /usr/include/bits/string3.h:120
#2  add_name (buf=<optimized out>, bufsize=<optimized out>, s=<optimized out>, name=<optimized out>) at fuse.c:907
#3  0x000000324580997c in try_get_path (f=<optimized out>, nodeid=<optimized out>, name=<optimized out>, path=<optimized out>, wnodep=<optimized out>, need_lock=<optimized out>) at fuse.c:956
#4  0x000000324580a281 in get_path_common (f=<optimized out>, nodeid=<optimized out>, name=<optimized out>, path=<optimized out>, wnode=<optimized out>) at fuse.c:1152
#5  0x0000003245812432 in fuse_lib_unlink (req=<optimized out>, parent=<optimized out>, name=<optimized out>) at fuse.c:1198
#6  0x0000003245817057 in fuse_ll_process_buf (data=0x6f5650, buf=0x7fffffffd850, ch=<optimized out>) at fuse_lowlevel.c:2441
#7  0x000000324581388f in fuse_session_loop (se=0x6f8410) at fuse_loop.c:40
#8  0x000000324580b698 in fuse_loop (f=<optimized out>) at fuse.c:4309
#9  0x000000324581bb8f in fuse_main_common (argc=<optimized out>, argv=<optimized out>, op=<optimized out>, op_size=<optimized out>, user_data=<optimized out>, compat=<optimized out>) at helper.c:355
#10 0x000000000046f1b6 in main (argc=4, argv=0x7fffffffdec8) at ../src/fuse.cpp:100

Here's the arguments I ran valgrind with:
valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes

A: This bug was the result of creating a shared_ptr with new, then typecasting it to a weak_ptr and deleting it.

A:
gdb says that all of strncpy's parameters (dest, src, and nbytes) have been "optimized out", which makes me think it's using uninitialized memory for that call. Am I interpreting this correctly?

No. This just means that the optimizer has removed some of the function prologue boilerplate that would allow the debugger to reliably print the arguments to the function.  This is very common with simple functions at any reasonable level of optimization.
Here's a simple example:
int
mystrcpy(char *p, const char *q)
{
    while (*p++ = *q++);
}

compiled with -g -O0 you see it spill its arguments to the stack immediately:
mystrcpy:
.LFB0:
        .file 1 "t.c"
        .loc 1 5 0
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        movq    %rsp, %rbp
        .cfi_offset 6, -16
        .cfi_def_cfa_register 6
        movq    %rdi, -8(%rbp)      <<< here
        movq    %rsi, -16(%rbp)     <<< and here
        ...

Then the compiler generated debug info about that:
    .section        .debug_info
    ...
    .uleb128 0x7
    .string "p"   <<< from char *p
    .byte   0x1
    .byte   0x4
    .long   0x65
    .byte   0x2
    .byte   0x91
    .sleb128 -24  <<< not 100% sure but this is probably related to frame offset
    .uleb128 0x7
    .string "q"
    .byte   0x1
    .byte   0x4
    .long   0x72
    .byte   0x2
    .byte   0x91
    .sleb128 -32   <<< note adjacent to p

When you crank up -O2 -g, despite -g the function becomes much smaller:
mystrcpy:
.LFB11:
        .file 1 "t.c"
        .loc 1 5 0
        .cfi_startproc
        (at this point we start copying, using the input regs directly)

And now there's no reference to p or q in the debug information.  As you can see from this example you can probably find the information you want in registers, but you will have to disassemble and understand the function to interpret them.  And if your function has called other functions you may have to find where your registers got spilled to the stack (could be quite far away for callee-saves regs).


text:
Q: Call a method just before OnClick is called I have been looking for my question on Google and inside the forum but I cannot an answer so far. I am using android studio to code an app in Java
The thing is : inside a class, I have overrided the OnClick() method because I have to implement a lot of views.
Now I want to call a function just before OnClick() is called.
What I mean is, for instance, if the user taps on a button, before OnClick() is called I want one of my methods to be called.
Does anyone know how to do this ?
Thank you in advance

A:
I want to call a function just before OnClick() is called

You can use a logic inside onClick() like,
if(userhaspermission())//your method to check if the user has permission
{
    //your onclick operation code
}

Make your checking permission method with return type as boolean

A: Implement your custom OnClickListener as follows
 public abstract class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            //Do common action

            if(condidtionSatisfied){
                performClick(v);
            }
        }

        public abstract void performClick(View v);
    }

Set onClickListener to any component as follows:
button.setOnClickListener(new MyOnClickListener() {
            @Override
            public void performClick(View v) {
                 //Execute post click action
            }
        });

This will ensure your common code will be called for all the views and it would be much cleaner approach.

A: Override the onClick() method and write your first logic which you want.

A: Write your own Listener like Sagar said

This logic is quite similar to Sagar's Answers.
Write abstract class as given below

    public abstract class OnClick implements View.OnClickListener {

    public void beforeClick(View v) {

    }

    @Override
    public void onClick(View v) {
        beforeClick(v);
        performClick(v);
        afterClick(v);
    }

    public void performClick(View v) {

    }

    public void afterClick(View v) {

    }
    }

NOTE : See in above code it implements View.OnClickListener, so this logic will works for views which extends View super class. If you want above logic for object's which needs Dialog interface onClick then you need to modify it for DialogInterface.OnClickListener.
So you can use above logic as below

   //Let say you need it for button with id button

  Button button = (Button) findViewById(R.id.button);

  button.setOnClickListener(new OnClick() {

        @Override
        public void beforeClick(View v) {
            Toast.makeText(MainActivity.this, "Before", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void performClick(View v) {
            Toast.makeText(MainActivity.this, "Click", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void afterClick(View v) {
            Toast.makeText(MainActivity.this, "After", Toast.LENGTH_SHORT).show();
        }

    });


text:
Q: how to merge and sum frames of images into one in Digital Micrograph? I tried to use the merge function to sum it together, but the intensity of the Merge Image does not equal to the addition of the two original images. Does anyone know how to do it in DM?

A: I think the question as asked is maybe a bit under-specified. For simple "intensity adding" of two images of the same size ( pixel dimensions ) you can simply use the label letters and a simple equation like f.e.:

will give you:

I also don't know what the 'merge' function you refer to should be. What script command are you referring to?


text:
Q: How to transfer one text file to another one? I have A.txt file as follow:
AAA  Opened successfully.
BBB Cannot connect.
CCC Opened successfully.
DDD Opened successfully.
EEE Cannot connect.

How can I use a batch file to generate B.txt as (Only include Cannot rows):
BBB Cannot connect.
EEE Cannot connect.

Thanks,

A: One-liner
find "Cannot" <a.txt >b.txt


text:
Q: 12.04 Unity capable, but still stuck with no loader/dash/ I ran
/usr/lib/nux/unity_support_test -p

And it seems I pass all tests, I'm using the latest proprietary drivers, Unity 2D/Gnome works just fine, just not Unity 3D
I already tried Unity doesn't load, no Launcher, no Dash appears logged in using 2D, activate the plugin but still no dice.
Is there a dump I can provide to get help?

A: If you've upgraded, or are using the same home partition/directory with old config files, it's possible for some old compiz configuration to break the Unity panel and launcher.  Open a terminal window and try:
unity --reset
Chris


text:
Q: Given a custom generic class that stores a List how do I prevent adding an object of type T more than once to the List? So this is the code that I have tried, but it adds the same object more than once:
namespace TestComparison
{
    public interface IAddable
    {
        int RandomIntValue { get; set; } // often Times this value will repeat.
    }

    public class AdditionManager<T> where T : IAddable
    {
        private List<T> addables;

        public AdditionManager()
        {
            addables = new List<T>();
        }

        public void Add(T _addable)
        {
            if (!addables.Contains(_addable))
            {
                addables.Add(_addable);
            }
        }

    }

    public class TestAddable : IAddable
    {
        public int RandomIntValue { get; set; }
        public Data UniqueData = new Data() { UniqueId = 10023 }; // This is what really make each item unique
    }

    public class Data
    {
        public int UniqueId { get; set; }
    }
}

I've heard about the IEqualityComparer and I have implemented it in non-generic classes, but I'm not quite sure how to implement it here.

A: Your problem indeed seems to be related to a missing IEqualityComparer.
Imagine the following:
class TestClass
{
    public int x;
}

class Program
{
    static void Main(string[] args)
    {
        TestClass nine = new TestClass() { x = 9 };
        TestClass twelve = new TestClass() { x = 12 };
        TestClass anotherNine = new TestClass() { x = 9 };

        Console.WriteLine(nine == twelve);
        Console.WriteLine(nine == anotherNine);
    }
}

What will this program output? The "surprising" answer is that it outputs False two times. This is because the objects are compared to each other, not the members of the objects. To achieve an actual value comparison which will compare the objects by their content instead of their reference you need to consider quite a few things. If you want to be really complete, you need IComparable, IEquality, GetHashcode etc etc. It's very easy to make a mistake there.
But since C# 9.0 there's a new type which can be used instead of class. The type is record. This new record type has all the stuff I mentioned implemented by default. If you want to go the long route, I suggest you to look into the new record type and what it actually is.
This means all you need to do is change the type of your TestAddable and Data from class to record and you should be fine.

A: You can use dependency injection to provide you with generic implementation.  Doing so you'll need to provide the custom IEqualityComparer<T> implementation that you want at the point of generic object's construction.
public class AdditionManager<T> where T : IAddable
{
    private List<T> addables;
    private IEqualityComparer<T> comparer;

    public AdditionManager()
        : this (EqualityComparer<T>.Default)
    { }

    public AdditionManager(IEqualityComparer<T> _comparer)
    {
        addables = new List<T>();
        comparer = _comparer;
    }

    public void Add(T _addable)
    {
         if (!addables.Contains(_addable, comparer))
         {
             addables.Add(_addable);
         }
    }
}

However, if you are looking for you list of addables to be unique based on some constraint, I would not use the above implementation for performance reasons.  As the List<T>.Contains check will become slower as the list grows larger.
If the order of the list does not matter change your List<T> to a HashSet<T>.  HashSet<T>.Contains will be just as quick as a Dictionary<TKey, TValue> lookup.  But this call can be avoided altogether with HashSet<T> as the Add call will first check to see if the item is in the set before adding it, and return true or false to indicate it was added or not`
So if the order of addables is of not concern, then I would use the following implementation.
public class AdditionManager<T> where T : IAddable
{
    private HashSet<T> addables;

    public AdditionManager()
        : this(EqualityComparer<T>.Default)
    { }

    public AdditionManager(IEqualityComparer<T> _comparer)
    {
        addables = new HashSet<T>(_comparer);
    }

    public void Add(T _addable)
    {
        // will not add the item to the HashSet if it is already present
        addables.Add(_addable);
    }
}

If you need to maintain the order of addables then I suggest maintaining the list of objects in both a HashSet<T> and List<T>.  This will provide you with the performance of the above implementation, but maintain the addition order on your items.  In this implementation any of the operations you need to perform, do them against the List<T> and only use the HashSet<T> to make sure the item isn't already present when adding to List<T>  If you are going to have some type of Remove operation, make sure to remove the item from both the HashSet<T> and List<T>
public class AdditionManager<T> where T : IAddable
{
    private HashSet<T> set;
    private List<T> list;

    public AdditionManager()
        : this(EqualityComparer<T>.Default)
    { }

    public AdditionManager(IEqualityComparer<T> _comparer)
    {
        set = new HashSet<T>(_comparer);
        list = new List<T>();
    }

    public void Add(T _addable)
    {
        if (set.Add(_addable))
            list.Add(_addable);
    }
}

To create this object using TestAddable you'll need an IEqualityComparer<TestAddable> like the following.  As others have suggested, the field(s) you are doing your comparison on should be made immutable, as a mutable key is going to cause bugs.
public class TestAddableComparer : IEqualityComparer<TestAddable>
{
    public bool Equals(TestAddable x, TestAddable y)
    {
        return x.UniqueData.Equals(y.UniqueData);
    }

    public int GetHashCode(TestAddable obj)
    {
        // since you are only comparing use `UniqueData` use that here for the hash code
        return obj.UniqueData.GetHashCode();
    }
}

Then to create the manager object do:
var additionManager = new AdditionManager<TestAddable>(new TestAddableComparer());

A: You can use a dictionary instead of a list. If you need a list in other parts of your code, it is easy to add a property that exposes the Values only.
public class AdditionManager<T> where T : IAddable
{
    private Dictionary<int,T> addables;

    public AdditionManager()
    {
        addables = new Dictionary<int,T>();
    }

    public void Add(T _addable)
    {
        if (!addables.ContainsKey(_addable.Data.RandomIntValue))
        {
            addables.Add(_addable.Data.RandomIntValue, _addable);
        }
    }

    public Dictionary<int,T>.ValueCollection Values => _addables.Values;
}


text:
Q: ColdFusion Error: The system has attempted to use an undefined value I am a graduate student and new to ColdFusion.
I started working on this already developed project by someone couple of years ago, and the client wants some changes to be done. So I went ahead and did some small modifications to the appearance of the form (insertdata.cfm), like adding some more options to a drop down menu, changing the label names and so on.
I am very sure this changes would not have affected the application in any way. And the place where the message says the error is - I didn't even touch that part. Now after 4 days I start getting this weird error saying
Error Occurred While Processing Request
The system has attempted to use an undefined value, which usually
indicates a programming error, either in your code or some system code.

Null Pointers are another name for undefined values.

And this happens randomly, not every time I access the website or different webpages. Here are the errors:
1st error:
The error occurred in /export/web/virtual/web3_unt_edu/cps/webaccess/sites/Amarillo/index.cfm: line 8
5 :   SELECT UserName,Password FROM user_data WHERE UserName=
6 :   <cfqueryparam value="#FORM.UserName#" maxlength="8">
7 :     AND Password=
8 :   <cfqueryparam value="#FORM.Password#" maxlength="8">
9 :   </cfquery>
10 :   <cfif MM_rsUser.RecordCount NEQ 0>

I also tried adding cfsqltype="cf_sql_clob" in cfqueryparam on my friends advice, but it doesn't work out.
2nd error:
The error occurred in /export/web/virtual/web3_unt_edu/cps/webaccess/sites/Amarillo/InsertData.cfm: line 13

11 :   <cflocation url="#MM_failureURL#" addtoken="no">
12 : </cfif>
13 : <cfquery name="rsDay" datasource="cps">
14 : SELECT days FROM days
15 : </cfquery>

3rd error
The error occurred in /export/web/virtual/web3_unt_edu/cps/webaccess/sites/Amarillo/InsertData.cfm: line 27

25 : ORDER BY ethnicity ASC
26 : </cfquery>
27 : <cfquery name="rsHospitals" datasource="cps_amarillo">
28 : SELECT *
29 : FROM hospitals

A: This also happens when you try to use a returned value from a function, but the function doesn't return a value -- this has troubled me in the past, but when I get this error now, it's the first thing I look for...

A: The problem is a datasource issue.  It has something to do with MySQL5 and Coldfusion 8.  Coldfusion 9 has the fix for it.  You will notice that the datasource does not have an option for MySQL 5 just 3/4.

A: In general, if you find that things are not consistently going wrong, look for data being stored in the session or being re-defined on every page. Then find the non-standard branches, either in your user's page clicks or the CF code, that might be missing / resetting these.
For the first issue, as Al points out, these values should be coming through for text fields. But look at the CFPARAM tag to defend against them not being there anyway. You can set a nonsense "default" value, and when you have it, log the prior page and any other information that might be useful to help you find how users are getting to that page without going to the form before it.
The second issue is probably because MM_failureURL is not defined or the definition is getting lost. It's ugly, but you can use CFDUMP to find out if it is in another namespace sometimes, or where it is getting dropped.
For the third issue, have you checked that cps_amarillo and rsHospitals are defined in the current namespace?
Another suggestion: Some of these issues might be from users bookmarking pages "in the middle" of your application, which would allow them to jump in without going through whatever setup (such as your login form) would establish your variables, query names, etc. If you are sure that users can't jump in without your initialization code, then you are off on the Edge Case Hunt.

A: In my experience this type of error happens when you (often by way of an extension/library/component) try to dereference a null pointer, which was much more commonplace back in the C++/COM+ CFX days than it is now.  The fact that it is happening in with basic CFQUERY code is a bit alarming.  What database type are you using?  I'm wondering if it is a driver and/or datasource issue.

A: Were these errors happening before you amended your code? If not no matter how unlikely it feels I would suggest rolling back your changes (you did keep a record right?)
If they were previously happening (or you can't roll back) you need to get more information about what is happening at error time. Can you arrange that you get sent error information.
Point to your error page in application.cfc
<cferror type="exception" template="errorPage.cfm">

Then add errrorpage.cfm
We are so sorry. Something went wrong. We are working on it now.

<cflog file="myapperrorlog" text="#error.message# - #error.diagnostics#">

<cfsavecontent variable="errortext">
<cfoutput>
An error occurred: http://#cgi.server_name##cgi.script_name#?#cgi.query_string#

Time: #dateFormat(now(), "short")# #timeFormat(now(), "short")#

<cfdump var="#error#" label="Error">
<cfdump var="#form#" label="Form">
<cfdump var="#url#" label="URL">
<cfdump var="#session#" label="Session">

</cfoutput>
</cfsavecontent>

<cfmail to="bugs@myproject.com" from="root@myproject.com" subject="Error: #error.message#" type="html">
    #errortext#
</cfmail>

Might help to get the info, more here on rays site

A: I experienced this Coldfusion error after transferring my server from mysql 4 to mysql 5
I've put together this small article on how to temporarily fix it until a hot fix is released from Adobe:
Read here

A: The solution is simple,  just got to coldfusion administrator, click on the datasource, click on show advanced settings, uncheck maintain connections. and you have banished the problem forever.


text:
Q: What does the prime symbol indicate in a nuclear reaction? I've come across a reaction shown as $ ^7\text{Li}(\alpha,\alpha^\prime)^7\text{Li}^*$. I understand that the asterisk indicates that the final $ ^7\text{Li}$ is in an excited state, but what about the prime symbol on the $\alpha$?  Does it simply indicate the incident $\alpha$ after the interaction?  If so, would it be correct to say this reaction describes an elastic collision (inelastic scattering) with some energy imparted to the $ ^7\text{Li}$?

A: I would interpret that as emphasis that it's an inelastic scattering reaction, so that the energy of the outgoing alphas is substantially different from the energy of the incident beam.  Of course an elastic scattering between a mass-4 alpha and a mass-7 lithium will have a pretty substantial energy change for most scattering angles, just due to kinematics; but if the lithium nucleus is knocked into some excited state, that energy has to have come from the incident alpha beam.
Note also that most $\rm^7Li^*$ decay by decomposition into $\rm\alpha+t$, rather than by photon emission.  The ENSDF database lumps all of $\rm^7Li(\alpha,\alpha)$, $\rm^7Li(\alpha,\alpha')$, $\rm^7Li(\alpha,t\alpha)$, and $\rm^7Li(\alpha,\alpha't)$ into one dataset, which only describes about five excited energy levels.  A source which uses more than one notation might have explanatory text about what they mean by the difference.


text:
Q: What's the difference between around the clock and 24/7? I found their definitions very similar. They both mean nonstop. Are they exactly synonymous or there are some differences?

A: As the comments already suggest, there is a subtle difference, which is how long they imply an action goes on for.
Around the clock means without ceasing, even during the night when most normal activity ceases. It can (and usually does) mean that one or people stayed up all night, but can also mean a larger collection (say, the workforce of a factory or the staff at a consulate or legal firm) between them worked "all hours". It may not be completely literal (factories may have short pauses during shift changes, for example; lawyers may order coffee).
24/7 (as @user121863 and @weather-vane pointed out) has a stronger connotation that not only does the activity continue all day, every day [of the week] – implying for more than a week – but (by usually not mentioning an individual week) implies that this is the pattern every week. If a time period is mentioned, it indicates that the pattern (no hour excluded, no day excluded) continued throughout that period.
In normal English usage, both mean non-stop, but typically the first is used for worked without stopping to meet a deadline, and the second for the lights never went out; the people and the machines kept moving hour after hour, day after day….


text:
Q: Google Cloud Speech API returned "Quota exceeded" My desktop Python application transcribes large sets of speech samples (each speech sample duration is between 1 sec and 8 sec long) and for that I am using Google Cloud Speech API. I am aware of all the usage limitations mentioned in this page and certainly within the limits to make sure that I do not violate any of these conditions.
When I started the application for one of my set of speech samples, it was able to transcribe few of them and interrupted in the middle with this error:
googleapiclient.errors.HttpError:
<HttpError 429 when requesting
https://speech.googleapis.com/v1beta1/speech:syncrecognize?alt=json returned
"Quota exceeded.">

I searched on web with this error ID and found this but I could not specifically relate it to the one that I am dealing with. Are there any other limitations with Google Cloud Speech API that I should be aware of?
Any help would be highly appreciated.

A: I also encounter this problem. Try checking the quotas on your API Manager dashboard > Speech API > Quotas.
I've just found out that for a simple Asynchronous requests, my quota increased by 50 requests.


text:
Q: I can't understand why Object reference is not set error in unity? I'm trying/learning about networking with unity and I have run into this error:
NullReferenceException: Object reference not set to an instance of an object
ClientController.ConnectToServer () (at Assets/Scripts/ClientController.cs:61)
ClientController.Start () (at Assets/Scripts/ClientController.cs:38)

The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;

public class ClientController : MonoBehaviour
{
    [Header("Server info")]
    public string websiteUrl = "http://localhost/game/index.php";
    public static string serverAddress = "";
    public const int serverPort = 100;
    public static bool isConnected = false;
    [Space(10)]
    public bool maintinenceMode = false;
    public static string serverVersion = "";
    [Header("Client info")]
    public static string clientIPv4 = IPManager.GetIP(ADDRESSFAM.IPv4);
    public static string clientIPv6 = IPManager.GetIP(ADDRESSFAM.IPv6);
    public static string clientVersion = "0.0.0"; // Need to add client version checker
    [Space(10)]
    public string clientUser;
    public string clientPass;
    [Space(10)]
    public string clientChar1;
    public string clientChar2;
    public string clientChar3;

    public static Socket _clientSocket;

    void Start()
    {
        ServerRequest();
        ConnectToServer();
        ServerInfoRequest(0, null);
        ServerInfoRequest(1, clientVersion);
    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator ServerRequest()
    {
        WWWForm form = new WWWForm();
        form.AddField("serverReq", "Please");
        var download = UnityWebRequest.Post(websiteUrl, form);
        yield return download.SendWebRequest();
        serverAddress = download.downloadHandler.text.ToString();
    }

    private static void ConnectToServer()
    {
        int attempts = 0;
        while (!_clientSocket.Connected)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress remoteIPAddress = IPAddress.Parse(serverAddress);
                IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, serverPort);
                _clientSocket.Connect(remoteEndPoint);
                attempts++;
            }
            catch (SocketException)
            {
                Debug.Log("Connection attempts: " + attempts.ToString());
            }
        }
        Debug.Log("Connected!");
        isConnected = true;
    }

    private static void ServerInfoRequest(int requsetType, string comparableData)
    {
        // Check
        byte[] buffer = Encoding.ASCII.GetBytes(requsetType.ToString());
        _clientSocket.Send(buffer);
        byte[] receivedBuf = new byte[1024];
        int rec = _clientSocket.Receive(receivedBuf);
        byte[] data = new byte[rec];
        Array.Copy(receivedBuf, data, rec);
        string reply = Encoding.ASCII.GetString(data);
        switch (requsetType)
        {
            // Check for maintinence
            case 0:
                Debug.Log("Checking for maintinence...");
                Debug.Log("Maintinence = " + reply);
                break;
            // Check server version
            case 1:
                Debug.Log("Checking for server version...");
                Debug.Log("Server version = " + reply);
                serverVersion = reply;
                int compareVersions = string.Compare(clientVersion, reply);
                Debug.Log("Client is compatibility is: " + compareVersions.ToString());
                break;
            default:
                Debug.Log("Unknown capabilities rising...");
                break;
        }
    }
}

I can't seem to figure out why the error occurs, I am kind of green around the ears but eager to learn.
Line 61 is:
while (!_clientSocket.Connected)

I can't seem to figure out why I get the error, any help would be greatly appreciated!
Thanks in advance for any help!

A: _clientSocket is never assigned, and you call .Connect on it, which is 'the same' as null.Connected.
That's why you get a NullReferenceException.
I will suggest you to do as the following :
private static void ConnectToServer()
    {
        int attempts = 0;

        // Add a null check
        while (_clientSocket == null || !_clientSocket.Connected)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress remoteIPAddress = IPAddress.Parse(serverAddress);
                IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, serverPort);
                _clientSocket.Connect(remoteEndPoint);
                attempts++;
            }
            catch (SocketException)
            {
                Debug.Log("Connection attempts: " + attempts.ToString());
            }
        }
        Debug.Log("Connected!");
        isConnected = true;
    }


text:
Q: Execution failed for task ':flutter_twitter:verifyReleaseResources' I'm working on Flutter app. I can run app in the android device successfully but try to make build (.apk) file and got below issues.
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_twitter:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/ipatel/.gradle/caches/transforms-2/files-2.1/8f09fa5c6115de167b21b323f769edd9/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /Users/ipatel/.gradle/caches/transforms-2/files-2.1/8f09fa5c6115de167b21b323f769edd9/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 5m 2s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                     303.8s (!)
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin firebase_messaging...
The plugin firebase_messaging could not be built due to the issue above.

Below are project's stuffs
defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.xxxx.eeee"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

> local.properties

sdk.dir=/Users/ipatel/Library/Android/sdk
flutter.sdk=/Users/ipatel/Documents/Amit/FlutterSetup/flutter
flutter.buildMode=release
flutter.versionName=1.0.0
flutter.ver

My app is compatible with AndroidX and also tried with many solution but can't able to fix my issue.
I checked
- https://github.com/roughike/flutter_twitter_login/issues/29
- A failure occurred while executing com.android.build.gradle.internal.tasks
- flutter Error "Android dependency 'androidx.core:core' has different version" using flutter_local_notifications and location packages
and others.
Flutter Doctor Result:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.12.13+hotfix.6, on Mac OS X 10.14.3 18D109, locale en-IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] VS Code (version 1.41.1)
[✓] Connected device (4 available)

build.gradle
android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.xxxx.aaaa"
        minSdkVersion 21
        targetSdkVersion 28
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

gradle.properties
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

~PS : Let me know if you want more details from my end.

A: Problem is with Execution failed for task ':flutter_twitter:verifyReleaseResources'.
i found link for this issue
flutter_twitter_login/issue #12
Add this dependency in your pubspec.yaml file and let me know this working or not?
flutter_twitter_login:
  git: git://github.com/eudangeld/flutter_twitter_login.git

A: Goto the android studio external libraries in the left side
--> select the library that cause this issue
--> then goto the android -> build.gradle and update the compileSdkVersion to 28

A: You need to update the compileSdkVersion of the flutter_twitter module to 28 :
1/ In your flutter project, locate your "android" folder and open it as an android project in Android Studio.
2/ Expand "Gradle Scripts" and wait for it to load.
3/ Locate "build.gradle (Module: flutter_twitter)"
4/ Modify the compileSdkVersion from 27->28.
5/ Save the changes.
My build worked after that.
The answer was here : https://github.com/flutter/flutter/issues/32595

A: The issue is some library is not compatible or not using androidx while others are. Thanks to google for transferring all support lib to androidx now many libraries having conflicts like this and I mostly go to debug around which lib has an issue like commenting and uncommenting the lib from pubspec.
Assuming the flutter_twitter plugin was the issue.

As we can check that, that twitter plugin not using AndroidX link so we need to change it our self.
(all these changes needs to be changed in twitter plugin, not flutter project)

I think you can change the gradle.properties to use androidx and also compile version to 28
gradle.properties:
android.useAndroidX=true
android.enableJetifier=true

add this two lines, change gradle classpath
classpath 'com.android.tools.build:gradle:3.5.3'
and compileSdkVersion 28 in flutter_twitter.
I am able to generate release build using that plugin.

Ohh yah you can find your cached version of plugin at /Users/parth.dave/.pub-cache/hosted/pub.dartlang.org/flutter_twitter_login-1.1.0/ something like this where you can update it. or either open android folder in androidstudio and studio will show you two projects app and twitter where you can update this things.

also sometimes it's better to open android project in android studio and update all things from which you might get errors before running flutter projects.

A: thank you, it worked for me for   device_id: ^0.1.3
plugin conflit with   cloud_firestore: ^0.13.4+2

*

*In your flutter project, locate your android folder and open it as an android project in Android Studio.

*Expand Gradle Scripts and wait for it to load.

*Locate build.gradle (Module: device_id)

*Modify the compileSdkVersion from 27 -> 28.

*Save the changes.

A: I faced a similar issue and here is how I fixed it by following this link.

*

*In Android Studio (with your project open) right-click the android folder, and click "Flutter"->"Open Android Module in Android Studio". Select "Open in New Window"

*In the new window, Wait for Gradle to finish the sync

*Expand "Gradle Scripts"

*Locate "build.gradle (Module: flutter_twitter)" or which so ever package is throwing the error

*Modify the compileSdkVersion from 28->29 (or whatever is defined in your android/app/build.gradle file).

*Save the changes and run flutter clean

*Build the signed apk.

A: seems like your firebase_messaging library version does not support AndroidX support. Make sure you have updated version of this library.
dependencies:
  firebase_messaging: ^6.0.9

A: I had the same problem before and it took almost a half day to find a solution.
My project compileSdkVersion was already 28 but in my case app-usage package compileSdkVersion was under 28 and i had to change it manually in
/home/"user"/.pub-cache/hosted/pub.dartlang.org/"package with problem"/android/build.gradle.
and it solved the problem.


text:
Q: Why are Vim filetype options ON when ~/.vimrc is missing but OFF when it is present? I am using Vim 8.1 on a Ubuntu system. Here are the three cases I have found.
Case 1
$ ls -l ~/.vimrc
ls: cannot access '/home/lone/.vimrc': No such file or directory
$ vim -u NONE +':filetype'
filetype detection:OFF  plugin:OFF  indent:OFF

Case 2
$ ls -l ~/.vimrc
ls: cannot access '/home/lone/.vimrc': No such file or directory
$ vim +':filetype'
filetype detection:ON  plugin:ON  indent:ON

Case 3
$ touch ~/.vimrc
$ ls -l ~/.vimrc
-rw-r--r-- 1 lone lone 0 Nov  2 18:41 /home/lone/.vimrc
$ vim +':filetype'
filetype detection:OFF  plugin:OFF  indent:OFF

Question

*

*Why is it that the filetype options are ON when ~/.vimrc is present but OFF when ~/.vimrc is present?

*Where in the Vim :help documentation can I find more about this behavior?

A: *

*-u NONE disables all vimrc's (including the defaults, more on that below)

*With no vimrc, the defaults come in to play (assuming you have vim >7.4.2111 or >8)

*With a vimrc, the defaults are not sourced.

From :help defaults.vim:
Defaults without a .vimrc file ~
                            *defaults.vim*
If Vim is started normally and no user vimrc file is found, the
$VIMRUNTIME/defaults.vim script is loaded.  This will set 'compatible' off,
switch on syntax highlighting and a few more things.  See the script for
details.  NOTE: this is done since Vim 8.0, not in Vim 7.4. (it was added in
patch 7.4.2111 to be exact).

This should work well for new Vim users.  If you create your own .vimrc, it is
recommended to add these lines somewhere near the top: >
    unlet! skip_defaults_vim
    source $VIMRUNTIME/defaults.vim
Then Vim works like before you had a .vimrc. Copying $VIMRUNTIME/vimrc_example
is way to do this.  Alternatively, you can copy defaults.vim to your .vimrc
and modify it (but then you won't get updates when it changes).

If you don't like some of the defaults, you can still source defaults.vim and
revert individual settings.  See the defaults.vim file for hints on how to
revert each item.
                        *skip_defaults_vim*
If you use a system-wide vimrc and don't want defaults.vim to change settings,
set the "skip_defaults_vim" variable.  If this was set and you want to load
defaults.vim from your .vimrc, first unlet skip_defaults_vim, as in the
example above.

A: vim -u NONE starts vim without any config file and sets all options to default values.
vim without ~/.vimrc reads configuration values from a system config file. Try /etc/vim/vimrc or /usr/share/vim/vimrc.
See http://vimdoc.sourceforge.net/htmldoc/starting.html#initialization


text:
Q: How to use DOM referenced .value's in different scopes? (refactoring/scope issue) Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>

See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button>

Thank HumbleOldMan later, go get rich now.

var profit = function(){

  var bp = document.getElementById("bp").value;
  var n = document.getElementById("n").value;
  var sp = document.getElementById("sp").value;
  var t = document.getElementById("t").value;
    var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
    console.log(result);
    document.getElementById("r").value = result;
}

var resetOnClick = function(){
  document.getElementById("t").value =
  document.getElementById("sp").value =
  document.getElementById("n").value =
  document.getElementById("bp").value = "";
  console.log("reset clicked");
}

// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//

And here is what I tried doing

The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.

A: You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.


text:
Q: Should we always specify ToString() explicitly? I have a custom class structure as follows.
public interface Stuff { }
public Thing : Stuff
{
  public new String ToString() { return "That's the thing!"; }
}

Then, in other parts of my code I have a method that takes a String object as a parameter. The first line compiles, while the second one doesn't. I thought that ToString was called by default when sending in an object. And Stuff, being inherited from Object class should have ToString already implemented (and also, in my case, shadowed by my implementation).
Thing thing = new Thing();
MustHaveString(thing.ToString());
MustHaveString(thing);

What do I miss?

A: Assuming MustHaveString looks something like:
public void MustHaveString(string arg)

Then simply saying thing results in a compile error, unless thing has an implicit conversion to string. Without the implicit conversion, you must do thing.ToString().  If, however, your code is like:
string myString = "This is a thing: " + thing;

Then the ToString is implicitly called, so it's optional.
In most cases, I would recommend explicitly calling the ToString method, to make it clear to people reading your code what's going on.
Edit: since this answer was accepted, I thought I should also mention that you should make your ToString() method an override, not a new. This will result in the normally-expected behavior, which is what I described above.

A: You're probably getting confused because of calls such as String.Format and Console.WriteLine, as well as string concatenation operator, which call ToString implcitly.
This isn't a general rule though. In general, if you need a string, you need to either call ToString explicitly or have some other conversion. I wouldn't recommend creating implicit conversions to string - they're likely to cause more pain than joy.
I'd also recommend against creating a new ToString method. Instead, you should override the one declared by object. Hiding methods is almost always a bad idea; there are a few cases where you really want to do it (e.g. to change the return type) but it should be avoided where possible.


text:
Q: SharePoint REST API call with more than 500 rows I have an AJAX call querying the SharePoint REST API which will return more than 500 rows:
$.ajax(
        {
             url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='Department:"
                    + "*'&selectproperties='Department'&sourceid='B09A7990-05EA-4AF9-81EF-EDFAB16C4E31'&sortlist='Department:ascending'&rowlimit=500",
                method: "GET",
                headers: {
                    "accept": "application/xml",
                },
                success: onSuccess,
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            }
        );

The REST API has a 500 row limit, so I cannot increase the rowlimit variable in the url.
In my onSuccess function, I'm trying to read the total rows to see if I need to query again for more rows:
onSuccess = function (data) {
    var rows = data.d.postquery.PrimaryQueryResult.RelevantResults.TotalRows;
....

This throws an exception that postquery does not exist, however.
How can I grab the TotalRows and query the REST API for additional rows?

A: See if these paths to the row count variables work:
data.d.query.PrimaryQueryResult.RelevantResults.RowCount

data.d.query.PrimaryQueryResult.RelevantResults.TotalRows

If you have specific questions about the object model, I find that the best first point of reference is to look at the returned xml or json using web developer tools and looking at the returned object graph.

A: You can raise the  MaxRowLimit property of your Search service application (Only with On-Prem SharePoint installation) using PowerShell to overcome this limitation. But remember, it will affect the perform though.

A: Try these.
data.d.query.PrimaryQueryResult.RelevantResults.TotalRows
data.d.query.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates
I tested on O365.

A: Here is an example that demonstrates how to  query all search results using SharePoint 2013 Search REST API:
function search(webUrl,queryText,rowLimit,startRow,allResults)
{
    var allResults = allResults || [];
    var url = webUrl + "/_api/search/query?querytext='" + queryText + "'&rowlimit=" + rowLimit + "'&startrow=" + startRow;
    return $.getJSON(url).then(function(data) {
           var relevantResults = data.PrimaryQueryResult.RelevantResults;
           allResults = allResults.concat(relevantResults.Table.Rows);
           if (relevantResults.TotalRows > startRow + relevantResults.RowCount) {
               return search(webUrl,queryText,rowLimit,startRow+relevantResults.RowCount,allResults);
           }
           return allResults;
    });
}

Key points:

*

*StartRow query parameter is used to specify next  paged search results

Usage
search(_spPageContextInfo.webAbsoluteUrl,'sharepoint',100,0)
  .done(function(results){
       for(var i = 0;i < results.length;i++){
           console.log(results[i].Cells[3].Value);
       }
   });


text:
Q: how to update table by clicking a link in php I have a project where I create a point system for students. A student may look at the solutions to a question, but if they do, they should lose 2 pts and their profile should also updated with new point score. Is it possible to update a table by clicking on a link? I attempted to do the following:
if($points >0)
{
    if(($status== '') || ($newuniq_id!= $uniq_id) || ($newquestion_id!= $quid))
    {
        $query = "insert into status(uniq_id, user_id, user_name, question_id, status) values('$uniq_id', '$id','$name','$quid','read')";
        mysql_query($query);

        $newpoints = $points - $cut_points;
        $newquery1 = "update $tabl_u set points = '$newpoints' where uniq = '$uniq1'";
        $newquer2 = mysql_query($newquery1);
    }
}

A: Assuming your php script is myscript.php
You can create each link that reference your script with the uniqid of the item you want to update.
<a href="myscript.php?update=true&uniqid=<?=$uniqid?>" />

Then in your script, you can check for the update GET request:
if (isset($_GET['update'])){
  $uniqid= $_GET['uniqid'];
  $newquery= // your update statement
}

A: You might want to check some of the PHP documentation as the mysql_* function set has been depreciated. To solve your problem, I would request back to the same page using the standard "a href" link, which will carry your data in the URL, or using $_POST if you dont want your users to see the data in the URL.
http://www.php.net/manual/en/function.mysql-query.php

mysqli_* is available to use.


text:
Q: Find an implicit solution to $y ^ { \prime } ( x ) = \frac { x ^ { 3 } } { 2 y \sqrt { 1 + y ^ { 2 } } }$ $y ^ { \prime } ( x ) = \frac { x ^ { 3 } } { 2 y \sqrt { 1 + y ^ { 2 } } }$
$\frac { d y } { d x } = \frac { x ^ { 3 } } { 2 y \sqrt { 1 + y ^ { 2 } } }$
$\frac { d x } { d y } = \frac { 2 y \sqrt { 1 + y ^ { 2 } } } { x ^ { 3 } }$
$\int x ^ { 3 } d x = 2 \int y \left( 1 + y ^ { 2 } \right) ^ { 1 / 2 } d y$
R.H.S.
$\int y \sqrt { 1 + y ^ { 2 } } d y$
let $u = 1 + y ^ { 2 }$
$ d u = 2 y d y $
$ \frac { d u } { 2 } = y d y $
$\int y \sqrt { 1 + y ^ { 2 } } d y$
$\int \sqrt { 1 + y ^ { 2 } } y d y$
$\int \frac { \sqrt { u } } { 2 } d u$
$\frac { 1 } { 2 } \int \sqrt { u } d u$
$= \frac { 1 } { 2 } \left[ \frac { 2 u ^ { 3 / 2 } } { 3 } \right]$
$= \frac { u ^ { 3 / 2 } } { 3 } = \frac { 1 } { 3 } \left( 1 + y ^ { 2 } \right) ^ { 3 / 2 } \ldots 1$
$\int x ^ { 3 } d y = 2 \int y \left( 1 + y ^ { 2 } \right) ^ { 1 / 2 } d y$
$\frac { x ^ { 4 } } { 4 } + c = 2 \left[ 1 / 3 \left( 1 + y ^ { 2 } \right) ^ { 3 / 2 } \right]$
$\frac { x ^ { 4 } } { 4 } + c = \frac { 2 } { 3 } \left( 1 + y ^ { 2 } \right) ^ { 3 / 2 }$
cant finish it , or maybe my working is wrong ?


text:
Q: Controller on angularJs On the Link below on plunker, I am trying to do a simple page connecting view 1 to view 2.
     On view 1 we can type a text which will be shown on View2.
     My difficulty is trying to understand how I can connect the Controller1  mentioned in the $stateProviderState, to the
 Controller1.js, to the view. I find it difficult to understand how the
 factory works, how to do the injection.
    Could anyone explain to me? Thank you.
Plnkr - Linking pages using ui-router
//app.module.js

var myApp = angular.module("myApp", ['ui.router']);

myApp.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when("", "/View1");

    $stateProvider
        .state("View1", {
            url: "/View1",
            templateUrl: "View1.html",
            view: {
              controller: 'Controller1'
            }
        })
        .state("View2", {
            url: "/View2",
            templateUrl: "View2.html",
            view: {
              controller: 'Controller2'
            }
         });
});

//Controller1.js

(function() {
  'use strict';
  angular
    .module("myApp")
    .factory('shareFactory', shareFactory)
    .controller('Controller1', Controller1);

  function Controller1(shareFactory, $scope, $http) {
    var vm = this;
    vm.textView1 = "SomethingToStartWith";

    function getView1() {
      shareFactory.getData()
        .then(function(response) {
          if (response.data) {
            vm.textView1 = response.data;
            console.log(vm.textView1);
          } else {
            console.log("Something was wrong");
            return;
          }

        }, function(response) {
          console.log("Entered this Error function");
        });
    }
  }
});

//Index.html

<!DOCTYPE html>

header

footer

//share.factory.js

(function() {
  angular
    .module("myApp")
    .factory('shareFactory', shareFactory);

  function shareFactory() {
    var data = '';

    return {
      getData: function() {
        return data;
      },
      setData: function(newData) {
        data = newData;
      }
    };
  }
})();

A: Maybe code explains itself?
Below code forked from your initial plunk can be found here http://plnkr.co/edit/WLe3TLTa6DKWUQ21lK3P
JavaScript
angular.module('myApp', ['ui.router'])
  .config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when('', 'view1');

    // set up states
    // no need to specify controllers in templates
    $stateProvider
      .state('view1', {
        url: '/view1',
        templateUrl: 'view1.html',
        controller: 'Controller1',
        controllerAs: 'vm'
      })
      .state('view2', {
        url: '/view2',
        templateUrl: 'view2.html',
        controller: 'Controller2',
        controllerAs: 'vm'
       });
  })

  // factory, shared data
  .factory('shareFactory', function($q) {
    var data = 'initial value';

    // mock $http using $q which returns
    // resolved/rejected promise, as would $http
    return {
      getData: function() {
        return $q.when(data); // resolve
      },
      setData: function(val) {
        if (val.length > 0) {
          data = val;
          return $q.when(); // resolve
        } else {
          return $q.reject('value can\'t be empty'); // reject
        }
      }
    };
  })
  .controller('Controller1', function(shareFactory, $state) {
    var vm = this;

    // because async
    shareFactory.getData()
      .then(function(data) {
        vm.data = data;
      });

    vm.set = function(data) {
      shareFactory.setData(data)
        .then(function() {
          vm.error = null;
          $state.go('view2');
        })
        .catch(function(e) {
          vm.error = e;
        });
    };
  })
  .controller('Controller2', function(shareFactory) {
    var vm = this;

    shareFactory.getData()
      .then(function(data) {
        vm.data = data;
      })
      .catch(function(e) {
        console.log(e);
      });
  });

index.html

view1.html

view1

  Enter a value:
  <input type="text"
         ng-model="vm.data">
  <input type="button"
         class="btn btn-default"
         value="Go to view2"
         ng-click="vm.set(vm.data)">

view2.html

view2

  The value set in view1 is:
  <input type="button"
         class="btn btn-default"
         value="Go to view1"
         ui-sref="view1">

A: Check the plunker. Injecting factory to controller, controller to main module and ui-routing
Check this
html

header

footer

main Js
var myApp = angular.module("myApp", ['ui.router','ConrollerApp']);

myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/View1");

$stateProvider
    .state("View1", {
        url: "/View1",
        templateUrl: "View1.html"

    })
    .state("View2", {
        url: "/View2",
        templateUrl: "View2.html"

     });
 });

Controller
var ctrl=angular.module("ConrollerApp",["Factory"])
ctrl.controller("AppController",function($scope,AppFactory){
 $scope.data=AppFactory.useData();
})

Factory
 var factoryapp=angular.module("Factory",[])
 factoryapp.factory("AppFactory",function(){

 return{
 useData:function(){
  var x=10;
 return x;
 }
}
})`


text:
Q: Rails: preserving callbacks when subclassing IntegrationTest I have a Rails 3 app that uses subdomains to separate different use cases.  Normal webapp requests go to www., mobile access goes to m., and requests for the JSON api are directed api..
My integration tests fall down these same divisions.  Additionally, all of my webapp integration tests use the same setup code, the mobile integration tests use different setup code, and the api tests have their own setup steps.  I want to implement a few subclasses of ActionDispatch::IntegrationTest, one for each "class" of integration test, to DRY up the code:
WebappIntegrationTest < ActionDispatch::IntegrationTest
MobileIntegrationTest < ActionDispatch::IntegrationTest
ApiIntegrationTest < ActionDispatch::IntegrationTest

These subclasses would each have setup and teardown methods that would handle preparing the test environment to run against that particular scenario.
However, I still want the ability to define setup and teardown steps in each individual test class.  That is to say, I want to be able to do this:
class IntegrationTests::Webapp::AccountTest < WebappIntegrationTest
    def setup
        # ... do webapp account-specific setup ...
    end
end

Each test in this class would then execute both the AccountTest setup AND the WebappIntegrationTest setup.  The class-specific setups need to be optional, but the subdomain-specific setups need to execute every time, regardless of whether there is a class-specific setup defined.
Here are a few approaches I have considered:

*

*I can't name both setup methods "setup" and have them both run... the AccountTest setup would clobber the WebappIntegrationTest setup.

*I could have WebappIntegrationTest implement setup, and then declare a new callback for AccountTest to optionally implement, call it "setup_extension"... but I don't want to change the API: I want new developers to be able to continue defining "setup" in the test files, oblivious to the fact that there is another setup being called upstream.

*I considered using alias_method_chain to stick the WebappIntegrationTest setup in the middle of the callback's method chain but (a) I couldn't get it to work (ruby threw and error saying it couldn't find the setup_with_x method at all), and (b) I believe that in this solution, the WebappIntegrationTest would only get called if AccountTest implemented setup, which I can't count on for all test files (though I might be wrong on this point)

Hopefully that explanation is clear enough...
Any thoughts on an elegant way to pull the shared setup code into the subdomain-specific base classes (with setup code that runs for every test of that type) while preserving the API (the ability for test classes to optionally implement their own method called "setup" in addition)?


text:
Q: $\lim _{x\to \infty }x^2\left(1-\sqrt[3]{\frac{\left(x^2-1\right)}{\left(x^2+1\right)}}\right)$ I really don't know what to try to solve this limit.
$\lim _{x\to \infty }x^2\left(1-\sqrt[3]{\frac{\left(x^2-1\right)}{\left(x^2+1\right)}}\right)$
If I multiply by x^2, it becomes an indeterminate form: + ∞ - ∞
If instead I simplify $1-\sqrt[3]{\frac{\left(x^2-1\right)}{\left(x^2+1\right)}}$ I get to ∞ * 0.
So what could I try?
I don't see a way to rewrite $x^2+1$

A: Let $$t=\sqrt[3]{\frac{\left(x^2-1\right)}{\left(x^2+1\right)}}\implies x^2=-{t^3+1\over t^3-1}$$ then
$$\lim _{t\to 1}-{t^3+1\over t^3-1}(1-t )=\lim _{t\to1 }{t^3+1\over t^2+t+1}={2\over 3}$$

A: series method...
As $x \to \infty$:
\begin{align}
\frac{x^2 - 1}{x^2+1} &= 1 - \frac{2}{x^2} + O(x^{-4})\qquad\text{(long division)}
\\
\left(\frac{x^2 - 1}{x^2+1}\right)^{1/3} &= 1 - \frac{2}{3x^2} + O(x^{-4})
\\
1 - \left(\frac{x^2 - 1}{x^2+1}\right)^{1/3} &= \frac{2}{3x^2} + O(x^{-4})
\\
x^2\left(1 - \left(\frac{x^2 - 1}{x^2+1}\right)^{1/3}\right) &=  \frac{2}{3} + O(x^{-2})
\end{align}
and thus
$$
\lim _{x\to \infty }x^2\left(1-\sqrt[3]{\frac{\left(x^2-1\right)}{\left(x^2+1\right)}}\;\right) = \frac{2}{3}
$$

A: Write $$\frac{\sqrt[3]{x^2+1}-\sqrt[3]{x^2-1}}{\sqrt[3]{x^2+1}}$$
and multiply numerator and denominator by
$$\sqrt[3]{x^2+1}^2+\sqrt{x^2+1}\sqrt[3]{x^2-1}+\sqrt[3]{x^2-1}^2$$

A: As usual,
$$1-\sqrt[3]z=\frac{1-z}{1+\sqrt[3]z+\sqrt[3]z^2}$$ and with
$$z:=\frac{x^2-1}{x^2+1}$$
the denominator tends to $3$ so that the limit reduces to that of
$$\frac13x^2\left(1-\frac{x^2-1}{x^2+1}\right).$$

$$\frac23.$$

A: You may set $x^2=\frac 1t$ and consider $t\to 0^+$.
Then, you only need the derivatives

*

*$(\star)$: $(\sqrt[3]{1-t})' =-\frac{1}{3\sqrt[3]{(1-t)^2}}$ and $(\sqrt[3]{1+t})'=\frac{1}{3\sqrt[3]{(1+t)^2}}$:

\begin{eqnarray*}x^2\left(1-\sqrt[3]{\frac{\left(x^2-1\right)}{\left(x^2+1\right)}}\right)
& \stackrel{x^2=\frac 1t}{=} & \frac{1-\sqrt[3]{\frac{1-t}{1+t}}}{t}\\
& = & \frac{1}{\sqrt[3]{1+t}}\cdot \frac{\sqrt[3]{1+t} - \sqrt[3]{1-t}}{t} \\
& = & \frac{1}{\sqrt[3]{1+t}}\cdot \left(\frac{\sqrt[3]{1+t} -1 }{t} - \frac{\sqrt[3]{1-t} -1}{t}\right) \\
& \stackrel{t \to 0^+}{\longrightarrow} & \left. (\sqrt[3]{1+t})'\right|_{t=0} - \left. (\sqrt[3]{1-t})'\right|_{t=0}\\
& \stackrel{(\star)}{=} & \frac 13 + \frac 13 = \frac{2}{3}
\end{eqnarray*}


text:
Q: Loading Nib file as inputAccessoryView I have a Nib file.  Image attached.  I would like this Nib file as the inputAccessoryView.  Reason being accessoryView doesn't adhere to Safe Area on iphoneX. grrrr!
I have set up my Nib file as per this tutorial...
https://medium.com/code-with-rohit/inputaccessoryview-and-iphonex-7b5547fe98da
How do I correctly get this Nib file inside the inputAccessoryView?

I have my custom Class "AccessoryView" as the File's Owner.  From here I struggle.
Any help as always highly appreciated.
UPDATE:
I've removed the File Owner and added the class to the top View.
In my AccessoryView Class I have
override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
        super.init(coder: aDecoder)
        if self.subviews.count == 0 {
            self.commonInit()
        }
    }

    class func instanceFromNib() -> UIView {
        return UINib(nibName: "AccessoryView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }

    private func commonInit() {
        guard let container = accessoryViewContainerView else { return }
        container.frame = self.bounds
        container.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        self.addSubview(container)
    }
}

But it gave me the below effect:

I then add the view to the inputAccessoryView as such:
override var inputAccessoryView: UIView? {
        get {
            return AccessoryView.instanceFromNib()
        }
    }

As you can see it has added the subViews but the constraints are all off.


text:
Q: In Rails 4.2 where should I keep my static assets? I'm using Rails 4.2 with the AssetPipeline. In my Sass I reference images using an absolute path like this:
.foo {
  background-image: url(/assets/images/foo.jpg)
}

This is my usual workflow for referencing assets of all kinds.
So in this case the static image ./public/assets/images/foo.jpg is referenced. This is fine in development.
In staging and production assets are precompiled and Capistrano links the ./public/assets directory, overwriting my assets. So apparently I'm not supposed to keep static assets in ./public/assets since that directory is being auto-generated.
The guide on the subject says "app/assets is for assets that are owned by the application." Well, images are own by the application. But if I put them in ./app/assets then end up all in the ./public/assets directory without their directory structure maintained. I don't like putting the images under app anyway. This doesn't work in all environments.
The guide also says "use app/assets for files that must undergo some pre-processing before they are served." That makes sense. It seems like a contradiction of the last statement I quoted, but I'm going to heed that advice because the images don't need to be processed.
What am I missing here?

A: Use the sass-rails gem, so you get nice helpers like asset-path which are both environment and magic-hash-path aware.


text:
Q: Differential equation with improper integral I have to find $f$ from the following equation:
$$\int_0^\infty f(u)\sin(ut)\,du=e^{-t}$$
where $t>0$
Any hint? Can I use the Laplace Transform method?

A: If you are not interested in finding all the solutions but just a solution you may notice that the Laplace and Cauchy distributions are related in such a way that, for any $t>0$,
$$ \int_{0}^{+\infty}\frac{u \sin(u t)}{1+u^2}\,du = \frac{1}{2}\int_{\mathbb{R}}\frac{u\sin(u t)}{1+u^2}\,du=\pi\,\text{Re}\operatorname*{Res}_{u=i}\frac{u e^{iut}}{1+u^2}=\frac{\pi}{2}e^{-t} $$
so $f(u)=\frac{2}{\pi}\cdot\frac{u}{1+u^2}$ is a solution.

A: With CAS help using MellinTransform:
$$\mathcal{M}_t\left[\int_0^{\infty } f(u) \sin (u t) \, du=\exp (-t)\right](s)$$
$$\Gamma (s) \sin \left(\frac{\pi  s}{2}\right) \mathcal{M}_u[f(u)](1-s)=\Gamma (s)$$
$$\mathcal{M}_u[f(u)](1-s)=\frac{1}{\sin \left(\frac{\pi  s}{2}\right)}$$
$$\mathcal{M}_u[f(u)](s)=\csc \left(\frac{1}{2} \pi  (1-s)\right)$$
then inverse MellinTransform is:
$$\mathcal{M}_s^{-1}\left[\mathcal{M}_u[f(u)](s)\right](u)=\mathcal{M}_s^{-1}\left[\csc \left(\frac{1}{2} \pi
   (1-s)\right)\right](u)=\mathcal{M}_s^{-1}\left[\sec \left(\frac{\pi
   s}{2}\right)\right](u)=\frac{2 u}{\pi  \left(1+u^2\right)}$$
$$f(u)=\frac{2 u}{\pi  \left(1+u^2\right)}$$


text:
Q: Como alterar uma palavra especifica em um TXT por outra Preciso alterar a configuração do servidor Zabbix que está nesse diretório C:\zabbix\conf\zabbix_agentd.win.conf
Preciso substituir a palavra: hostname= por hostname=192.168.1.1
Fiz esse, mas a parte abaixo do hostname não entendi aonde colocar o nome para procurar e aonde colocar a palavra que irá substituir. Estou usando Python 3.6
import socket
import re

hostname = socket.gethostname()

with open('C:\zabbix\conf\zabbix_agentd.win.conf') as f:
    for l in f:
        s = l.split('*')
        editar = re.sub(r"\b%s\b" % s[0] , s[1], editor)

A: Seu código não faz muito sentido pro que você está pedindo. Você não precisa usar expressões regulares pro seu caso, e nem split. Basta o replace, que é o método mais básica que faz isso e é uma função da classe str.
Além disso, mudar as variáveis depois de ler o arquivo em modo de leitura não muda o arquivo. Pra mudar o arquivo, é necessário abri-lo em modo de escrita (passando 'w' como segundo argumento do open) e escrever seus dados com write ou writelines.
Suponhamos que meu hostname seja 'DESKTOP-PI3R74I' e meu arquivo contenha o seguinte:
lalala
foo
DESKTOP-PI3R74I=
bar
foobar

Seu código ficaria assim:
import socket

hostname = socket.gethostname()
print(hostname)  # 'DESKTOP-PI3R74I'

# Abrir o arquivo em modo de leitura
with open('arquivo.txt', 'r') as fd:
    txt = fd.read()  # Ler todo o arquivo

    # Substituir hostname= por hostname=192.168.1.1 em todas as
    # ocorrências no texto lido
    txt = txt.replace(hostname + '=', hostname + '=192.168.1.1')

# Abrir o arquivo em modo de escrita
with open('arquivo.txt', 'w') as fd:
    fd.write(txt)  # Escrever texto modificado


text:
Q: replacing elements in list when certain condition met I'm working on a python script, where currently if a defined text file has certain phrases that match a list, it will remove them from the file.
Relevant list code snippets are as follows:
replacements = {'pc-123456 alert good-name-here':'',
                'pc-123456 alert remove-name-here':'',
}

Where the first half within the { is the direct text from the alert file and the:'', is to clear the text from the file if it matches. Currently, this works.
I need to add the following to the replacements list in my script, where:
replacements = {'12-Dec-19 00:00 pc-123456 alert good-name-here':'',
                '12-Dec-19 00:01 pc-123456 alert remove-name-here':'',
                '12-Dec-19 00:01 pc-234567 alert remove-name-here':'',
}

But I want to remove any detail that is defined as 'remove-name-here' (including date/time, name of device etc)., even though the alert will occur across more than 2 devices (eg. pc-123456, pc-2345678, pc-356435, pc-4563255) etc.
What's the simplest way to remove the whole text line if the script picks up a different device name for the same alert name, and to remove the time stamp (that is not defined currently within the replacements list)?
Rest of code is as follows:
lines = []
with open('path/to/file.txt') as infile:
    for line in infile:
        for src, target in replacements.items():
            line = line.replace(src, target)
        lines.append(line)

with open('path/to/same/file.txt', 'w') as outfile:
    for line in lines:
        outfile.write(line)

Thanks.

A: If you know what is at the end of a line you can do something like this:

to_remove_endings = ['to_remove_ending']
lines = []

with open('path/to/file.txt') as infile:
    for line in infile:
        next_line = line
        for ending in to_remove_endings:
            if line.rstrip().endswith(ending):
                next_line = '\n'
                break
        lines.append(next_line)

with open('path/to/same/file.txt', 'w') as outfile:
    for line in lines:
        outfile.write(line)

You can also look for substrings:
unwanted = ['substring 1', 'substring 2']
lines = []

with open('path/to/file.txt') as infile:
    for line in infile:
        next_line = line
        for substring in unwanted:
            if substring in line:
                next_line = '\n'
                break
        lines.append(next_line)

with open('path/to/same/file.txt', 'w') as outfile:
    for line in lines:
        outfile.write(line)


text:
Q: Create configurable product using multiple bundle products Lot of time, people have inquired about creating bundle product from multiple configurable products. Even extensions are available for the same.
But my requirement is different.
I require to attach payment frequency (recurring profile) attribute to bundle product, and based on that require to generate configurable product.
I am not getting enough pointers for the same.
So basically, what I need is:
When I create configurable product, I should be able to select bundle products, along with simple products.
Any pointers would be helpful.
If ready-made such solution is not available, please suggest what things I should be take care of.


text:
Q: Is there a way in Django Admin, without custom HTML, to add a custom autocomplete_field that upon save provides a queryset to a model field? Currently, in one of my Django admin model views, I am able to individually select multiple available countries (Applicant countries) as is available in my database:

But this is very tiresome when actually I only really work with a handful of country groupings. But I do have a need to add or subtract the odd country without being required to manage and think of category names for each group of countries.
The idea I had was to use keywords (also serves other purposes in the application):

What I want to do is add a custom field via admin.ModelAdmin that is also an autocomplete_field, showing the keywords associated with countries in a dropdown. If an item on this dropdown is selected, it would return a queryset of countries with selected keyword to the model field (Applicant countries). Nothing else would need to be saved, don't need to keep track of which country associated keywords were used in the past. It is just a shortcut to bulk selecting many countries at once (so upon add/edit, the custom field would always appear empty).
I want as far as possible to do things the Django admin way, without touching custom HTML and things like that. If this is not possible, I will explore a solution that involves a Django-Q task.
Here is some code to explain the relationships:
models.py -> Keyword:
class Keyword(models.Model):
    name = models.TextField()

models.py -> Country:
class Country(models.Model):
    """
    More info: https://en.wikipedia.org/wiki/ISO_3166-1
    """

    name = models.TextField()
    alpha_2_code = models.CharField(max_length=2)
    alpha_3_code = models.CharField(max_length=3)
    independent = models.BooleanField()
    keywords = models.ManyToManyField(Keyword)

models.py -> FundingProgram
class FundingProgram(models.Model):
    # Unimportant fields redacted
    applicant_countries = models.ManyToManyField(Country, blank=True)

admin.py -> FundingProgramAdmin
@admin.register(models.FundingProgram)
class FundingProgramAdmin(admin.ModelAdmin, DynamicArrayMixin):
    autocomplete_fields = (
        "applicant_countries",
    )
    search_fields = (
        "applicant_countries__keywords__name",
    )

    # Here is where I think I should make a custom field,
    # that acts as a multiple choice (autocomplete) dropdown where
    # a function takes input and returns a queryset to applicant_countries field

A: I managed to solve the problem with the use of Django Autocomplete Light library.
This is what I did (only included relevant additions here, read docs on how to install the library, etc).
views.py (Todo: Make below codeblock more DRY)
from dal import autocomplete

from my_app import models

class KeywordsSelect(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated:
            return models.Keyword.objects.none()
        qs = models.Keyword.objects.all()
        if self.q:
            # Todo: Probably worth sorting the queryset for consistency
            qs = qs.filter(name__istartswith=self.q)
        return qs

    def get_result_value(self, result):
        return result.pk

class CountriesSelect(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated:
            return models.Country.objects.none()
        qs = models.Country.objects.all()
        if self.q:
            # Todo: Probably worth sorting the queryset for consistency
            qs = qs.filter(name__istartswith=self.q)
        return qs

    def get_result_value(self, result):
        return result.pk

urls.py
from django.conf.urls import url
from my_app import views
urlpatterns = [
    url(r"^keywords-select/$", views.KeywordsSelect.as_view(), name="keywords-select",),
    url(r"^countries-select/$", views.CountriesSelect.as_view(), name="countries-select",),
 ]

The above creates an endpoint which can be queried like: http://localhost:8000/countries-select/?q=Austri, returning an output such as:
{
  "results": [
    {
      "id": 9,
      "text": "Austria",
      "selected_text": "Austria"
    }
  ],
  "pagination": {
    "more": false
  }
}

Now we can modify admin to include a modified form that will call this endpoint in an autoselect box. Note below that I need to explicitly list all of the fields and to get two fields to exist side by side, they need to be contained in their own tuple, ("applicant_countries", "bulk_add_countries_by_keyword",) below.
admin.py
from dal import autocomplete
from django import forms

class FundingProgramForm(forms.ModelForm):
    # Newly created field not retrieved from models.py
    bulk_add_countries_by_keyword = forms.ModelMultipleChoiceField(
        queryset=models.Keyword.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(url="keywords-select"),
        required=False,
    )

    class Meta:
        # applicant_countries is a field from models.py which gets overridden here
        widgets = {
            "applicant_countries": autocomplete.ModelSelect2Multiple(
                url="countries-select"
            )
        }

    def save(self, commit=True):
        qs = self.cleaned_data["applicant_countries"].union(
            models.Country.objects.filter(
                keywords__in=self.cleaned_data["bulk_add_countries_by_keyword"]
            )
        )
        self.cleaned_data["applicant_countries"] = qs
        return super(FundingProgramForm, self).save(commit=commit)

@admin.register(models.FundingProgram)
class FundingProgramAdmin(admin.ModelAdmin):
    form = FundingProgramForm
    # Other fields hardcoded below, otherwise they won't appear in model form
    fields = (
        ("applicant_countries", "bulk_add_countries_by_keyword",),
    )
    # Warning: Remove the following from autocomplete_fields, as it is already overidden with a django autocomplete light widget
    #     autocomplete_fields = (
    #         "applicant_countries",
    #     )


text:
Q: CFG for a^n b^3m c d^m e f^2n with m, n > 0 I want to find the CFG for this a^n b^3m c d^m e f^2n  with m, n > 0
What I have so far
S -> A B C
A -> a A ff
B -> bbb B d
C -> c e

Does this make any sense?

A: I think that this is the grammar:
; this rule generates "a" first and "ff" last
S = a A ff

; allow more "a" first and "ff" last
A = S

; between "a^n" and "f^2n" there will be "b^3m c d^m" followed by "e"
A = B e

; this rule generates "bbb" first and "d" last
B = bbb C d

; allow more "bbb" first and "d" last
C = B

; this rules generates "c" between "b^3m" and "d^m"
C = c

A: Your grammar so far allows the c to come after the d which violates the rules.
The following should work
S = a S ff | a bbb B d e ff
B = bbb B d | c

The first rule guarantees, that for every a in the beginning there are two f in the end. It enforces at least one a. The second half enforces the sequence d e ff....
The second rule enforces the correct number of b and d and also that the single c is between the bs and the cs


text:
Q: Sum object key by key with Mongo on Node I'm trying to group all this object in one, the idea is to combine all the object.
My function know is like this:
app.get('/stats/:id(\\d+)/weapon/:weapon', function(req, res, next) {
        db.collection('stats').aggregate( [
            { $match: { _id: parseInt(req.params.id, 10) } },
            { $unwind: "$session" },
            { $addFields: { weapon: { $objectToArray: '$session.weapons.' + sanitize(req.params.weapon) }, _id: false } },
            { $addFields: { weapon: { $arrayToObject: "$weapon" } } },
            { $project: { weapon: "$weapon", _id: false }  }
         ], function(err, doc) {
                if( !err ) {
                    res.json(doc);
                }
                else {
                    console.log(err);
                    res.end();
                }
        });
    });

and return something like this:
[
   {
      "weapon":{
         "shots":30,
         "hitbox":{
            "head":7,
            "chest":4
         },
         "kills":4,
         "dmg":590
      }
   },
   {
      "weapon":{
         "shots":46,
         "kills":4,
         "hitbox":{
            "head":3,
            "chest":4,
            "stomach":3,
            "left_leg":2
         },
         "hs":3,
         "dmg":479
      }
   },
   {
      "weapon":{
         "shots":30,
         "hitbox":{
            "head":7,
            "chest":4
         },
         "kills":4,
         "dmg":590
      }
   }
]

My idea is to return only one instance of weapon with the sum key by key.
I already try $group and concat array but i can't get the result that i want...
I want like this:
[
   {
      "weapon":{
         "shots":160,
         "hitbox":{
            "head":17,
            "chest":12,
            "stomach":3,
            "left_leg":2
         },
         "kills":12,
         "hs":3,
         "dmg":1659
      }
   }
]


text:
Q: Android - Interactive ImageViews I have an image that have several portions inside that are supposed to become selectable.
The task is that user will tap on specific small portion of image and that location is recorded and sent back to a callback somehow.

I am at very initial planning stage with this app, so there is no code examples whatsoever.
p.s. if this does not lie under stackoverflow forum, please suggest where I can post it and get the fastest response possible.


text:
Q: How to add multiple stylesheets for mobile and tablet in opencart theme Im using an edited version of the default theme. I want to have multiple css files for mobile and tablet. I've added mobile.css and tablet.css to the header file right after the stylesheet.css code
However the stylesheet is not loading. NO changes are made if I resize the browser.
My header.tpl looks like this:
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<!--[if IE 8 ]><html dir="<?php echo $direction; ?>" lang="<?php echo $lang; ?>" class="ie8"><![endif]-->
<!--[if IE 9 ]><html dir="<?php echo $direction; ?>" lang="<?php echo $lang; ?>" class="ie9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<html dir="<?php echo $direction; ?>" lang="<?php echo $lang; ?>">
<!--<![endif]-->
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $title; ?></title>
<base href="<?php echo $base; ?>" />
<?php if ($description) { ?>
<meta name="description" content="<?php echo $description; ?>" />
<?php } ?>
<?php if ($keywords) { ?>
<meta name="keywords" content= "<?php echo $keywords; ?>" />
<?php } ?>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<?php if ($icon) { ?>
<link href="<?php echo $icon; ?>" rel="icon" />
<?php } ?>
<?php foreach ($links as $link) { ?>
<link href="<?php echo $link['href']; ?>" rel="<?php echo $link['rel']; ?>" />
<?php } ?>
<script src="catalog/view/javascript/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
<link href="catalog/view/javascript/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />
<script src="catalog/view/javascript/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<link href="catalog/view/javascript/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Open+Sans:400,400i,300,700" rel="stylesheet" type="text/css" />
<link href="catalog/view/theme/default/stylesheet/stylesheet.css" rel="stylesheet">

<link href="catalog/view/theme/default/stylesheet/mobile.css" rel="stylesheet">

<?php foreach ($styles as $style) { ?>
<link href="<?php echo $style['href']; ?>" type="text/css" rel="<?php echo $style['rel']; ?>" media="<?php echo $style['media']; ?>" />
<?php } ?>
<script src="catalog/view/javascript/common.js" type="text/javascript"></script>
<?php foreach ($scripts as $script) { ?>
<script src="<?php echo $script; ?>" type="text/javascript"></script>
<?php } ?>
<?php echo $google_analytics; ?>
</head>

Thanks

A: to resize display with screen width you have to use:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link re`l="stylesheet" href="main.css" media="screen>
<link rel="stylesheet" href="mobile.css" media="screen and (max-width: 640px)">

In this example main.css is used in all case, and mobile.css will be applied when screen will pass below 640px
(and you can add another one to lower resolution if needed)
In your code, mobile css should be applied all the time, so maybe you should use your brower console to check if links are good...
and check if you don't overwrite your css in
<?php foreach ($styles as $style) { ?>
<link href="<?php echo $style['href']; ?>" type="text/css" rel="<?php echo $style['rel']; ?>" media="<?php echo $style['media']; ?>" />
<?php } ?>

Create opencart theme

*

*http://code.tutsplus.com/tutorials/create-a-custom-theme-with-opencart-introduction--cms-21786

*http://code.tutsplus.com/tutorials/create-a-custom-theme-with-opencart-part-two--cms-21865

*http://code.tutsplus.com/tutorials/create-a-custom-theme-with-opencart-part-three--cms-21890

*http://code.tutsplus.com/tutorials/create-a-custom-theme-with-opencart-part-four--cms-21932
To clear opencart cache:

*

*image cache located at in public_html/image/cache

*if you have vqmod public_html/vqmod/vqcache

*system cache public_html/system/cache

Do not delete the cache folder only the contents within them folders.