Programs & Examples On #Visual studio sdk

The Visual Studio SDK includes documentation, samples, and code to help you develop products that integrate with the Visual Studio product family.

Regex to extract substring, returning 2 results for some reason

Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)

var source = "afskfsd33j"
var result = source.match(/a(.*)j/);

result: ["afskfsd33j", "fskfsd33"]

The reason why you received this exact result is following:

First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".

Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".

If you want to get rid of second value in array you may define pattern like this:

/a(?:.*)j/

where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.

Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:

/a.*j/

If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:

var result = /a.*j/.test(source);

The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml

Background color of text in SVG

The previous answers relied on doubling up text and lacked sufficient whitespace.

By using atop and   I was able to get the results I wanted.

This example also includes arrows, a common use case for SVG text labels:

<svg viewBox="-105 -40 210 234">
<title>Size Guide</title>
<defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
        <feFlood flood-color="white"></feFlood>
        <feComposite in="SourceGraphic" operator="atop"></feComposite>
    </filter>
    <marker id="arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
        <path d="M 0 0 L 10 5 L 0 10 z"></path>
    </marker>
</defs>
<g id="garment">
    <path id="right-body" fill="none" stroke="black" stroke-width="1" stroke-linejoin="round" d="M0 0 l30 0 l0 154 l-30 0"></path>
    <path id="right-sleeve" d="M30 0 l35 0 l0 120 l-35 0" fill="none" stroke-linejoin="round" stroke="black" stroke-width="1"></path>
    <use id="left-body" href="#right-body" transform="scale(-1,1)"></use>
    <use id="left-sleeve" href="#right-sleeve" transform="scale(-1,1)"></use>
    <path id="collar-right-top" fill="none" stroke="black" stroke-width="1" stroke-linejoin="round" d="M0 -6.5 l11.75 0 l6.5 6.5"></path>
    <use id="collar-left-top" href="#collar-right-top" transform="scale(-1,1)"></use>
    <path id="collar-left" fill="white" stroke="black" stroke-width="1" stroke-linejoin="round" d="M-11.75 -6.5 l-6.5 6.5 l30 77 l6.5 -6.5 Z"></path>
    <path id="front-right" fill="white" stroke="black" stroke-width="1" d="M18.25 0 L30 0 l0 154 l-41.75 0 l0 -77 Z"></path>
    <line x1="0" y1="0" x2="0" y2="154" stroke="black" stroke-width="1" stroke-dasharray="1 3"></line>
    <use id="collar-right" href="#collar-left" transform="scale(-1,1)"></use>
</g>
<g id="dimension-labels">
    <g id="dimension-sleeve-length">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="85" y1="0" x2="85" y2="120" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="85" y="60" class="dimension" text-anchor="middle" dominant-baseline="middle"> 120 cm</text>
    </g>
    <g id="dimension-length">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-85" y1="0" x2="-85" y2="154" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="-85" y="77" text-anchor="middle" dominant-baseline="middle" class="dimension"> 154 cm</text>
    </g>
    <g id="dimension-sleeve-to-sleeve">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-65" y1="-20" x2="65" y2="-20" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="0" y="-20" text-anchor="middle" dominant-baseline="middle" class="dimension">&nbsp;130 cm&nbsp;</text>
    </g>
    <g title="Back Width" id="dimension-back-width">
        <line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-30" y1="174" x2="30" y2="174" stroke="black" stroke-width="1"></line>
        <text font-size="10" filter="url(#solid)" fill="black" x="0" y="174" text-anchor="middle" dominant-baseline="middle" class="dimension">&nbsp;60 cm&nbsp;</text>
    </g>
</g>
</svg>

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

How to analyze disk usage of a Docker container

Keep in mind that docker ps --size may be an expensive command, taking more than a few minutes to complete. The same applies to container list API requests with size=1. It's better not to run it too often.

Take a look at alternatives we compiled, including the du -hs option for the docker persistent volume directory.

SQL WHERE ID IN (id1, id2, ..., idn)

Doing the SELECT * FROM MyTable where id in () command on an Azure SQL table with 500 million records resulted in a wait time of > 7min!

Doing this instead returned results immediately:

select b.id, a.* from MyTable a
join (values (250000), (2500001), (2600000)) as b(id)
ON a.id = b.id

Use a join.

Calculate correlation for more than two variables?

You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:

http://www.statmethods.net/stats/correlations.html

Invalid application of sizeof to incomplete type with a struct

The cause of errors such as "Invalid application of sizeof to incomplete type with a struct ... " is always lack of an include statement. Try to find the right library to include.

How do you debug React Native?

Instead of Cmd+M, for Android Emulator Press F10 in Windows. The emulator starts to show all the react-native debug options.

image

Reference — What does this symbol mean in PHP?

<=> Spaceship Operator

Added in PHP 7

The spaceship operator <=> is the latest comparison operator added in PHP 7. It is a non-associative binary operator with the same precedence as equality operators (==, !=, ===, !==). This operator allows for simpler three-way comparison between left-hand and right-hand operands.

The operator results in an integer expression of:

  • 0 when both operands are equal
  • Less than 0 when the left-hand operand is less than the right-hand operand
  • Greater than 0 when the left-hand operand is greater than the right-hand operand

e.g.

1 <=> 1; // 0
1 <=> 2; // -1
2 <=> 1; // 1

A good practical application of using this operator would be in comparison type callbacks that are expected to return a zero, negative, or positive integer based on a three-way comparison between two values. The comparison function passed to usort is one such example.

Before PHP 7 you would write...

$arr = [4,2,1,3];

usort($arr, function ($a, $b) {
    if ($a < $b) {
        return -1;
    } elseif ($a > $b) {
        return 1;
    } else {
        return 0;
    }
});

Since PHP 7 you can write...

$arr = [4,2,1,3];

usort($arr, function ($a, $b) {
    return $a <=> $b;
});

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

What is the main difference between Inheritance and Polymorphism?

With Inheritance the implementation is defined in the superclass -- so the behavior is inherited.

class Animal
{
  double location;
  void move(double newLocation)
  {
    location = newLocation;
  }
}

class Dog extends Animal;

With Polymorphism the implementation is defined in the subclass -- so only the interface is inherited.

interface Animal
{
  void move(double newLocation);
}

class Dog implements Animal
{
  double location;
  void move(double newLocation)
  {
    location = newLocation;
  }
}

Should try...catch go inside or outside a loop?

While performance might be the same and what "looks" better is very subjective, there is still a pretty big difference in functionality. Take the following example:

Integer j = 0;
    try {
        while (true) {
            ++j;

            if (j == 20) { throw new Exception(); }
            if (j%4 == 0) { System.out.println(j); }
            if (j == 40) { break; }
        }
    } catch (Exception e) {
        System.out.println("in catch block");
    }

The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.

Before any details, here the other example:

Integer i = 0;
    while (true) {
        try {
            ++i;

            if (i == 20) { throw new Exception(); }
            if (i%4 == 0) { System.out.println(i); }
            if (i == 40) { break; }

        } catch (Exception e) { System.out.println("in catch block"); }
    }

Same logic as above, only difference is that the try/catch block is now inside the while loop.

Here comes the output (while in try/catch):

4
8
12 
16
in catch block

And the other output (try/catch in while):

4
8
12
16
in catch block
24
28
32
36
40

There you have quite a significant difference:

while in try/catch breaks out of the loop

try/catch in while keeps the loop active

Align DIV's to bottom or baseline

The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.

CSS

#container {
        display: table;
        height: auto;
}

#top {
    display: table-cell;
    width:50%;
    height: 100%;
}

#bottom {
    display: table-cell;
    width:50%;
    vertical-align: bottom;
    height: 100%;
}

HTML

<div id=“container”>
    <div id=“top”>Dynamic content aligned to top of #container</div>
    <div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>

Example

I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.

How do I get the last inserted ID of a MySQL table in PHP?

there is a function to know what was the last id inserted in the current connection

mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
$id = mysql_insert_id();

plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.

That function is called mysql_insert_id

What is the size of an enum in C?

Taken from the current C Standard (C99): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

6.7.2.2 Enumeration specifiers
[...]
Constraints
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
[...]
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

Not that compilers are any good at following the standard, but essentially: If your enum holds anything else than an int, you're in deep "unsupported behavior that may come back biting you in a year or two" territory.

Update: The latest publicly available draft of the C Standard (C11): http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf contains the same clauses. Hence, this answer still holds for C11.

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

Why is list initialization (using curly braces) better than the alternatives?

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)

Why is it not advisable to have the database and web server on the same machine?

Ok! Here is the thing, it is more Secure to have your DB Server installed on another Machine and your Application on the Web Server. You then connect your application to the DB with a Web Link. Thanks it.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

performSelector may cause a leak because its selector is unknown

This code doesn't involve compiler flags or direct runtime calls:

SEL selector = @selector(zeroArgumentMethod);
NSMethodSignature *methodSig = [[self class] instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setSelector:selector];
[invocation setTarget:self];
[invocation invoke];

NSInvocation allows multiple arguments to be set so unlike performSelector this will work on any method.

How do I access my webcam in Python?

gstreamer can handle webcam input. If I remeber well, there are python bindings for it!

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How can I decrypt MySQL passwords

You can't decrypt password in mysql, because password is hashed by using md5 hash algorithm, which is not an encoding algorithm.

Incrementing a date in JavaScript

Tomorrow in one line in pure JS but it's ugly !

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

C# 'or' operator?

if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{    // Do stuff here
}

Error #2032: Stream Error

From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.

Here are the links where I found this information:

http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/

http://curtismorley.com/2008/02/08/actionscript-error-2032/

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.

There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen variable, and thus no way of telling when user is in the minimal-ui in advance.

These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:

When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID brim-treadmill.

Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).

When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.

The end result looks like this:

Brim in iOS simulator.

For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.

Scream and orientationchangeend have been developed as part of this project.

keytool error bash: keytool: command not found

find your jre location ::sudo find / -name jre And then :: sudo update-alternatives --install /usr/bin/keytool keytool /opt/jdk/<jdk.verson>/jre/bin/keytool 100

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

How do I reset a sequence in Oracle?

This stored procedure restarts my sequence:

Create or Replace Procedure Reset_Sequence  
  is
  SeqNbr Number;
begin
   /*  Reset Sequence 'seqXRef_RowID' to 0    */
   Execute Immediate 'Select seqXRef.nextval from dual ' Into SeqNbr;
   Execute Immediate 'Alter sequence  seqXRef increment by - ' || TO_CHAR(SeqNbr) ;
   Execute Immediate 'Select seqXRef.nextval from dual ' Into SeqNbr;
   Execute Immediate 'Alter sequence  seqXRef increment by 1';
END;

/

Binary Search Tree - Java Implementation

You can use a TreeMap data structure. TreeMap is implemented as a red black tree, which is a self-balancing binary search tree.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

The C99 stdint.h defines these:

  • int8_t
  • int16_t
  • int32_t
  • uint8_t
  • uint16_t
  • uint32_t

And, if the architecture supports them:

  • int64_t
  • uint64_t

There are various other integer typedefs in stdint.h as well.

If you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway.

The uint32 and uint64 (i.e. without the _t suffix) are probably application specific.

How do I format a string using a dictionary in python-3.x?

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

how to fix Cannot call sendRedirect() after the response has been committed?

you have already forwarded the response in catch block:

RequestDispatcher dd = request.getRequestDispatcher("error.jsp");

dd.forward(request, response);

so, you can not again call the :

response.sendRedirect("usertaskpage.jsp");

because it is already forwarded (committed).

So what you can do is: keep a string to assign where you need to forward the response.

    String page = "";
    try {

    } catch (Exception e) {
      page = "error.jsp";
    } finally {
      page = "usertaskpage.jsp";
    }

RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);

Android Linear Layout - How to Keep Element At Bottom Of View?

Step 1 : Create two view inside a linear layout

Step 2 : First view must set to android:layout_weight="1"

Step 3 : Second view will automatically putted downwards

<LinearLayout
android:id="@+id/botton_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

    <View
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

    <Button
    android:id="@+id/btn_health_advice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>


</LinearLayout>

Android ListView selected item stay highlighted

Simplistic way is,if you are using listview in a xml,use this attributes on your listview,

android:choiceMode="singleChoice"
android:listSelector="#your color code"

if not using xml,by programatically

listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);

Display JSON as HTML

Here's a light-weight solution, doing only what OP asked, including highlighting but nothing else: How can I pretty-print JSON using JavaScript?

Better way to sum a property value in an array

It's working for me in TypeScript and JavaScript:

_x000D_
_x000D_
let lst = [_x000D_
     { description:'Senior', price: 10},_x000D_
     { description:'Adult', price: 20},_x000D_
     { description:'Child', price: 30}_x000D_
];_x000D_
let sum = lst.map(o => o.price).reduce((a, c) => { return a + c });_x000D_
console.log(sum);
_x000D_
_x000D_
_x000D_

I hope is useful.

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

How to write to a CSV line by line?

You could just write to the file as you would write any normal file.

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)

Resetting a setTimeout

var redirectionDelay;
function startRedirectionDelay(){
    redirectionDelay = setTimeout(redirect, 115000);
}
function resetRedirectionDelay(){
    clearTimeout(redirectionDelay);
}

function redirect(){
    location.href = 'file.php';
}

// in your click >> fire those
resetRedirectionDelay();
startRedirectionDelay();

here is an elaborated example for what's really going on http://jsfiddle.net/ppjrnd2L/

Find oldest/youngest datetime object in a list

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

Angular IE Caching issue for $http

The guaranteed one that I had working was something along these lines:

myModule.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.common) {
        $httpProvider.defaults.headers.common = {};
    }
    $httpProvider.defaults.headers.common["Cache-Control"] = "no-cache";
    $httpProvider.defaults.headers.common.Pragma = "no-cache";
    $httpProvider.defaults.headers.common["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT";
}]);

I had to merge 2 of the above solutions in order to guarantee the correct usage for all methods, but you can replace common with get or other method i.e. put, post, delete to make this work for different cases.

Specify an SSH key for git push for a given domain

Another alternative is to use ssh-ident, to manage your ssh identities.

It automatically loads and uses different keys based on your current working directory, ssh options, and so on... which means you can easily have a work/ directory and private/ directory that transparently end up using different keys and identities with ssh.

PHP: How do I display the contents of a textfile on my page?

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Try this to open a file in php

Refer this: (http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)

How to convert QString to int?

Use .toInt() for int .toFloat() for float and .toDouble() for double

toInt();

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Try this:

private void txtEntry_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string trimText;

            trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
            this.txtEntry.Text = trimText;
            btnEnter.PerformClick();
        }
    }

How to call a function from another controller in angularjs?

If the two controller is nested in One controller.
Then you can simply call:

$scope.parentmethod();  

Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.

Maven package/install without test (skip tests)

The best and the easiest way to do it, in IntelliJ Idea in the window “Maven Project”, and just don’t click on the test button. I hope, I helped you. Have a good day :)

How to increment a letter N times per iteration and store in an array?

ord() will not work because your end string is two characters long.

Returns the ASCII value of the first character of string.

Watch it break.

From my testing, you need to check that the end string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.

Code: (Demo)

function excelCols($letter,$end,$step=1){  // function doesn't check that $end is "later" than $letter
    if($step==0)return [];  // prevent infinite loop
    do{
        $letters[]=$letter;  // store letter
        for($x=0; $x<$step; ++$x){  // increment in accordance with $step declaration
            if($letter===$end)break(2);  // break if end is "stepped on"
            ++$letter;
        }
    }while(true);
    return $letters;    
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));

Output:

A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
 --- 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX

Here is an array-functions approach:

Code: (Demo)

$start='C';
$end='DD';
$step=4;

// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1);  // store A - Z as $array and $result
foreach($array as $a){
    foreach($array as $b){
        $result[]="$a$b";  // store double letter combinations
        if(in_array($end,$result)){break(2);}  // stop asap
    }
}
//echo implode(' ',$result),"\n\n";

// slice away from the front of the array
$result=array_slice($result,array_search($start,$result));  // reindex keys
//echo implode(' ',$result),"\n\n";

 // punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo

// result is ready
echo implode(' ',$result);

Output:

C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

When restoring a backup, how do I disconnect all active connections?

To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

TLS 1.2 not working in cURL

You must use an integer value for the CURLOPT_SSLVERSION value, not a string as listed above

Try this:

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2

http://php.net/manual/en/function.curl-setopt.php

value should be an integer for the following values of the option parameter: CURLOPT_SSLVERSION

One of

CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).

hash function for string

There are a number of existing hashtable implementations for C, from the C standard library hcreate/hdestroy/hsearch, to those in the APR and glib, which also provide prebuilt hash functions. I'd highly recommend using those rather than inventing your own hashtable or hash function; they've been optimized heavily for common use-cases.

If your dataset is static, however, your best solution is probably to use a perfect hash. gperf will generate a perfect hash for you for a given dataset.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

I had issues getting through a form because of this error.

I used Ctrl+Click to click the submit button and navigate through the form as usual.

Search for "does-not-contain" on a DataFrame in pandas

Additional to nanselm2's answer, you can use 0 instead of False:

df["col"].str.contains(word)==0

HTML+CSS: How to force div contents to stay in one line?

I jumped here looking for the very same thing, but none worked for me.

There are instances where regardless what you do, and depending on the system (Oracle Designer: Oracle 11g - PL/SQL), divs will always go to the next line, in which case you should use the span tag instead.

This worked wonders for me.

<span float: left; white-space: nowrap; overflow: hidden; onmouseover="rollOverImageSectionFiveThreeOne(this)">
    <input type="radio" id="radio4" name="p_verify_type" value="SomeValue"  />
</span> 
Just Your Text || 
<span id="headerFiveThreeOneHelpText" float: left; white-space: nowrap; overflow: hidden;></span>

How do I disable form resizing for users?

I always use this:

// Lock form
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;

This way you can always resize the form from Designer without changing code.

Equation for testing if a point is inside a circle

Calculate the Distance

D = Math.Sqrt(Math.Pow(center_x - x, 2) + Math.Pow(center_y - y, 2))
return D <= radius

that's in C#...convert for use in python...

Is there a CSS selector by class prefix?

It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):

div[class^="status-"], div[class*=" status-"]

Notice the space character in the second attribute selector. This picks up div elements whose class attribute meets either of these conditions:

  • [class^="status-"] — starts with "status-"

  • [class*=" status-"] — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class attributes dynamically).

Naturally, this also works in jQuery, as demonstrated here.

The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"] will match the following element, which may be undesirable:

<div id='D' class='foo-class foo-status-bar bar-class'></div>

If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.

If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status- prefix its own status class instead as Gumbo suggests.

Print time in a batch file (milliseconds)

Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.

g++ undefined reference to typeinfo

I encounter an situation that is rare, but this may help other friends in similar situation. I have to work on an older system with gcc 4.4.7. I have to compile code with c++11 or above support, so I build the latest version of gcc 5.3.0. When building my code and linking to the dependencies if the dependency is build with older compiler, then I got 'undefined reference to' error even though I clearly defined the linking path with -L/path/to/lib -llibname. Some packages such as boost and projects build with cmake usually has a tendency to use the older compiler, and they usually cause such problems. You have to go a long way to make sure they use the newer compiler.

SQL: ... WHERE X IN (SELECT Y FROM ...)

One reason why you might prefer to use a JOIN rather than NOT IN is that if the Values in the NOT IN clause contain any NULLs you will always get back no results. If you do use NOT IN remember to always consider whether the sub query might bring back a NULL value!

RE: Question in Comments

'x' NOT IN (NULL,'a','b')

= 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'

= Unknown and True and True

= Unknown

AttributeError: Module Pip has no attribute 'main'

For me this issue occured when I was running python while within my site-packages folder. If I ran it anywhere else, it was no longer an issue.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

Have Excel formulas that return 0, make the result blank

Just append an empty string to the end. It forces Excel to see it for what it is.

For example:

=IFERROR(1/1/INDEX(A,B,C) & "","")

Any way to generate ant build.xml file automatically from Eclipse?

I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).

We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:

ant-build-for-java

To use it, call:

java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]

The first argument is the folder with the repositories. It will search the folder recursively for any .project file. The tool will create a build.xml in the given folder.

Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.

The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.

Spark java.lang.OutOfMemoryError: Java heap space

To add a use case to this that is often not discussed, I will pose a solution when submitting a Spark application via spark-submit in local mode.

According to the gitbook Mastering Apache Spark by Jacek Laskowski:

You can run Spark in local mode. In this non-distributed single-JVM deployment mode, Spark spawns all the execution components - driver, executor, backend, and master - in the same JVM. This is the only mode where a driver is used for execution.

Thus, if you are experiencing OOM errors with the heap, it suffices to adjust the driver-memory rather than the executor-memory.

Here is an example:

spark-1.6.1/bin/spark-submit
  --class "MyClass"
  --driver-memory 12g
  --master local[*] 
  target/scala-2.10/simple-project_2.10-1.0.jar 

How to iterate through a list of objects in C++

Since C++ 11, you could do the following:

for(const auto& student : data)
{
  std::cout << student.name << std::endl;
}

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This error can be because of no SSH key on the your local machine. Check the SSH key locally:

$ cat ~/.ssh/id_rsa.pub

If above command do not give any output use below command to create ssh key(Linux/Mac):

$ ssh-keygen 

Now again run cat ~/.ssh/id_rsa.pub This is your SSH key. Copy and add this key to your SSH keys in on git. In gitlab/bitbucket go to

profile settings -> SSH Keys -> add Key

and add the key

sql query to get earliest date

Using "limit" and "top" will not work with all SQL servers (for example with Oracle). You can try a more complex query in pure sql:

select mt1.id, mt1."name", mt1.score, mt1."date" from mytable mt1
where mt1.id=2
and mt1."date"= (select min(mt2."date") from mytable mt2 where mt2.id=2)

Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

Window.open and pass parameters by post method

I've used this in the past, since we typically use razor syntax for coding

@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))

{

// add hidden and form filed here

}

How would I access variables from one class to another?

Can you explain why you want to do this?

You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:

class ClassA(object):
   var1 = 1
   var2 = 2
   @classmethod
   def method(cls):
       cls.var1 = cls.var1 + cls.var2
       return cls.var1

In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.

I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

This is the solution, which is worked for me.

<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
                    actionListener="#{userGroupSetupController.saveData()}" 
                    update="growl userGroupList userGroupSetupForm" />

Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from @ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.

Trigger css hover with JS

I don't think what your asking is possible.

See: Hover Item with JQuery

Basically, adding a class is the only way to accomplish this that I am aware of.

How to convert std::string to LPCWSTR in C++ (Unicode)

I prefer using standard converters:

#include <codecvt>

std::string s = "Hi";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(s);
LPCWSTR result = wide.c_str();

Please find more details in this answer: https://stackoverflow.com/a/18597384/592651


Update 12/21/2020 : My answer was commented on by @Andreas H . I thought his comment is valuable, so I updated my answer accordingly:

  1. codecvt_utf8_utf16 is deprecated in C++17.
  2. Also the code implies that source encoding is UTF-8 which it usually isn't.
  3. In C++20 there is a separate type std::u8string for UTF-8 because of that.

But it worked for me because I am still using an old version of C++ and it happened that my source encoding was UTF-8 .

.bashrc: Permission denied

If you can't access the file and your os is any linux distro or mac os x then either of these commands should work:

sudo nano .bashrc

chmod 777 .bashrc 

it is worthless

Disable color change of anchor tag when visited

For :hover to override :visited, and to make sure :visited is the same as the initial color, :hover must come after :visited.

So if you want to disable the color change, a:visited must come before a:hover. Like this:

a { color: gray; }
a:visited { color: orange; }
a:hover { color: red; }

To disable :visited change you would style it with non-pseudo class:

a, a:visited { color: gray; }
a:hover { color: red; }

MySQL Error: #1142 - SELECT command denied to user

You need to give privileges to the particular user by giving the command mysql> GRANT ALL PRIVILEGES . To 'username'@'localhost'; and then give FLUSH PRIVILEGES; command. Then it won't give this error.., hope it helps thank you..!

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

I haven't tested every single one of these answers but you don't need to use complicated functions to accomplish this. It's so much easier than that! My code below will work in any office VBA application (Word, Access, Excel, Outlook, etc.) and is very simple. Hope this helps:

''Dimension 2 Arrays
Dim InnerArray(1 To 3) As Variant ''The inner is for storing each column value of the current row
Dim OuterArray() As Variant ''The outer is for storing each row in
Dim i As Byte

    i = 1
    Do While i <= 5

        ''Enlarging our outer array to store a/another row
        ReDim Preserve OuterArray(1 To i)

        ''Loading the current row column data in
        InnerArray(1) = "My First Column in Row " & i
        InnerArray(2) = "My Second Column in Row " & i
        InnerArray(3) = "My Third Column in Row " & i

        ''Loading the entire row into our array
        OuterArray(i) = InnerArray

        i = i + 1
    Loop

    ''Example print out of the array to the Intermediate Window
    Debug.Print OuterArray(1)(1)
    Debug.Print OuterArray(1)(2)
    Debug.Print OuterArray(2)(1)
    Debug.Print OuterArray(2)(2)

CASE .. WHEN expression in Oracle SQL

You can only check the first character of the status. For this you use substring function.

substr(status, 1,1)

In your case past.

Sorting string array in C#

If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:

var arr = arr.OrderBy(x=>x).ToArray();

Why can't I have "public static const string S = "stuff"; in my Class?

const is similar to static we can access both varables with class name but diff is static variables can be modified and const can not.

no module named zlib

After you install the missing zlib dev package you can also use pythonbrew to uninstall and then reinstall the version of python you wanted and it seems like it picks up the new package to compile to correct abilities. This way you can keep using pythonbrew and don't have to do the compilation yourself (though it isn't that difficult)

How to work with string fields in a C struct?

You could just use an even simpler typedef:

typedef char *string;

Then, your malloc would look like a usual malloc:

string s = malloc(maxStringLength);

How to set "value" to input web element using selenium?

Use findElement instead of findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

OR

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

OR using JavascriptExecutor

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

OR

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

OR (in javascript)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

Hope it will help you :)

Can I set variables to undefined or pass undefined as an argument?

You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.

You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.

The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.

To properly test for undefined or null, use these:

if(typeof(testvar) === "undefined") { ... }

if(testvar === null) { ... }

Passing parameters to click() & bind() event in jquery?

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

Can I loop through a table variable in T-SQL?

Here's my variant. Pretty much just like all the others, but I only use one variable to manage the looping.

DECLARE
  @LoopId  int
 ,@MyData  varchar(100)

DECLARE @CheckThese TABLE
 (
   LoopId  int  not null  identity(1,1)
  ,MyData  varchar(100)  not null
 )


INSERT @CheckThese (MyData)
 select MyData from MyTable
 order by DoesItMatter

SET @LoopId = @@rowcount

WHILE @LoopId > 0
 BEGIN
    SELECT @MyData = MyData
     from @CheckThese
     where LoopId = @LoopId

    --  Do whatever

    SET @LoopId = @LoopId - 1
 END

Raj More's point is relevant--only perform loops if you have to.

Best way to get whole number part of a Decimal number

You just need to cast it, as such:

int intPart = (int)343564564.4342

If you still want to use it as a decimal in later calculations, then Math.Truncate (or possibly Math.Floor if you want a certain behaviour for negative numbers) is the function you want.

Difference between margin and padding?

Padding is space inside the border, whereas Margin is space outside the border.

What's an Aggregate Root?

If you follow a database-first approach, you aggregate root is usually the table on the 1 side of a 1-many relationship.

The most common example being a Person. Each person has many addresses, one or more pay slips, invoices, CRM entries, etc. It's not always the case, but 9/10 times it is.

We're currently working on an e-commerce platform, and we basically have two aggregate roots:

  1. Customers
  2. Sellers

Customers supply contact info, we assign transactions to them, transactions get line items, etc.

Sellers sell products, have contact people, about us pages, special offers, etc.

These are taken care of by the Customer and Seller repository respectively.

Is Google Play Store supported in avd emulators?

Yes, you can enable/use Play Store on Android Emulator(AVD): Before that you have to set up some prerequisites:

  1. Start Android SDK Manager and select Google Play Intel x86 Atom System Image (Recomended: because it will work comparatively faster) of your required android version (For Example: Android 7.1.1 or API 25)

[Note: Please keep all other thing as it is, if you are going to install it for first time] Or Install as the image below: enter image description here

  1. After download is complete Goto Tools->Manage AVDs...->Create from your Android SDK Manager

  2. enter image description here

Check you have provided following option correctly. Not sure about internal and SD card storage. You can choose different. And Target must be your downloaded android version

  1. Also check Google Play Intel Atom (x86) in CPU/ABI is provided

  2. Click OK

  3. Then Start your Android Emulator. There you will see the Android Play Store. See --- enter image description here

What is the difference between #import and #include in Objective-C?

#include + guard == #import

#include guardWiki - macro guard, header guard or file guard prevents to double include a header by a preprocessor that can slow down a build time

The next step is

.pch[About] => @import[About]

[#import in .h or .m]

How can I extract all values from a dictionary in Python?

Use values()

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}

>>> d.values()
<<< [-0.3246, -0.9185, -3985]

This action could not be completed. Try Again (-22421)

I had this problem too. My issue was that I had previously uploaded a build with the same build number.I just increased the build number in Unity and the problem was resolved. As a matter of fact I didn't realise this was the cause until I used Application Loader, which gave a much more informative error message.

How to iterate over associative arrays in Bash

Welcome to input associative array 2.0!

    clear
    echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            echo -n "(pair $(( $i+1 )))"
            read -p ' Enter key: ' k
            read -p '         Enter value: ' v
            echo " "
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array 2.0!"

Output:

Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
         Enter value: Value#1

(pair 2) Enter key: Key Two
         Enter value: Value2

(pair 3) Enter key: Key3
         Enter value: Val3

(pair 4) Enter key: Key4
         Enter value: Value4


The keys are:  Key4 Key3 Key Number 1 Key Two
The values are:  Value4 Val3 Value#1 Value2

Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2

Thanks for using input associative array 2.0!

Input associative array 1.0

(keys and values that contain spaces are not supported)

    clear
    echo "Welcome to input associative array! (written by mO extraordinaire!)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            read -p 'Enter key and value separated by a space: ' k v
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array!"

Output:

Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100

The keys are:  h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are:  80 10 100 70 60 50 40 30 90 20

Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20

Thanks for using input associative array!

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

Git push rejected "non-fast-forward"

I had a similar problem and I resolved it with: git pull origin

Programmatically Creating UILabel

Swift 3:

let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)

What's the main difference between Java SE and Java EE?

JavaSE and JavaEE both are computing platform which allows the developed software to run.

There are three main computing platform released by Sun Microsystems, which was eventually taken over by the Oracle Corporation. The computing platforms are all based on the Java programming language. These computing platforms are:

Java SE, i.e. Java Standard Edition. It is normally used for developing desktop applications. It forms the core/base API.

Java EE, i.e. Java Enterprise Edition. This was originally known as Java 2 Platform, Enterprise Edition or J2EE. The name was eventually changed to Java Platform, Enterprise Edition or Java EE in version 5. Java EE is mainly used for applications which run on servers, such as web sites.

Java ME, i.e. Java Micro Edition. It is mainly used for applications which run on resource constrained devices (small scale devices) like cell phones, most commonly games.

How to set a cell to NaN in a pandas dataframe

Most replies here need to import numpy as np

There is a built-in solution into pandas itself: pd.NA, to use like this:

df.replace('N/A', pd.NA)

Resource leak: 'in' is never closed

If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

How can I remove all objects but one from the workspace in R?

How about this?

# Removes all objects except the specified & the function itself.

rme <- function(except=NULL){
  except = ifelse(is.character(except), except, deparse(substitute(except)))
  rm(list=setdiff(ls(envir=.GlobalEnv), c(except,"rme")), envir=.GlobalEnv)
}

How to enable remote access of mysql in centos?

Bind-address XXX.XX.XX.XXX in /etc/my.cnf

comment line:

skip-networking

or

skip-external-locking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;
quit;

add firewall rule:

iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

Convert UIImage to NSData and convert back to UIImage in Swift?

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Solution 1

guard let image = UIImage(named: "img") else { return }
let jpegData = image.jpegData(compressionQuality: 1.0)
let pngData = image.pngData()

Solution 2.1

extension UIImage {
    func toData (options: NSDictionary, type: CFString) -> Data? {
        guard let cgImage = cgImage else { return nil }
        return autoreleasepool { () -> Data? in
            let data = NSMutableData()
            guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
            CGImageDestinationAddImage(imageDestination, cgImage, options)
            CGImageDestinationFinalize(imageDestination)
            return data as Data
        }
    }
}

Usage of solution 2.1

// about properties: https://developer.apple.com/documentation/imageio/1464962-cgimagedestinationaddimage
let options: NSDictionary =     [
    kCGImagePropertyOrientation: 6,
    kCGImagePropertyHasAlpha: true,
    kCGImageDestinationLossyCompressionQuality: 0.5
]

// https://developer.apple.com/documentation/mobilecoreservices/uttype/uti_image_content_types
guard let data = image.toData(options: options, type: kUTTypeJPEG) else { return }
let size = CGFloat(data.count)/1000.0/1024.0
print("\(size) mb")

Solution 2.2

extension UIImage {

    func toJpegData (compressionQuality: CGFloat, hasAlpha: Bool = true, orientation: Int = 6) -> Data? {
        guard cgImage != nil else { return nil }
        let options: NSDictionary =     [
                                            kCGImagePropertyOrientation: orientation,
                                            kCGImagePropertyHasAlpha: hasAlpha,
                                            kCGImageDestinationLossyCompressionQuality: compressionQuality
                                        ]
        return toData(options: options, type: .jpeg)
    }

    func toData (options: NSDictionary, type: ImageType) -> Data? {
        guard cgImage != nil else { return nil }
        return toData(options: options, type: type.value)
    }
    // about properties: https://developer.apple.com/documentation/imageio/1464962-cgimagedestinationaddimage
    func toData (options: NSDictionary, type: CFString) -> Data? {
        guard let cgImage = cgImage else { return nil }
        return autoreleasepool { () -> Data? in
            let data = NSMutableData()
            guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
            CGImageDestinationAddImage(imageDestination, cgImage, options)
            CGImageDestinationFinalize(imageDestination)
            return data as Data
        }
    }

    // https://developer.apple.com/documentation/mobilecoreservices/uttype/uti_image_content_types
    enum ImageType {
        case image // abstract image data
        case jpeg                       // JPEG image
        case jpeg2000                   // JPEG-2000 image
        case tiff                       // TIFF image
        case pict                       // Quickdraw PICT format
        case gif                        // GIF image
        case png                        // PNG image
        case quickTimeImage             // QuickTime image format (OSType 'qtif')
        case appleICNS                  // Apple icon data
        case bmp                        // Windows bitmap
        case ico                        // Windows icon data
        case rawImage                   // base type for raw image data (.raw)
        case scalableVectorGraphics     // SVG image
        case livePhoto                  // Live Photo

        var value: CFString {
            switch self {
            case .image: return kUTTypeImage
            case .jpeg: return kUTTypeJPEG
            case .jpeg2000: return kUTTypeJPEG2000
            case .tiff: return kUTTypeTIFF
            case .pict: return kUTTypePICT
            case .gif: return kUTTypeGIF
            case .png: return kUTTypePNG
            case .quickTimeImage: return kUTTypeQuickTimeImage
            case .appleICNS: return kUTTypeAppleICNS
            case .bmp: return kUTTypeBMP
            case .ico: return kUTTypeICO
            case .rawImage: return kUTTypeRawImage
            case .scalableVectorGraphics: return kUTTypeScalableVectorGraphics
            case .livePhoto: return kUTTypeLivePhoto
            }
        }
    }
}

Usage of solution 2.2

let compressionQuality: CGFloat = 0.4
guard let data = image.toJpegData(compressionQuality: compressionQuality) else { return }
printSize(of: data)

let options: NSDictionary =     [
                                    kCGImagePropertyHasAlpha: true,
                                    kCGImageDestinationLossyCompressionQuality: compressionQuality
                                ]
guard let data2 = image.toData(options: options, type: .png) else { return }
printSize(of: data2)

Problems

Image representing will take a lot of cpu and memory resources. So, in this case it is better to follow several rules:

- do not run jpegData(compressionQuality:) on main queue

- run only one jpegData(compressionQuality:) simultaneously

Wrong:

for i in 0...50 {
    DispatchQueue.global(qos: .utility).async {
        let quality = 0.02 * CGFloat(i)
        //let data = image.toJpegData(compressionQuality: quality)
        let data = image.jpegData(compressionQuality: quality)
        let size = CGFloat(data!.count)/1000.0/1024.0
        print("\(i), quality: \(quality), \(size.rounded()) mb")
    }
}

Right:

let serialQueue = DispatchQueue(label: "queue", qos: .utility, attributes: [], autoreleaseFrequency: .workItem, target: nil)

for i in 0...50 {
    serialQueue.async {
        let quality = 0.02 * CGFloat(i)
        //let data = image.toJpegData(compressionQuality: quality)
        let data = image.jpegData(compressionQuality: quality)
        let size = CGFloat(data!.count)/1000.0/1024.0
        print("\(i), quality: \(quality), \(size.rounded()) mb")
    }
}

Links

jQuery Scroll to Div

The script below is a generic solution that works for me. It is based on ideas pulled from this and other threads.

When a link with an href attribute beginning with "#" is clicked, it scrolls the page smoothly to the indicated div. Where only the "#" is present, it scrolls smoothly to the top of the page.

$('a[href^=#]').click(function(){
    event.preventDefault();
    var target = $(this).attr('href');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

For example, When the code above is present, clicking a link with the tag <a href="#"> scrolls to the top of the page at speed 600. Clicking a link with the tag <a href="#mydiv"> scrolls to 100px above <div id="mydiv"> at speed 600. Feel free to change these numbers.

I hope it helps!

size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

regular expression to validate datetime format (MM/DD/YYYY)

It's long, but great:

new RegExp(/(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);

Download the Android SDK components for offline install

You can download manually by parsing the XMLs that you see in Android SDK Manager log.
Currently the XMLs are addon_list and repository. These xmls can change over a course of time.

It has the location of the SDKs, you can browse to the link and download directly via browser. These files has to be placed under proper folder, example the files of google APIs has to be placed under add-ons, if you don't know where the files has to go.

Here is something to help you.
The blogpost from my blog to Install Android SDKs offline --> Offline Installation of Android SDK's

How do I make a composite key with SQL Server Management Studio?

create table my_table (
    id_part1 int not null,
    id_part2 int not null,
    primary key (id_part1, id_part2)
)

Triggering a checkbox value changed event in DataGridView

I found a combination of the first two answers gave me what I needed. I used the CurrentCellDirtyStateChanged event and inspected the EditedFormattedValue.

private void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
   DataGridView dgv = (DataGridView)sender;
   DataGridViewCell cell = dgv.CurrentCell;
   if (cell.RowIndex >= 0 && cell.ColumnIndex == 3) // My checkbox column
     {
        // If checkbox checked, copy value from col 1 to col 2
        if (dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue != null && dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue.Equals(true))
        {
           dgv.Rows[cell.RowIndex].Cells[1].Value = dgv.Rows[cell.RowIndex].Cells[2].Value;
        }
     }
}

How to run C program on Mac OS X using Terminal?

to compile c-program in macos simply follow below steps

using cd command in terminal go to your c-program location
then type the command present below
make filename
then type
./filename

What is the $$hashKey added to my JSON.stringify result

It comes with the ng-repeat directive usually. To do dom manipulation AngularJS flags objects with special id.

This is common with Angular. For example if u get object with ngResource your object will embed all the resource API and you'll see methods like $save, etc. With cookies too AngularJS will add a property __ngDebug.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

Is there a decorator to simply cache function return values?

Starting from Python 3.2 there is a built-in decorator:

@functools.lru_cache(maxsize=100, typed=False)

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

Example of an LRU cache for computing Fibonacci numbers:

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> print([fib(n) for n in range(16)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> print(fib.cache_info())
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

If you are stuck with Python 2.x, here's a list of other compatible memoization libraries:

Is there a "goto" statement in bash?

A simple searchable goto for the use of commenting out code blocks when debugging.

GOTO=false
if ${GOTO}; then
    echo "GOTO failed"
    ...
fi # End of GOTO
echo "GOTO done"

Result is-> GOTO done

Add jars to a Spark Job - spark-submit

Another approach in spark 2.1.0 is to use --conf spark.driver.userClassPathFirst=true during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars option.

Explain the concept of a stack frame in a nutshell

If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily

Let me explain how stack works:

First you have to know how functions are represented in stack :

Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.

enter image description here

Let's understand with example :

def hello(x):
    if x==1:
        return "op"
    else:
        u=1
        e=12
        s=hello(x-1)
        e+=1
        print(s)
        print(x)
        u+=1
    return e

hello(4)

Now understand parts of this program :

enter image description here

Now let's see what is stack and what are stack parts:

enter image description here

Allocation of the stack :

Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.

See this in practice:

enter image description here

Deallocation of the block:

So now whenever a function encounters return statement, it delete the current frame from the stack.

While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.

enter image description here

How to get a List<string> collection of values from app.config in WPF?

There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection (as in Richard's answer) and parsing the string yourself (as in Adam's answer).

For example, you could write the following configuration section:

public class MySection : ConfigurationSection
{
    [ConfigurationProperty("MyStrings")]
    [TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
    public CommaDelimitedStringCollection MyStrings
    {
        get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
    }
}

You could then have an app.config that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
  </configSections>
  <foo MyStrings="a,b,c,hello,world"/>
</configuration>

Finally, your code would look like this:

var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
    Console.WriteLine(s); //for example

How to enable or disable an anchor using jQuery?

Try the below lines

$("#yourbuttonid").attr("disabled", "disabled");
$("#yourbuttonid").removeAttr("href");

Coz, Even if you disable <a> tag href will work so you must remove href also.

When you want enable try below lines

$("#yourbuttonid").removeAttr("disabled");
$("#yourbuttonid").attr("href", "#nav-panel");

Difference between private, public, and protected inheritance

I found an easy answer and so thought of posting it for my future reference too.

Its from the links http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

class Base
{
public:
    int m_nPublic; // can be accessed by anybody
private:
    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    int m_nProtected; // can be accessed by Base member functions, or derived classes.
};

class Derived: public Base
{
public:
    Derived()
    {
        // Derived's access to Base members is not influenced by the type of inheritance used,
        // so the following is always true:

        m_nPublic = 1; // allowed: can access public base members from derived class
        m_nPrivate = 2; // not allowed: can not access private base members from derived class
        m_nProtected = 3; // allowed: can access protected base members from derived class
    }
};

int main()
{
    Base cBase;
    cBase.m_nPublic = 1; // allowed: can access public members from outside class
    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class
    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class
}

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

How to display a list of images in a ListView in Android?

I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):

public class ItemsList extends ListActivity {

private ItemsAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.items_list);

    this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
    setListAdapter(this.adapter);
}

private class ItemsAdapter extends ArrayAdapter<Item> {

    private Item[] items;

    public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.items_list_item, null);
        }

        Item it = items[position];
        if (it != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
            if (iv != null) {
                iv.setImageDrawable(it.getImage());
            }
        }

        return v;
    }
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    this.adapter.getItem(position).click(this.getApplicationContext());
}
}

E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView() method, that prepares view for items within list. There is also method add() on ArrayAdapter to add items to the end of the list.

R.layout.items_list is simple layout with ListView

R.layout.items_list_item is layout representing one item in list

Couldn't connect to server 127.0.0.1:27017

Sample solution Press Window+R and type services.msc to view all the services on machine Then find MongoDBServer right click it and start it. Then go to C:\Program Files\MongoDB\Server\4.2\bin and type mongo on command promt.

How make background image on newsletter in outlook?

You can use it only in body tag or in tables. Something like this:

<table width="100%" background="YOUR_IMAGE_URL" style="STYLES YOU WANT (i.e. background-repeat)">

This worked for me.

Convert Mercurial project to Git

Ok I finally worked this out. This is using TortoiseHg on Windows. If you're not using that you can do it on the command line.

  1. Install TortoiseHg
  2. Right click an empty space in explorer, and go to the TortoiseHg settings:

TortoiseHg Settings

  1. Enable hggit:

enter image description here

  1. Open a command line, enter an empty directory.

  2. git init --bare .git (If you don't use a bare repo you'll get an error like abort: git remote error: refs/heads/master failed to update

  3. cd to your Mercurial repository.

  4. hg bookmarks hg

  5. hg push c:/path/to/your/git/repo

  6. In the Git directory: git config --bool core.bare false (Don't ask me why. Something about "work trees". Git is seriously unfriendly. I swear writing the actual code is easier than using Git.)

Hopefully it will work and then you can push from that new git repo to a non-bare one.

Get the index of a certain value in an array in PHP

array_search is the way to do it.

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

From the docs:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

How to create a file in a directory in java?

String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
    File f = new File(path);
    File f1 = new File(fname);

    f.mkdirs() ;
    try {
        f1.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This should create a new file inside a directory

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How to print a linebreak in a python function?

You have your slash backwards, it should be "\n"

A Generic error occurred in GDI+ in Bitmap.Save method

for me it was a path issue when saving the image.

int count = Directory.EnumerateFiles(System.Web.HttpContext.Current.Server.MapPath("~/images/savedimages"), "*").Count();

var img = Base64ToImage(imgRaw);

string path = "images/savedimages/upImages" + (count + 1) + ".png";

img.Save(Path.Combine(System.Web.HttpContext.Current.Server.MapPath(path)));

return path;

So I fixed it by adding the following forward slash

String path = "images/savedimages....

should be

String path = "/images/savedimages....

Hope that helps anyone stuck!

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');
$db->showLog();

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

How do I read a resource file from a Java jar file?

If you use resources extensively, you might consider using Commons VFS.

Also supports: * Local Files * FTP, SFTP * HTTP and HTTPS * Temporary Files "normal FS backed) * Zip, Jar and Tar (uncompressed, tgz or tbz2) * gzip and bzip2 * resources * ram - "ramdrive" * mime

There's also JBoss VFS - but it's not much documented.

Auto height div with overflow and scroll when needed

You can do this just with flexboxes and overflow property.

Even if parent height is computed too.

Please see this answer or JSFiddle for details.

Add x and y labels to a pandas plot

For cases where you use pandas.DataFrame.hist:

plt = df.Column_A.hist(bins=10)

Note that you get an ARRAY of plots, rather than a plot. Thus to set the x label you will need to do something like this

plt[0][0].set_xlabel("column A")

Draw horizontal rule in React Native

This is in React Native (JSX) code, updated to today:

<View style = {styles.viewStyleForLine}></View>

const styles = StyleSheet.create({
viewStyleForLine: {
    borderBottomColor: "black", 
    borderBottomWidth: StyleSheet.hairlineWidth, 
    alignSelf:'stretch',
    width: "100%"
  }
})

you can use either alignSelf:'stretch' or width: "100%" both should work... and,

borderBottomWidth: StyleSheet.hairlineWidth

here StyleSheet.hairlineWidth is the thinnest, then,

borderBottomWidth: 1,

and so on to increase thickness of the line.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

In addition to @Saleh Masum solution:

If you get auto-layout errors, you can just remove the constraints from the tableViewCell.contentView

Swift 3:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let tableViewCell = super.tableView(tableView, cellForRowAt: indexPath)

    if tableViewCell.isHidden == true
    {
        tableViewCell.contentView.removeConstraints(tableViewCell.contentView.constraints)
        return 0
    }
    else{
        return super.tableView(tableView, heightForRowAt: indexPath)
    }

}

This solution depends on the flow of your app. If you want to show/hide the cell in the same view controller instance this may not be the best choice, because it removes the constraints.

Prevent WebView from displaying "web page not available"

Check out the discussion at Android WebView onReceivedError(). It's quite long, but the consensus seems to be that a) you can't stop the "web page not available" page appearing, but b) you could always load an empty page after you get an onReceivedError

Position buttons next to each other in the center of page

you can add this style to your buttons:

#button1 , #button2 {
display:inline-block;
/* additional code */
}

this aligns your buttons inline. ('side by side') :)

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the fields are empty they are not valid, so the ng-invalid and ng-invalid-required classes are added properly.

You can use the class ng-pristine to check out whether the fields have already been used or not.

How to match "anything up until this sequence of characters" in a regular expression?

If you're looking to capture everything up to "abc":

/^(.*?)abc/

Explanation:

( ) capture the expression inside the parentheses for access using $1, $2, etc.

^ match start of line

.* match anything, ? non-greedily (match the minimum number of characters required) - [1]

[1] The reason why this is needed is that otherwise, in the following string:

whatever whatever something abc something abc

by default, regexes are greedy, meaning it will match as much as possible. Therefore /^.*abc/ would match "whatever whatever something abc something ". Adding the non-greedy quantifier ? makes the regex only match "whatever whatever something ".

Differences between time complexity and space complexity?

Yes, this is definitely possible. For example, sorting n real numbers requires O(n) space, but O(n log n) time. It is true that space complexity is always a lowerbound on time complexity, as the time to initialize the space is included in the running time.

Disable clipboard prompt in Excel VBA on workbook close

If you don't want to save any changes and don't want that Save prompt while saving an Excel file using Macro then this piece of code may helpful for you

Sub Auto_Close()

     ThisWorkbook.Saved = True

End Sub

Because the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save, so no Save prompt.

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.

Pros:

  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.

Cons:

  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.

Pros

  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning

Cons

  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

Extracting Nupkg files using command line

did the same thing like this:

clear
cd PACKAGE_DIRECTORY

function Expand-ZIPFile($file, $destination)
{
    $shell = New-Object -ComObject Shell.Application
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($destination).copyhere($item)
    }
}

Dir *.nupkg | rename-item -newname {  $_.name  -replace ".nupkg",".zip"  }

Expand-ZIPFile "Package.1.0.0.zip" “DESTINATION_PATH”

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

A couple of suggestions

The ACE driver isn't installed by default. It's also a 64 bit driver, so it might be worth disabling 32bit in your app pool. I've known 64 bit drivers not work when 32 bit is enabled.(eg the ISAPI filter which connects IIS to Tomcat).

The older JET driver is 32bit. It is included by default. If you could save a copy of your database as a .mdb file then using the JET driver might be a workaround

Android camera android.hardware.Camera deprecated

Faced with the same issue, supporting older devices via the deprecated camera API and needing the new Camera2 API for both current devices and moving into the future; I ran into the same issues -- and have not found a 3rd party library that bridges the 2 APIs, likely because they are very different, I turned to basic OOP principals.

The 2 APIs are markedly different making interchanging them problematic for client objects expecting the interfaces presented in the old API. The new API has different objects with different methods, built using a different architecture. Got love for Google, but ragnabbit! that's frustrating.

So I created an interface focussing on only the camera functionality my app needs, and created a simple wrapper for both APIs that implements that interface. That way my camera activity doesn't have to care about which platform its running on...

I also set up a Singleton to manage the API(s); instancing the older API's wrapper with my interface for older Android OS devices, and the new API's wrapper class for newer devices using the new API. The singleton has typical code to get the API level and then instances the correct object.

The same interface is used by both wrapper classes, so it doesn't matter if the App runs on Jellybean or Marshmallow--as long as the interface provides my app with what it needs from either Camera API, using the same method signatures; the camera runs in the App the same way for both newer and older versions of Android.

The Singleton can also do some related things not tied to the APIs--like detecting that there is indeed a camera on the device, and saving to the media library.

I hope the idea helps you out.

Save image from url with curl PHP

This is easiest implement.

function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen($url, 'rb');
    if ($file) {
        $newf = fopen($newfname, 'wb');
        if ($newf) {
            while (!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}

REST API error return good practices

Please stick to the semantics of protocol. Use 2xx for successful responses and 4xx , 5xx for error responses - be it your business exceptions or other. Had using 2xx for any response been the intended use case in the protocol, they would not have other status codes in the first place.

How to open an external file from HTML

Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='http://server/directory/file.xlsx'

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

You're probably setting a value for a key in the alertView, which is not allowed. The key is in this case LoginScreen. I don't see any call to setValue(), so I assume it's somewhere else in the code.

How to get current html page title with javascript

try like this

$('title').text();

How to remove ASP.Net MVC Default HTTP Headers?

X-Powered-By is a custom header in IIS. Since IIS 7, you can remove it by adding the following to your web.config:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

This header can also be modified to your needs, for more information refer to http://www.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders


Add this to web.config to get rid of the X-AspNet-Version header:

<system.web>
  <httpRuntime enableVersionHeader="false" />
</system.web>

Finally, to remove X-AspNetMvc-Version, edit Global.asax.cs and add the following in the Application_Start event:

protected void Application_Start()
{
    MvcHandler.DisableMvcResponseHeader = true;
}

You can also modify headers at runtime via the Application_PreSendRequestHeaders event in Global.asax.cs. This is useful if your header values are dynamic:

protected void Application_PreSendRequestHeaders(object source, EventArgs e)
{
      Response.Headers.Remove("foo");
      Response.Headers.Add("bar", "quux");
}

Most Useful Attributes

I have been using the [DataObjectMethod] lately. It describes the method so you can use your class with the ObjectDataSource ( or other controls).

[DataObjectMethod(DataObjectMethodType.Select)] 
[DataObjectMethod(DataObjectMethodType.Delete)] 
[DataObjectMethod(DataObjectMethodType.Update)] 
[DataObjectMethod(DataObjectMethodType.Insert)] 

More info

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I had the same problem into my Spring Boot+Spring Data project when invoking to a @RepositoryRestResource.

The problem is the MIME type returned; which is application/hal+json. Adding it to the server.compression.mime-types property solved this problem for me.

Hope this helps to someone else!

Cleanest way to write retry logic?

Update after 6 years: now I consider that the approach below is pretty bad. To create a retry logic we should consider to use a library like Polly.


My async implementation of the retry method:

public static async Task<T> DoAsync<T>(Func<dynamic> action, TimeSpan retryInterval, int retryCount = 3)
    {
        var exceptions = new List<Exception>();

        for (int retry = 0; retry < retryCount; retry++)
        {
            try
            {
                return await action().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }

            await Task.Delay(retryInterval).ConfigureAwait(false);
        }
        throw new AggregateException(exceptions);
    }

Key points: I used .ConfigureAwait(false); and Func<dynamic> instead Func<T>

Difference between <context:annotation-config> and <context:component-scan>

As a complementary, you can use @ComponentScan to use <context:component-scan> in annotation way.

It's also described at spring.io

Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's element.

One thing to note, if you're using Spring Boot, the @Configuration and @ComponentScan can be implied by using @SpringBootApplication annotation.

How can I format decimal property to currency?

Try this;

  string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);

It will convert 123423.083234 to $1,23,423 format.

How to get the total number of rows of a GROUP BY query?

It's a little memory-inefficient but if you're using the data anyway, I use this frequently:

$rows = $q->fetchAll();
$num_rows = count($rows);

splitting a number into the integer and decimal parts

We can use a not famous built-in function; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338

Python Image Library fails with message "decoder JPEG not available" - PIL

On Mac OS X Mavericks (10.9.3), I solved this by doing the follows:

Install libjpeg by brew (package management system)

brew install libjpeg

reinstall pillow (I use pillow instead of PIL)

pip install -I pillow

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

Simple proof that GUID is not unique

Aren't you all missing a major point?

I thought GUIDs were generated using two things which make the chances of them being Globally unique quite high. One is they are seeded with the MAC address of the machine that you are on and two they use the time that they were generated plus a random number.

So unless you run it on the actual machine and run all you guesses within the smallest amount of time that the machine uses to represent a time in the GUID you will never generate the same number no matter how many guesses you take using the system call.

I guess if you know the actual way a GUID is made would actually shorten the time to guess quite substantially.

Tony

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

How to set a bitmap from resource

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

How can I compare two lists in python and return matches

If you want a boolean value:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(b) == set(a)  & set(b) and set(a) == set(a) & set(b)
False
>>> a = [3,1,2]
>>> b = [1,2,3]
>>> set(b) == set(a)  & set(b) and set(a) == set(a) & set(b)
True

Counting the number of elements with the values of x in a vector

There is also count(numbers) from plyr package. Much more convenient than table in my opinion.

How can I concatenate strings in VBA?

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"

What does "pending" mean for request in Chrome Developer Window?

The fix, for me, was to add the following to the top of the php file which was being requested.

header("Cache-Control: no-cache,no-store");

What exactly is an instance in Java?

I think that Object = Instance. Reference is a "link" to an Object.

Car c = new Car();

variable c stores a reference to an object of type Car.

Project Links do not work on Wamp Server

How To Fix The Broken Icon Links (blank.gif, text.gif, etc.)

Unfortunately as previously mentioned, simply adding a virtual host to your project doesn't fix the broken icon links.

The Problem:

WAMP/Apache does not change the directory reference for the icons to your respective installation directory. It is statically set to "c:/Apache24/icons" and 99.9% of users Apache installation does not reside here. Especially with WAMP.

The Fix:

  1. Find your Apache icons directory! Typically it will be located here: "c:/wamp/bin/apache/apache2.4.9/icons". However your mileage may vary depending on your installation and if your Apache version is different, then your path will be different as well.\

  2. Open up httpd-autoindex.conf in your favorite editor. This file can usually be found here: "C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf". Again, if your Apache version is different, then so will this path.

  3. Find this definition (usually located near the top of the file):

    Alias /icons/ "c:/Apache24/icons/"
    
    <Directory "c:/Apache24/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
    </Directory>
    
  4. Replace the "c:/Apache24/icons/" directories with your own. IMPORTANT You MUST have a trailing forward slash in the first directory reference. The second directory reference must have no trailing slash. Your results should look similar to this. Again, your directory may differ:

    Alias /icons/ "c:/wamp/bin/apache/apache2.4.9/icons/"
    
    <Directory "c:/wamp/bin/apache/apache2.4.9/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
    </Directory>
    
  5. Restart your Apache server and enjoy your cool icons!

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

CSS: how do I create a gap between rows in a table?

All you need:

table {
    border-collapse: separate;
    border-spacing: 0 1em;
}

That assumes you want a 1em vertical gap, and no horizontal gap. If you're doing this, you should probably also look at controlling your line-height.

Sort of weird that some of the answers people gave involve border-collapse: collapse, whose effect is the exact opposite of what the question asked for.

Visual studio code terminal, how to run a command with administrator rights?

Step 1: Restart VS Code as an adminstrator

(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)

Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted

Set an empty DateTime variable

The method you used (AddWithValue) doesn't convert null values to database nulls. You should use DBNull.Value instead:

myCommand.Parameters.AddWithValue(
    "@SurgeryDate", 
    someDate == null ? DBNull.Value : (object)someDate
);

This will pass the someDate value if it is not null, or DBNull.Value otherwise. In this case correct value will be passed to the database.

find path of current folder - cmd

2015-03-30: Edited - Missing information has been added

To retrieve the current directory you can use the dynamic %cd% variable that holds the current active directory

set "curpath=%cd%"

This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with

for %%a in ("%cd%\") do set "curpath=%%~fa"

Or you can use another dynamic variable: %__CD__% that will return the current active directory with an ending backslash.

Also, remember the %cd% variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory

for %%a in (".\") do set "curpath=%%~fa"

Up to windows XP, the %__CD__% variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__% is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set command).

BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.

set "curpath=%~dp0"

It will return the directory where the batch file is stored, with an ending backslash.

BUT this will fail if in the batch file the shift command has been used

shift
echo %~dp0

As the arguments to the batch file has been shifted, the %0 reference to the current batch file is lost.

To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1 to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine

@echo off
    setlocal enableextensions

    rem Destroy batch file reference
    shift
    echo batch folder is "%~dp0"

    rem Call the subroutine to get the batch folder 
    call :getBatchFolder batchFolder
    echo batch folder is "%batchFolder%"

    exit /b

:getBatchFolder returnVar
    set "%~1=%~dp0" & exit /b

This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

How do I check if a variable is of a certain type (compare two types) in C?

From linux/typecheck.h:

/*
 * Check at compile time that something is of a particular type.
 * Always evaluates to 1 so you may use it easily in comparisons.
 */
#define typecheck(type,x) \
({  type __dummy; \
    typeof(x) __dummy2; \
    (void)(&__dummy == &__dummy2); \
    1; \
})

Here you can find explanation which statements from standard and which GNU extensions above code uses.

(Maybe a bit not in scope of the question, since question is not about failure on type mismatch, but anyway, leaving it here).

How to keep Docker container running after starting services?

Motivation:

There is nothing wrong in running multiple processes inside of a docker container. If one likes to use docker as a light weight VM - so be it. Others like to split their applications into micro services. Me thinks: A LAMP stack in one container? Just great.

The answer:

Stick with a good base image like the phusion base image. There may be others. Please comment.

And this is yet just another plead for supervisor. Because the phusion base image is providing supervisor besides of some other things like cron and locale setup. Stuff you like to have setup when running such a light weight VM. For what it's worth it also provides ssh connections into the container.

The phusion image itself will just start and keep running if you issue this basic docker run statement:

moin@stretchDEV:~$ docker run -d phusion/baseimage
521e8a12f6ff844fb142d0e2587ed33cdc82b70aa64cce07ed6c0226d857b367
moin@stretchDEV:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS
521e8a12f6ff        phusion/baseimage   "/sbin/my_init"     12 seconds ago      Up 11 seconds

Or dead simple:

If a base image is not for you... For the quick CMD to keep it running I would suppose something like this for bash:

CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"

Or this for busybox:

CMD exec /bin/sh -c "trap : TERM INT; (while true; do sleep 1000; done) & wait"

This is nice, because it will exit immediately on a docker stop. Just plain sleep or cat will take a few seconds before the container exits.

Adding rows to tbody of a table using jQuery

With Lodash you can create a template and you can do that following way:

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12">
                <table id="tblEntAttributes" class="table">
                    <tbody>
                        <tr>
                            <td>
                                chkboxId
                            </td>
                            <td>
                               chkboxValue
                            </td>
                            <td>
                                displayName
                            </td>
                            <td>
                               logicalName
                            </td>
                            <td>
                                dataType
                            </td>
                        </tr>
                    </tbody>
                </table>
                <button class="btn btn-primary" id="test">appendTo</button>
            </div>
        </div>
     </div>

And here goes the javascript:

        var count = 1;
        window.addEventListener('load', function () {
            var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>");
            document.getElementById('test').addEventListener('click', function (e) {
                var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
                var tableRowData = compiledRow(ajaxData);
                $("#tblEntAttributes tbody").append(tableRowData);
                count++;
            });
        });

Here it is in jsbin

Angular 4 HttpClient Query Parameters

joshrathke is right.

In angular.io docs is written that URLSearchParams from @angular/http is deprecated. Instead you should use HttpParams from @angular/common/http. The code is quite similiar and identical to what joshrathke have written. For multiple parameters that are saved for instance in a object like

{
  firstParam: value1,
  secondParam, value2
}

you could also do

for(let property in objectStoresParams) {
  if(objectStoresParams.hasOwnProperty(property) {
    params = params.append(property, objectStoresParams[property]);
  }
}

If you need inherited properties then remove the hasOwnProperty accordingly.

Count items in a folder with PowerShell

You can also use an alias

(ls).Count

System.MissingMethodException: Method not found?

This may have been mentioned already, but for me the problem was that the project was referencing 2 nuget packages, and each of those nuget packages referenced a different version of another nuget package.

So:

Project -> Nuget A -> Nuget X 1.1

Project -> Nuget B -> Nuget X 1.2

Both versions of Nuget X had the same extension method that was being called from Project.

When I updated both Nuget A & B to versions that referenced the same version of Nuget X, the error went away.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I had the same problem, when suddenly any test didn't appeared on Test Explorer window. I has the updated version of "NUnit3TestAdapter"

and after lots of searches and efforts, I found that I need set the following values in project properties: [In Solution Explorer window: right click on Project > Properties] Under Build tab, set Platform=x64, and set Platform target=x86 or Any CPU Build the project and all tests will be appear on Test Explorer window.

Important note: I came to a solution after seeing the next msg in the output window:

"Test run will use DLL(s) built for framework Framework45 and platform X86. Following DLL(s) will not be part of run: AutomationTests.dll is built for Framework Framework45 and Platform X64."