Programs & Examples On #Cas

Central Authentication Service, a trusted system to authenticate a user or Code Access Security, a Microsoft .NET system for limiting actions that untrusted code can perform.

Uri not Absolute exception getting while calling Restful Webservice

The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

How to allow http content within an iframe on a https site

Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

how to calculate percentage in python

marks = raw_input('Enter your Obtain marks:')
outof = raw_input('Enter Out of marks:')
marks = int(marks)
outof = int(outof)
per = marks*100/outof
print 'Your Percentage is:'+str(per)

Note : raw_input() function is used to take input from console and its return string formatted value. So we need to convert into integer otherwise it give error of conversion.

How do I use reflection to invoke a private method?

Are you absolutely sure this can't be done through inheritance? Reflection is the very last thing you should look at when solving a problem, it makes refactoring, understanding your code, and any automated analysis more difficult.

It looks like you should just have a DrawItem1, DrawItem2, etc class that override your dynMethod.

How to activate a specific worksheet in Excel?

Would the following Macro help you?

Sub activateSheet(sheetname As String)
'activates sheet of specific name
    Worksheets(sheetname).Activate
End Sub

Basically you want to make use of the .Activate function. Or you can use the .Select function like so:

Sub activateSheet(sheetname As String)
'selects sheet of specific name
    Sheets(sheetname).Select
End Sub

If two cells match, return value from third

I think what you want is something like:

=INDEX(B:B,MATCH(C2,A:A,0))  

I should mention that MATCH checks the position at which the value can be found within A:A (given the 0, or FALSE, parameter, it looks only for an exact match and given its nature, only the first instance found) then INDEX returns the value at that position within B:B.

Why do I always get the same sequence of random numbers with rand()?

Seeding the rand()

void srand (unsigned int seed)

This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.

To produce a different pseudo-random series each time your program is run, do srand (time (0))

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

Click event doesn't work on dynamically generated elements

Use the .on() method with delegated events

$('#staticParent').on('click', '.dynamicElement', function() {
    // Do something on an existent or future .dynamicElement
});

The .on() method allows you to delegate any desired event handler to:
current elements or future elements added to the DOM at a later time.

P.S: Don't use .live()! From jQuery 1.7+ the .live() method is deprecated.

Login to website, via C#

Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest and HttpWebResponse otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie' didn't return anything despite other websites does.

So I think this where we need to store cookies for next Requests, so I added this.


To the "POSTing to the login form" code block :

var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;


And To the "GETting the page behind the login form" :

HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);


Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest and WebResponse with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET

How to count check-boxes using jQuery?

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

alert($(":checkbox:checked").length);

CSS to set A4 paper size

https://github.com/cognitom/paper-css seems to solve all my needs.

Paper CSS for happy printing

Front-end printing solution - previewable and live-reloadable!

Is there an eval() function in Java?

The following resolved the issue:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "4*5";
System.out.println(engine.eval(str));

Github: error cloning my private repository

If you are using the Git command shell that installs with the GitHub for Windows app then this and various other problems can show after an update. Just start the Git Hub windows app and shut it down again. The shell will then work OK again. The problem is that the update does not complete until the windows application is run. Just using the shell on its does not trigger the update to complete.

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

C/C++ macro string concatenation

If they're both strings you can just do:

#define STR3 STR1 STR2

This then expands to:

#define STR3 "s" "1"

and in the C language, separating two strings with space as in "s" "1" is exactly equivalent to having a single string "s1".

Checking images for similarity with OpenCV

If for matching identical images ( same size/orientation )

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Source

How to find difference between two Joda-Time DateTimes in minutes

DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();

In practice I think this will always give the same result as the answer based on Duration. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years().

In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.

What is /dev/null 2>&1?

As described by the others, writing to /dev/null eliminates the output of a program. Usually cron sends an email for every output from the process started with a cronjob. So by writing the output to /dev/null you prevent being spammed if you have specified your adress in cron.

How to display Toast in Android?

Here's another one:

refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),getText(R.string.refresh_btn_pushed),Toast.LENGTH_LONG).show();
            }
        });

Where Toast is:

Toast.makeText(getBaseContext(),getText(R.string.refresh_btn_pushed),Toast.LENGTH_LONG).show();

& strings.xml:

<string name="refresh_btn_pushed">"Refresh was Clicked..."</string>

SQL Server 2008 can't login with newly created user

Login to Server as Admin

Go To Security > Logins > New Login

Step 1:

Login Name : SomeName

Step 2:

Select  SQL Server / Windows Authentication.

More Info on, what is the differences between sql server authentication and windows authentication..?

Choose Default DB and Language of your choice

Click OK

Try to connect with the New User Credentials, It will prompt you to change the password. Change and login

OR

Try with query :

USE [master] -- Default DB
GO

CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO

--123456 is the Password And Username is Login User 
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO

Using Server.MapPath in external C# Classes in ASP.NET

Whether you're running within the context of ASP.NET or not, you should be able to use HostingEnvironment.ApplicationPhysicalPath

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

Very simple C# CSV reader

Here's a simple function I made. It accepts a string CSV line and returns an array of fields:

It works well with Excel generated CSV files, and many other variations.

    public static string[] ParseCsvRow(string r)
    {

        string[] c;
        string t;
        List<string> resp = new List<string>();
        bool cont = false;
        string cs = "";

        c = r.Split(new char[] { ',' }, StringSplitOptions.None);

        foreach (string y in c)
        {
            string x = y;


            if (cont)
            {
                // End of field
                if (x.EndsWith("\""))
                {
                    cs += "," + x.Substring(0, x.Length - 1);
                    resp.Add(cs);
                    cs = "";
                    cont = false;
                    continue;

                }
                else
                {
                    // Field still not ended
                    cs += "," + x;
                    continue;
                }
            }

            // Fully encapsulated with no comma within
            if (x.StartsWith("\"") && x.EndsWith("\""))
            {
                if ((x.EndsWith("\"\"") && !x.EndsWith("\"\"\"")) && x != "\"\"")
                {
                    cont = true;
                    cs = x;
                    continue;
                }

                resp.Add(x.Substring(1, x.Length - 2));
                continue;
            }

            // Start of encapsulation but comma has split it into at least next field
            if (x.StartsWith("\"") && !x.EndsWith("\""))
            {
                cont = true;
                cs += x.Substring(1);
                continue;
            }

            // Non encapsulated complete field
            resp.Add(x);

        }

        return resp.ToArray();

    }

How to install node.js as windows service?

From this blog

Next up, I wanted to host node as a service, just like IIS. This way it’d start up with my machine, run in the background, restart automatically if it crashes and so forth.

This is where nssm, the non-sucking service manager, enters the picture. This tool lets you host a normal .exe as a Windows service.

Here are the commands I used to setup an instance of the your node application as a service, open your cmd like administrator and type following commands:

nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
net start service_name

phpinfo() - is there an easy way for seeing it?

If you have php installed on your local machine try:

$ php -a
Interactive shell

php > phpinfo();

What is the correct way to write HTML using Javascript?

The document.write method is very limited. You can only use it before the page has finished loading. You can't use it to update the contents of a loaded page.

What you probably want is innerHTML.

Why does my sorting loop seem to append an element where it shouldn't?

Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.

Another issue is with your methodology. Use the Arrays.sort() method:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);

Output:

 Hello
 This
Example
Is
Sorting

Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.

Which characters need to be escaped when using Bash?

There are two easy and safe rules which work not only in sh but also bash.

1. Put the whole string in single quotes

This works for all chars except single quote itself. To escape the single quote, close the quoting before it, insert the single quote, and re-open the quoting.

'I'\''m a s@fe $tring which ends in newline
'

sed command: sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"

2. Escape every char with a backslash

This works for all characters except newline. For newline characters use single or double quotes. Empty strings must still be handled - replace with ""

\I\'\m\ \a\ \s\@\f\e\ \$\t\r\i\n\g\ \w\h\i\c\h\ \e\n\d\s\ \i\n\ \n\e\w\l\i\n\e"
"

sed command: sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.

2b. More readable version of 2

There's an easy safe set of characters, like [a-zA-Z0-9,._+:@%/-], which can be left unescaped to keep it more readable

I\'m\ a\ s@fe\ \$tring\ which\ ends\ in\ newline"
"

sed command: LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.


Note that in a sed program, one can't know whether the last line of input ends with a newline byte (except when it's empty). That's why both above sed commands assume it does not. You can add a quoted newline manually.

Note that shell variables are only defined for text in the POSIX sense. Processing binary data is not defined. For the implementations that matter, binary works with the exception of NUL bytes (because variables are implemented with C strings, and meant to be used as C strings, namely program arguments), but you should switch to a "binary" locale such as latin1.


(You can easily validate the rules by reading the POSIX spec for sh. For bash, check the reference manual linked by @AustinPhillips)

Hard reset of a single file

Reference to HEAD is not necessary.

git checkout -- file.js is sufficient

Get a Windows Forms control by name in C#

A simple solution would be to iterate through the Controls list in a foreach loop. Something like this:

foreach (Control child in Controls)
{
    // Code that executes for each control.
}

So now you have your iterator, child, which is of type Control. Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:

child.MouseDown += new MouseEventHandler(dragDown);

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

Javascript/Jquery to change class onclick?

I think you mean that you want want an onclick event that changes a class.

Here is the answer if someone visits this question and is literally looking to assign a class and it's onclick with JQUERY.

It is somewhat counter-intuitive, but if you want to change the onclick event by changing the class you need to declare the onclick event to apply to elements of a parent object.

HTML

<div id="containerid">
     Text <a class="myClass" href="#" />info</a>
     Other Text <div class="myClass">other info</div>
</div>
<div id="showhide" class="meta-info">hide info</div>

Document Ready

$(function() {
     $("#containerid").on("click",".myclass",function(e){ /*do stuff*/ }
     $("#containerid").on("click",".mynewclass",function(e){ /*do different stuff*/ }
     $("#showhide").click(function() {changeclass()}
});

Slight Tweak to Your Javascript

<script>
function changeclass() {
        $(".myClass,.myNewClass").toggleClass('myNewClass').toggleClass('myClass');
} 
</script>

If you can't reliably identify a parent object you can do something like this.

$(function() {
     $(document).on("click",".myclass",function(e){}
     $(document).on("click",".mynewclass",function(e){}
});

If you just want to hide the items you might find it simpler to use .hide() and .show().

How to count duplicate rows in pandas dataframe?

If you like to count duplicates on particular column(s):

len(df['one'])-len(df['one'].drop_duplicates())

If you want to count duplicates on entire dataframe:

len(df)-len(df.drop_duplicates())

Or simply you can use DataFrame.duplicated(subset=None, keep='first'):

df.duplicated(subset='one', keep='first').sum()

where

subset : column label or sequence of labels(by default use all of the columns)

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Mark duplicates as True except for the first occurrence.
  • last : Mark duplicates as True except for the last occurrence.
  • False : Mark all duplicates as True.

Setting a WebRequest's body data

With HttpWebRequest.GetRequestStream

Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

What Language is Used To Develop Using Unity

All development is done using your choice of C#, Boo, or a dialect of JavaScript.

  • C# needs no explanation :)
  • Boo is a CLI language with very similar syntax to Python; it is, however, statically typed and has a few other differences. It's not "really" Python; it just looks similar.
  • The version of JavaScript used by Unity is also a CLI language, and is compiled. Newcomers often assume JS isn't as good as the other three, but it's compiled and just as fast and functional.

Most of the example code in the documentation is in JavaScript; if you poke around the official forums and wiki you'll see a pretty even mix of C# and Javascript. Very few people seem to use Boo, but it's just as good; pick the language you already know or are the happiest learning.

Unity takes your C#/JS/Boo code and compiles it to run on iOS, Android, PC, Mac, XBox, PS3, Wii, or web plugin. Depending on the platform that might end up being Objective C or something else, but that's completely transparent to you. There's really no benefit to knowing Objective C; you can't program in it.


Update 2019/31/01

Starting from Unity 2017.2 "UnityScript" (Unity's version of JavaScript, but not identical to) took its first step towards complete deprecation by removing the option to add a "JavaScript" file from the UI. Though JS files could still be used, support for it will completely be dropped in later versions.

This also means that Boo will become unusable as its compiler is actually built as a layer on top of UnityScript and will thus be removed as well.

This means that in the future only C# will have native support.

unity has released a full article on the deprecation of UnityScript and Boo back in August 2017.

How to read text file in JavaScript

Javascript doesn't have access to the user's filesystem for security reasons. FileReader is only for files manually selected by the user.

SQL Server replace, remove all after certain character

Use LEFT combined with CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

I get the following results:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

How to store token in Local or Session Storage in Angular 2?

Simple example:

var userID = data.id;

localStorage.setItem('userID',JSON.stringify(userID));

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.

For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.

Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.

Fatal error: Class 'Illuminate\Foundation\Application' not found

I had accidentally commented out:

require __DIR__.'/../bootstrap/autoload.php';

in /public/index.php

When pasting in some debugging statements.

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

In Unix, how do you remove everything in the current directory and below it?

rm  -rf * 

Don't do it! It's dangerous! MAKE SURE YOU'RE IN THE RIGHT DIRECTORY!

Can I Set "android:layout_below" at Runtime Programmatically?

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

Auto-increment primary key in SQL tables

Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):

CREATE TABLE "dbo"."TableName"
(
   id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
   name varchar(20),
);

the insert statement should list all columns except the id column (it will be filled with autoincremented value):

INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');

and the result of

SELECT id, name FROM "dbo"."TableName";

will be

id    name
--------------------------
1     alpha
2     beta

How to Get Element By Class in JavaScript?

I think something like:

function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
    if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
        elems[i].innerHTML = content;
    }
}
}

would work

Add ... if string is too long PHP

This will return a given string with ellipsis based on WORD count instead of characters:

<?php
/**
*    Return an elipsis given a string and a number of words
*/
function elipsis ($text, $words = 30) {
    // Check if string has more than X words
    if (str_word_count($text) > $words) {

        // Extract first X words from string
        preg_match("/(?:[^\s,\.;\?\!]+(?:[\s,\.;\?\!]+|$)){0,$words}/", $text, $matches);
        $text = trim($matches[0]);

        // Let's check if it ends in a comma or a dot.
        if (substr($text, -1) == ',') {
            // If it's a comma, let's remove it and add a ellipsis
            $text = rtrim($text, ',');
            $text .= '...';
        } else if (substr($text, -1) == '.') {
            // If it's a dot, let's remove it and add a ellipsis (optional)
            $text = rtrim($text, '.');
            $text .= '...';
        } else {
            // Doesn't end in dot or comma, just adding ellipsis here
            $text .= '...';
        }
    }
    // Returns "ellipsed" text, or just the string, if it's less than X words wide.
    return $text;
}

$description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!';

echo elipsis($description, 30);
?>

Deleting all records in a database table

If you mean delete every instance of all models, I would use

ActiveRecord::Base.connection.tables.map(&:classify)
  .map{|name| name.constantize if Object.const_defined?(name)}
  .compact.each(&:delete_all)

How to prevent a double-click using jQuery?

This is my first ever post & I'm very inexperienced so please go easy on me, but I feel I've got a valid contribution that may be helpful to someone...

Sometimes you need a very big time window between repeat clicks (eg a mailto link where it takes a couple of secs for the email app to open and you don't want it re-triggered), yet you don't want to slow the user down elsewhere. My solution is to use class names for the links depending on event type, while retaining double-click functionality elsewhere...

var controlspeed = 0;

$(document).on('click','a',function (event) {
    eventtype = this.className;
    controlspeed ++;
    if (eventtype == "eg-class01") {
        speedlimit = 3000;
    } else if (eventtype == "eg-class02") { 
        speedlimit = 500; 
    } else { 
        speedlimit = 0; 
    } 
    setTimeout(function() {
        controlspeed = 0;
    },speedlimit);
    if (controlspeed > 1) {
        event.preventDefault();
        return;
    } else {

        (usual onclick code goes here)

    }
});

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

It sounds like you have a memory leak. The problem isn't handling many images, it's that your images aren't getting deallocated when your activity is destroyed.

It's difficult to say why this is without looking at your code. However, this article has some tips that might help:

http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

In particular, using static variables is likely to make things worse, not better. You might need to add code that removes callbacks when your application redraws -- but again, there's not enough information here to say for sure.

What is the "assert" function?

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

19.3 Assertions

1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.

2 The contents are the same as the Standard C library header <assert.h>.

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

7.2 Diagnostics <assert.h>

1 The header <assert.h> defines the assert macro and refers to another macro, NDEBUG which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as

 #define assert(ignore) ((void)0)

The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.

2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

7.2.1 Program diagnostics

7.2.1.1 The assert macro

Synopsis

1.

#include <assert.h>
void assert(scalar expression);

Description

2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.

Returns

3 The assert macro returns no value.

Flask ImportError: No Module Named Flask

my answer just for any users that use Visual Studio Flesk Web project :

Just Right Click on "Python Environment" and Click to "Add Environment"

How to compare two strings are equal in value, what is the best method?

Not forgetting

.equalsIgnoreCase(String)

if you're not worried about that sort of thing...

How to show the Project Explorer window in Eclipse

Try to close Eclipse IDE and reopen it and

click on window->show view->project explorer

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, this answer is correct only to versions preceding 1.1.5. For 1.1.5 and later, see the currently accepted answer.

Before Angular 1.1.5:

The form of a ternary in angularjs is:

((condition) && (answer if true) || (answer if false))

An example would be:

<ul class="nav">
    <li>
        <a   href="#/page1" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Goals</a>
    </li>
    <li>
        <a   href="#/page2" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Groups</a>
    </li>
</ul>

or:

 <li  ng-disabled="currentPage == 0" ng-click="currentPage=0"  class="{{(currentPage == 0) && 'disabled' || ''}}"><a> << </a></li>

Difference between wait and sleep

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

synchronized(LOCK) {   
   Thread.sleep(1000); // LOCK is held
}

synchronized(LOCK) {   
   LOCK.wait(); // LOCK is not held
}

Let categorize all above points :

Call on:

  • wait(): Call on an object; current thread must synchronize on the lock object.
  • sleep(): Call on a Thread; always currently executing thread.

Synchronized:

  • wait(): when synchronized multiple threads access same Object one by one.
  • sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.

Hold lock:

  • wait(): release the lock for other objects to have chance to execute.
  • sleep(): keep lock for at least t times if timeout specified or somebody interrupt.

Wake-up condition:

  • wait(): until call notify(), notifyAll() from object
  • sleep(): until at least time expire or call interrupt().

Usage:

  • sleep(): for time-synchronization and;
  • wait(): for multi-thread-synchronization.

Ref:diff sleep and wait

How to set editor theme in IntelliJ Idea

It's simple please follow the below step.

  1. On IntelliJ press 'Ctrl Alt + S' [ press ctrl alt and S together], this will open 'Setting popup'
  2. In Search panel 'left top search 'Theme' keyword.
  3. In left panel itself you can see 'Appearance', click on this
  4. Right side panel you can see Theme: and drop down with following option

    • Dracula
    • IntelliJ
    • Windows

just select which ever you want and click on apply and Ok.

I hope this may work for you..enter image description here

I misunderstood question. Sorry. for editor - File->Settings->Editor->Colors &Fonts and choose your scheme.... :)

Format output string, right alignment

Try this approach using the newer str.format syntax:

line_new = '{:>12}  {:>12}  {:>12}'.format(word[0], word[1], word[2])

And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])

How to add a bot to a Telegram Group?

Another way :

change BOT_USER_NAME before use

https://telegram.me/BOT_USER_NAME?startgroup=true

How do I use raw_input in Python 3

A reliable way to address this is

from six.moves import input

six is a module which patches over many of the 2/3 common code base pain points.

How do Python functions handle the types of the parameters that you pass in?

Python is strongly typed because every object has a type, every object knows its type, it's impossible to accidentally or deliberately use an object of a type "as if" it was an object of a different type, and all elementary operations on the object are delegated to its type.

This has nothing to do with names. A name in Python doesn't "have a type": if and when a name's defined, the name refers to an object, and the object does have a type (but that doesn't in fact force a type on the name: a name is a name).

A name in Python can perfectly well refer to different objects at different times (as in most programming languages, though not all) -- and there is no constraint on the name such that, if it has once referred to an object of type X, it's then forevermore constrained to refer only to other objects of type X. Constraints on names are not part of the concept of "strong typing", though some enthusiasts of static typing (where names do get constrained, and in a static, AKA compile-time, fashion, too) do misuse the term this way.

Google.com and clients1.google.com/generate_204

with the massive remit by google to stop both spam and the scraping of their search database, I believe that this is part of the effort to track bots etc.

some simple anti bot pseudo could go like this.

On GET (google.*) Save RemoteEndPoint
{
    If RemoteEndPoint GETs (clients1.google.com/generate_204) Then
        Set botAlert_stage1 = false;
    Else
        Set botAlert_stage1 = true;
    End If
}

I also believe that the latest google frontpage 'theme' is also a new tool to help with the anti spam/bot activity.

** NOTE ** ipv6.google.com also includes this measure.

Just my unfounded unproofed two 2p.

How to insert blank lines in PDF?

You can add Blank Line throw PdfContentByte class in itextPdf. As shown below:

package com.pdf.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class Ranvijay {

    public static final String RESULT = "d:/printReport.pdf";

    public void createPdf(String filename) throws Exception {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        document.open();

        Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
        Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
        PdfPTable tabletmp = new PdfPTable(1);
        tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tabletmp.setWidthPercentage(100);
        PdfPTable table = new PdfPTable(2);
        float[] colWidths = { 45, 55 };
        table.setWidths(colWidths);
        String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
        Image image2 = Image.getInstance(new URL(imageUrl));
        image2.setWidthPercentage(60);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.NO_BORDER);
        cell.addElement(image2);
        table.addCell(cell);
        String email = "[email protected]";
        String collectionDate = "09/09/09";
        Chunk chunk1 = new Chunk("Date: ", normal);
        Phrase ph1 = new Phrase(chunk1);

        Chunk chunk2 = new Chunk(collectionDate, bold);
        Phrase ph2 = new Phrase(chunk2);

        Chunk chunk3 = new Chunk("\nEmail: ", normal);
        Phrase ph3 = new Phrase(chunk3);

        Chunk chunk4 = new Chunk(email, bold);
        Phrase ph4 = new Phrase(chunk4);

        Paragraph ph = new Paragraph();
        ph.add(ph1);
        ph.add(ph2);
        ph.add(ph3);
        ph.add(ph4);

        table.addCell(ph);
        tabletmp.addCell(table);
        PdfContentByte canvas = writer.getDirectContent();
        canvas.saveState();
        canvas.setLineWidth((float) 10 / 10);
        canvas.moveTo(40, 806 - (5 * 10));
        canvas.lineTo(555, 806 - (5 * 10));
        canvas.stroke();
        document.add(tabletmp);
        canvas.restoreState();
        PdfPTable tabletmp1 = new PdfPTable(1);
        tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tabletmp1.setWidthPercentage(100);

        document.add(tabletmp1);

        document.close();
    }

    /**
     * Main method.
     * 
     * @param args
     *            no arguments needed
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws Exception {
        new Ranvijay().createPdf(RESULT);
        System.out.println("Done Please check........");
    }

}

How to change text transparency in HTML/CSS?

There is no CSS property like background-opacity that you can use only for changing the opacity or transparency of an element's background without affecting the child elements, on the other hand if you will try to use the CSS opacity property it will not only changes the opacity of background but changes the opacity of all the child elements as well. In such situation you can use RGBA color introduced in CSS3 that includes alpha transparency as part of the color value. Using RGBA color you can set the color of the background as well as its transparency.

Authentication failed to bitbucket

I Reverted to sourcetree 2.0

This solved the bug for me.

https://www.sourcetreeapp.com/download-archives

Delete first character of a string in Javascript

Another alternative to get the first character after deleting it:

// Example string
let string = 'Example';

// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];

console.log(character);
// 'E'

console.log(string);
// 'xample'

What is ViewModel in MVC?

If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.

If there are too few view-specific data and/or transformations, you can use the Model itself

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

DT[order(-x)] works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x) syntax in keeping with the set* commands like setnames, setkey

How to linebreak an svg text within javascript?

This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea, but it does have auto-wrapped text.

However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>s, each with x="0" and dy="1.4em" to simulate actual lines of text. For example:

<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
  <text x="0" y="0">
    <tspan x="0" dy="1.2em">very long text</tspan>
    <tspan x="0" dy="1.2em">I would like to linebreak</tspan>
  </text>
</g>

Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

How to automatically generate a stacktrace when my program crashes

For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in execinfo.h to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found in the libc manual.

Here's an example program that installs a SIGSEGV handler and prints a stacktrace to stderr when it segfaults. The baz() function here causes the segfault that triggers the handler:

#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>


void handler(int sig) {
  void *array[10];
  size_t size;

  // get void*'s for all entries on the stack
  size = backtrace(array, 10);

  // print out all the frames to stderr
  fprintf(stderr, "Error: signal %d:\n", sig);
  backtrace_symbols_fd(array, size, STDERR_FILENO);
  exit(1);
}

void baz() {
 int *foo = (int*)-1; // make a bad pointer
  printf("%d\n", *foo);       // causes segfault
}

void bar() { baz(); }
void foo() { bar(); }


int main(int argc, char **argv) {
  signal(SIGSEGV, handler);   // install our handler
  foo(); // this will call foo, bar, and baz.  baz segfaults.
}

Compiling with -g -rdynamic gets you symbol info in your output, which glibc can use to make a nice stacktrace:

$ gcc -g -rdynamic ./test.c -o test

Executing this gets you this output:

$ ./test
Error: signal 11:
./test(handler+0x19)[0x400911]
/lib64/tls/libc.so.6[0x3a9b92e380]
./test(baz+0x14)[0x400962]
./test(bar+0xe)[0x400983]
./test(foo+0xe)[0x400993]
./test(main+0x28)[0x4009bd]
/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]
./test[0x40086a]

This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before main in addition to main, foo, bar, and baz.

Definition of "downstream" and "upstream"

When you read in git tag man page:

One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If "yourRepo" has declared "otherRepo" as a remote one, then:

  • you are pulling from upstream "otherRepo" ("otherRepo" is "upstream from you", and you are "downstream for otherRepo").
  • you are pushing to upstream ("otherRepo" is still "upstream", where the information now goes back to).

Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.


The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

  • you know what upstream is (the repos you are pulling from or pushing to)
  • you don't know what downstream is made of (the other repos pulling from or pushing to your repo).

Basically:

In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").


You can see an illustration in the git-rebase man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":

It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.


Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse man page:

Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '-') and parameters meant for the underlying git rev-list command they use internally and flags and parameters for the other commands they use downstream of git rev-list. This command is used to distinguish between them.

How to throw RuntimeException ("cannot find symbol")

Just for others: be sure it is new RuntimeException, not new RuntimeErrorException which needs error as an argument.

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

I came up with this too... then I solve it by putting the database information directly in " database.php " In your case, I would change the information like this

mysql' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'wdcollect',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

and don't forget to change your setting in XAMPP's config.inc

['auth_type'] = 'config';
['Servers'][$i]['user'] = 'root';
['Servers'][$i]['password'] = '';
['AllowNoPassword'] = true;

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

Groovy write to file (newline)

It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

You can always get the correct new line character through System.getProperty("line.separator") for example.

Are HTTPS URLs encrypted?

I agree with the previous answers:

To be explicit:

With TLS, the first part of the URL (https://www.example.com/) is still visible as it builds the connection. The second part (/herearemygetparameters/1/2/3/4) is protected by TLS.

However there are a number of reasons why you should not put parameters in the GET request.

First, as already mentioned by others: - leakage through browser address bar - leakage through history

In addition to that you have leakage of URL through the http referer: user sees site A on TLS, then clicks a link to site B. If both sites are on TLS, the request to site B will contain the full URL from site A in the referer parameter of the request. And admin from site B can retrieve it from the log files of server B.)

Python: How to use RegEx in an if statement?

The REPL makes it easy to learn APIs. Just run python, create an object and then ask for help:

$ python
>>> import re
>>> help(re.compile(r''))

at the command line shows, among other things:

search(...)

search(string[, pos[, endpos]]) --> match object or None. Scan through string looking for a match, and return a corresponding MatchObject instance. Return None if no position in the string matches.

so you can do

regex = re.compile(regex_txt, re.IGNORECASE)

match = regex.search(content)  # From your file reading code.
if match is not None:
  # use match

Incidentally,

regex_txt = "facebook.com"

has a . which matches any character, so re.compile("facebook.com").search("facebookkcom") is not None is true because . matches any character. Maybe

regex_txt = r"(?i)facebook\.com"

The \. matches a literal "." character instead of treating . as a special regular expression operator.

The r"..." bit means that the regular expression compiler gets the escape in \. instead of the python parser interpreting it.

The (?i) makes the regex case-insensitive like re.IGNORECASE but self-contained.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

How do I import CSV file into a MySQL table?

I did it in simple way using phpmyadmin. I followed the steps by @Farhan but all data were eltered in single column. How I did:

  1. Created a CSV file and deleted the header row with column names. Kept only data.
  2. I created a table with column names matching the csv columns.
  3. Remember to assign appropriate types to each column.
  4. I just selected the import and went to import tab.
  5. In browse I selected the CSV file and kept all options as it is.
  6. To my surprise all the data got imported successfully in their appropriate columns.

How to split strings over multiple lines in Bash?

You can use bash arrays

$ str_array=("continuation"
             "lines")

then

$ echo "${str_array[*]}"
continuation lines

there is an extra space, because (after bash manual):

If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable

So set IFS='' to get rid of extra space

$ IFS=''
$ echo "${str_array[*]}"
continuationlines

Implementation difference between Aggregation and Composition in Java

A simple Composition program

public class Person {
    private double salary;
    private String name;
    private Birthday bday;

    public Person(int y,int m,int d,String name){
        bday=new Birthday(y, m, d);
        this.name=name;
    }


    public double getSalary() {
        return salary;
    }

    public String getName() {
        return name;
    }

    public Birthday getBday() {
        return bday;
    }

    ///////////////////////////////inner class///////////////////////
    private class Birthday{
        int year,month,day;

        public Birthday(int y,int m,int d){
            year=y;
            month=m;
            day=d;
        }

        public String toString(){
           return String.format("%s-%s-%s", year,month,day);

        }
    }

    //////////////////////////////////////////////////////////////////

}
public class CompositionTst {

    public static void main(String[] args) {
        // TODO code application logic here
        Person person=new Person(2001, 11, 29, "Thilina");
        System.out.println("Name : "+person.getName());
        System.out.println("Birthday : "+person.getBday());

        //The below object cannot be created. A bithday cannot exixts without a Person 
        //Birthday bday=new Birthday(1988,11,10);

    }
}

jQuery selector to get form by name

For detecting if the form is present, I'm using

if($('form[name="frmSave"]').length > 0) {
    //do something
}

Set the maximum character length of a UITextField

I found this quick and simple

- (IBAction)backgroundClick:(id)sender {
    if (mytext.length <= 7) {
        [mytext resignFirstResponder];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Too Big" 
                                                        message:@"Please Shorten Name"
                                                       delegate:nil 
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

"Unable to launch the IIS Express Web server" error

  1. Close your project.
  2. Go to folder settings and select show hidden folders option.
  3. Open the folder where your application is. You will see a .vs folder.
  4. Open the .vs folder, you will see a config folder in it. Delete its content.
  5. Run Visual Studio in admin mode. Open your solution from the File menu.
  6. Clean your solution.
  7. Build it.
  8. Run it and voila!

I do not recommend deleting IIS Express folder or messing with the config file in it.

Get user profile picture by Id

This will be helpful link:

http://graph.facebook.com/893914824028397/picture?type=large&redirect=true&width=500&height=500

You can set height and width as you needed

893914824028397 is facebookid

Absolute Positioning & Text Alignment

Maybe specifying a width would work. When you position:absolute an element, it's width will shrink to the contents I believe.

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

Get connection string from App.config

string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;

How to connect android emulator to the internet

[EDIT] For more recent version of Android Studio, the emulator you need to use is no longer in the ~/Library/Android/sdk/tools folder but in ~/LibraryAndroid/sdk/emulator. If while trying the below solution you get the following message "PANIC: Missing emulator engine program for 'x86' CPU.”, then please refer to https://stackoverflow.com/a/49511666 to update your bash environment.

Operating System : Mac OS X El Capitan

IDE : Android Studio 2.2

For some reasons, I wasn't able to access internet through my AVD at work (probably proxy or network configuration issues). What did the trick for me was to launch in command line my AVD and giving manually the Google public DNS 8.8.8.8.

In your Terminal go to the folder tools of your Android sdk to find the 'emulator' program:

cd ~/Library/Android/sdk/tools

Then retrieve the name of your AVDs :

emulator -list-avds

It will return you something like this:

Android_Wear_Round_API_23
Nexus_10_API_22
Nexus_5X_API_22
Nexus_5X_API_24
Nexus_9_API_24

Then launch the AVD you would like with the following instructions:

emulator -avd NameOfYourDevice -dns-server 8.8.8.8

Your AVD is launched and you should be able to use internet.

Rename file with Git

Note that, from March 15th, 2013, you can move or rename a file directly from GitHub:

(you don't even need to clone that repo, git mv xx and git push back to GitHub!)

renaming

You can also move files to entirely new locations using just the filename field.
To navigate down into a folder, just type the name of the folder you want to move the file into followed by /.
The folder can be one that’s already part of your repository, or it can even be a brand-new folder that doesn’t exist yet!

moving

Could not find a version that satisfies the requirement <package>

This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., six, pytz etc).

You should therefore manually include these in requirements.txt (so that the first step downloads them explicitly) or you should install all packages using PyPI and then pip freeze > requirements.txt to store the list of all packages needed.

How to select a CRAN mirror in R

If you need to set the mirror in a non-interactive way (for example doing an rbundler install in a deploy script) you can do it in this way:

First manually run:

chooseCRANmirror()

Pick the mirror number that is best for you and remember it. Then to automate the selection:

R -e 'chooseCRANmirror(graphics=FALSE, ind=87);library(rbundler);bundle()'

Where 87 is the number of the mirror you would like to use. This snippet also installs the rbundle for you. You can omit that if you like.

Append String in Swift

You can simply append string like:

var worldArg = "world is good"

worldArg += " to live";

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

This method automatically outputs column names with your row data using BCP.

The script writes one file for the column headers (read from INFORMATION_SCHEMA.COLUMNS table) then appends another file with the table data.

The final output is combined into TableData.csv which has the headers and row data. Just replace the environment variables at the top to specify the Server, Database and Table name.

set BCP_EXPORT_SERVER=put_my_server_name_here
set BCP_EXPORT_DB=put_my_db_name_here
set BCP_EXPORT_TABLE=put_my_table_name_here

BCP "DECLARE @colnames VARCHAR(max);SELECT @colnames = COALESCE(@colnames + ',', '') + column_name from %BCP_EXPORT_DB%.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='%BCP_EXPORT_TABLE%'; select @colnames;" queryout HeadersOnly.csv -c -T -S%BCP_EXPORT_SERVER%

BCP %BCP_EXPORT_DB%.dbo.%BCP_EXPORT_TABLE% out TableDataWithoutHeaders.csv -c -t, -T -S%BCP_EXPORT_SERVER%

set BCP_EXPORT_SERVER=
set BCP_EXPORT_DB=
set BCP_EXPORT_TABLE=

copy /b HeadersOnly.csv+TableDataWithoutHeaders.csv TableData.csv

del HeadersOnly.csv
del TableDataWithoutHeaders.csv

Note that if you need to supply credentials, replace the -T option with -U my_username -P my_password

This method has the advantage of always having the column names in sync with the table by using INFORMATION_SCHEMA.COLUMNS. The downside is that it creates temporary files. Microsoft should really fix the bcp utility to support this.

This solution uses the SQL row concatenation trick from here combined with bcp ideas from here

When to use If-else if-else over switch statements and vice versa

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.

Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

Get difference between two lists

If you run into TypeError: unhashable type: 'list' you need to turn lists or sets into tuples, e.g.

set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))

See also How to compare a list of lists/sets in python?

Radio button validation in javascript

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}?

See it in action: http://jsfiddle.net/FhgQS/

how to open *.sdf files?

It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.

Visual Studio can also open the files directly if was created with the right version of SQL Compact.

There are also some third-party tools for manipulating them.

How to convert a Collection to List?

Use streams:

someCollection.stream().collect(Collectors.toList())

Allow Access-Control-Allow-Origin header using HTML5 fetch API

You need to set cors header on server side where you are requesting data from. For example if your backend server is in Ruby on rails, use following code before sending back response. Same headers should be set for any backend server.

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

Can you use @Autowired with static fields?

Create a bean which you can autowire which will initialize the static variable as a side effect.

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

How do you compare structs for equality in C?

Note you can use memcmp() on non static stuctures without worrying about padding, as long as you don't initialise all members (at once). This is defined by C90:

http://www.pixelbeat.org/programming/gcc/auto_init.html

Is there a way to programmatically minimize a window

Form myForm;
myForm.WindowState = FormWindowState.Minimized;

What is the difference between "is None" and "== None"

class Foo:
    def __eq__(self,other):
        return True
foo=Foo()

print(foo==None)
# True

print(foo is None)
# False

What does "where T : class, new()" mean?

when using the class in constraints it's mean you can only use Reference type, another thing to add is when to use the constraint new(), it's must be the last thing you write in the Constraints terms.

How do the post increment (i++) and pre increment (++i) operators work in Java?

I believe you are executing all these statements differently
executing together will result => 38 ,29

int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated, 
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)

How to get item's position in a list?

Just to illustrate complete example along with the input_list which has searies1 (example: input_list[0]) in which you want to do a lookup of series2 (example: input_list[1]) and get indexes of series2 if it exists in series1.

Note: Your certain condition will go in lambda expression if conditions are simple

input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)

output:

[0, 2, 6]

Vba macro to copy row from table if value in table meets condition

That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.

Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
    , Unique:=False

Is it possible to change the location of packages for NuGet?

One more little tidbit that I just discovered. (This may be so basic that some haven't mentioned it, but it was important for my solution.) The "packages" folder ends up in the same folder as your .sln file.

We moved our .sln file and then fixed all of the paths inside to find the various projects and voila! Our packages folder ended up where we wanted it.

SQL Server after update trigger

Here is my example after a test

CREATE TRIGGER [dbo].UpdateTasadoresName 
ON [dbo].Tasadores  
FOR  UPDATE
AS 
      UPDATE Tasadores 
      SET NombreCompleto = RTRIM( Tasadores.Nombre + ' ' + isnull(Tasadores.ApellidoPaterno,'') + ' ' + isnull(Tasadores.ApellidoMaterno,'')    )  
      FROM Tasadores 
    INNER JOIN INSERTED i ON Tasadores.id = i.id

The inserted special table will have the information from the updated record.

Parsing JSON Array within JSON Object

Your code is fine, just replace the following line:

JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));

with this line:

JSONArray jsonMainArr = mainJSON.getJSONArray("source");

Difference between a theta join, equijoin and natural join

Cartesian product of two tables gives all the possible combinations of tuples like the example in mathematics the cross product of two sets . since many a times there are some junk values which occupy unnecessary space in the memory too so here joins comes to rescue which give the combination of only those attribute values which are required and are meaningful.

inner join gives the repeated field in the table twice whereas natural join here solves the problem by just filtering the repeated columns and displaying it only once.else, both works the same. natural join is more efficient since it preserves the memory .Also , redundancies are removed in natural join .

equi join of two tables are such that they display only those tuples which matches the value in other table . for example : let new1 and new2 be two tables . if sql query select * from new1 join new2 on new1.id = new.id (id is the same column in two tables) then start from new2 table and join which matches the id in second table . besides , non equi join do not have equality operator they have <,>,and between operator .

theta join consists of all the comparison operator including equality and others < , > comparison operator. when it uses equality(=) operator it is known as equi join .

How do I zip two arrays in JavaScript?

Zip Arrays of same length:

Using Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
_x000D_
_x000D_

Zip Arrays of different length:

Using Array.from()

_x000D_
_x000D_
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
_x000D_
_x000D_

Using Array.prototype.fill() and Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
_x000D_
_x000D_

Remove Duplicate objects from JSON Array

**The following method does the way you want. It filters the array based on all properties values. **

    var standardsList = [
  { "Grade": "Math K", "Domain": "Counting & Cardinality" },
  { "Grade": "Math K", "Domain": "Counting & Cardinality" },
  { "Grade": "Math K", "Domain": "Counting & Cardinality" },
  { "Grade": "Math K", "Domain": "Counting & Cardinality" },
  { "Grade": "Math K", "Domain": "Geometry" },
  { "Grade": "Math 1", "Domain": "Counting & Cardinality" },
  { "Grade": "Math 1", "Domain": "Counting & Cardinality" },
  { "Grade": "Math 1", "Domain": "Orders of Operation" },
  { "Grade": "Math 2", "Domain": "Geometry" },
  { "Grade": "Math 2", "Domain": "Geometry" }
];

const removeDupliactes = (values) => {
  let concatArray = values.map(eachValue => {
    return Object.values(eachValue).join('')
  })
  let filterValues = values.filter((value, index) => {
    return concatArray.indexOf(concatArray[index]) === index

  })
  return filterValues
}
removeDupliactes(standardsList) 

Results this

[{Grade: "Math K", Domain: "Counting & Cardinality"}

{Grade: "Math K", Domain: "Geometry"}

{Grade: "Math 1", Domain: "Counting & Cardinality"}

{Grade: "Math 1", Domain: "Orders of Operation"}

{Grade: "Math 2", Domain: "Geometry"}] 

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

Complex CSS selector for parent of active child

Many people answered with jQuery parent, but just to add on to that I wanted to share a quick snippet of code that I use for adding classes to my navs so I can add styling to li's that only have sub-menus and not li's that don't.

$("li ul").parent().addClass('has-sub');

Android - how do I investigate an ANR?

You can enable StrictMode in API level 9 and above.

StrictMode is most commonly used to catch accidental disk or network access on the application's main thread, where UI operations are received and animations take place. By keeping your application's main thread responsive, you also prevent ANR dialogs from being shown to users.

public void onCreate() {
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                           .detectAll()
                           .penaltyLog()
                           .penaltyDeath()
                           .build());
    super.onCreate();
}

using penaltyLog() you can watch the output of adb logcat while you use your application to see the violations as they happen.

Spring Boot application.properties value not populating

If you're working in a large multi-module project, with several different application.properties files, then try adding your value to the parent project's property file.

If you are unsure which is your parent project, check your project's pom.xml file, for a <parent> tag.

This solved the issue for me.

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

If you read this POST in 2016, please achieve what you want by using

--only={prod[uction]|dev[elopment]} 

argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV.

from: https://docs.npmjs.com/cli/install

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

How can I find matching values in two arrays?

With some ES6:

let sortedArray = [];
firstArr.map((first) => {
  sortedArray[defaultArray.findIndex(def => def === first)] = first;
});
sortedArray = sortedArray.filter(v => v);

This snippet also sorts the firstArr based on the order of the defaultArray

like:

let firstArr = ['apple', 'kiwi', 'banana'];
let defaultArray = ['kiwi', 'apple', 'pear'];
...
console.log(sortedArray);
// ['kiwi', 'apple'];

Load local images in React.js

In React.js latest version v17.0.1, we can not require the local image we have to import it. like we use to do before = require('../../src/Assets/images/fruits.png'); Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';

Before React V17.0.1 we can use require(../) and it is working fine.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

I've just faced the same problem just after installed Oracle XE 11.2. After reading and consulting a DBA friend, I ran the following command:

C:\>tnsping xe

TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2017 14:27:44

Copyright (c) 1997, 2014, Oracle.  All rights reserved.

Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora


Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE)))

OK (30 msec)

C:\>

As you can see, it takes long time to resolve, so I added an entry to hosts file as follows:

127.0.0.1       localhost

Once done, ran again the same command:

C:\>tnsping xe

TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2
017 14:40:29

Copyright (c) 1997, 2014, Oracle.  All rights reserved.

Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora


Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SER
VICE_NAME = XE)))
OK (30 msec)

C:\>

As time response radically decreases, I tried my connection on sqldeveloper successfully.

connection succed

Phonegap + jQuery Mobile, real world sample or tutorial

you may check this website: Phonegap RSS feeds, Javascript, this is an example about rss reader which uses the phonegap and jquery-mobile techniques

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

I had the same issue when I was using GIT bash to merge master branch in to my feature branch. I followed the following steps to overcome this.

  1. press 'i' (To insert a merge message)
  2. write your merge message
  3. press esc button (To go back)
  4. write ':wq' (write & quit)
  5. then press enter

no overload for matches delegate 'system.eventhandler'

Change the klik method as follows:

public void klik(object pea, EventArgs e)
{
    Bitmap c = this.DrawMandel();
    Button btn = pea as Button;
    Graphics gr = btn.CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

How do I clear my local working directory in Git?

All the answers so far retain local commits. If you're really serious, you can discard all local commits and all local edits by doing:

git reset --hard origin/branchname

For example:

git reset --hard origin/master

This makes your local repository exactly match the state of the origin (other than untracked files).

If you accidentally did this after just reading the command, and not what it does :), use git reflog to find your old commits.

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

MVVM Passing EventArgs As Command Parameter

I know this is a fairly old question, but I ran into the same problem today and wasn't too interested in referencing all of MVVMLight just so I can use event triggers with event args. I have used MVVMLight in the past and it's a great framework, but I just don't want to use it for my projects any more.

What I did to resolve this problem was create an ULTRA minimal, EXTREMELY adaptable custom trigger action that would allow me to bind to the command and provide an event args converter to pass on the args to the command's CanExecute and Execute functions. You don't want to pass the event args verbatim, as that would result in view layer types being sent to the view model layer (which should never happen in MVVM).

Here is the EventCommandExecuter class I came up with:

public class EventCommandExecuter : TriggerAction<DependencyObject>
{
    #region Constructors

    public EventCommandExecuter()
        : this(CultureInfo.CurrentCulture)
    {
    }

    public EventCommandExecuter(CultureInfo culture)
    {
        Culture = culture;
    }

    #endregion

    #region Properties

    #region Command

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    #region EventArgsConverterParameter

    public object EventArgsConverterParameter
    {
        get { return (object)GetValue(EventArgsConverterParameterProperty); }
        set { SetValue(EventArgsConverterParameterProperty, value); }
    }

    public static readonly DependencyProperty EventArgsConverterParameterProperty =
        DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    public IValueConverter EventArgsConverter { get; set; }

    public CultureInfo Culture { get; set; }

    #endregion

    protected override void Invoke(object parameter)
    {
        var cmd = Command;

        if (cmd != null)
        {
            var param = parameter;

            if (EventArgsConverter != null)
            {
                param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
            }

            if (cmd.CanExecute(param))
            {
                cmd.Execute(param);
            }
        }
    }
}

This class has two dependency properties, one to allow binding to your view model's command, the other allows you to bind the source of the event if you need it during event args conversion. You can also provide culture settings if you need to (they default to the current UI culture).

This class allows you to adapt the event args so that they may be consumed by your view model's command logic. However, if you want to just pass the event args on verbatim, simply don't specify an event args converter.

The simplest usage of this trigger action in XAML is as follows:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter Command="{Binding Path=Update, Mode=OneTime}" EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

If you needed access to the source of the event, you would bind to the owner of the event

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter 
            Command="{Binding Path=Update, Mode=OneTime}" 
            EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"
            EventArgsConverterParameter="{Binding ElementName=SomeEventSource, Mode=OneTime}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

(this assumes that the XAML node you're attaching the triggers to has been assigned x:Name="SomeEventSource"

This XAML relies on importing some required namespaces

xmlns:cmd="clr-namespace:MyProject.WPF.Commands"
xmlns:c="clr-namespace:MyProject.WPF.Converters"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and creating an IValueConverter (called NameChangedArgsToStringConverter in this case) to handle the actual conversion logic. For basic converters I usually create a default static readonly converter instance, which I can then reference directly in XAML as I have done above.

The benefit of this solution is that you really only need to add a single class to any project to use the interaction framework much the same way that you would use it with InvokeCommandAction. Adding a single class (of about 75 lines) should be much more preferable to an entire library to accomplish identical results.

NOTE

this is somewhat similar to the answer from @adabyron but it uses event triggers instead of behaviours. This solution also provides an event args conversion ability, not that @adabyron's solution could not do this as well. I really don't have any good reason why I prefer triggers to behaviours, just a personal choice. IMO either strategy is a reasonable choice.

how to open an URL in Swift3

All you need is:

guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

CSS width of a <span> tag

You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.

You could use display inline-block but that isn't widely supported.

A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

.NET Core vs Mono

You have chosen not only a realistic path, but arguably one of the best ecosystems strongly backed(also X-platforms) by MS. Still you should consider following points:

  • Update: Main doc about .Net platform standard is here: https://github.com/dotnet/corefx/blob/master/Documentation/architecture/net-platform-standard.md
  • Update: Current Mono 4.4.1 cannot run latest Asp.Net core 1.0 RTM
  • Although mono is more feature complete, its future is unclear, because MS owns it for some months now and its a duplicate work for them to support it. But MS is definitely committed to .Net Core and betting big on it.
  • Although .Net core is released, the 3rd party ecosystem is not quite there. For example Nhibernate, Umbraco etc cannot run over .Net core yet. But they have a plan.
  • There are some features missing in .Net Core like System.Drawing, you should look for 3rd party libraries
  • You should use nginx as front server with kestrelserver for asp.net apps, because kestrelserver is not quite ready for production. For example HTTP/2 is not implemented.

I hope it helps

Run all SQL files in a directory

I wrote an open source utility in C# that allows you to drag and drop many SQL files and start running them against a database.

The utility has the following features:

  • Drag And Drop script files
  • Run a directory of script files
  • Sql Script out put messages during execution
  • Script passed or failed that are colored green and red (yellow for running)
  • Stop on error option
  • Open script on error option
  • Run report with time taken for each script
  • Total duration time
  • Test DB connection
  • Asynchronus
  • .Net 4 & tested with SQL 2008
  • Single exe file
  • Kill connection at anytime

RegEx match open tags except XHTML self-contained tags

You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n?erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege???x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the transgression of a chi?ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c??o??rrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg?ex parsers for HTML will ins?tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil?l devour your HT?ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi?ght he com?e?s, ?h?i?s un?ho?ly radian?ce? destro?ying all enli??^?ghtenment, HTML tags lea?ki¸n?g fr?o?m ?yo??ur eye?s? ?l?ik?e liq?uid pain, the song of re?gular exp?ression parsing will exti?nguish the voices of mor?tal man from the sp?here I can see it can you see _????i^??t´??_??_? it is beautiful t?he final snuffing of the lie?s of Man ALL IS LOS´???????T ALL I?S LOST the pon?y he comes he c??omes he comes the ich?or permeates all MY FACE MY FACE ?h god no NO NOO?O?O NT stop the an?*?????¯????g????????l??????????e¯?s ?a¸??r?????e n?ot re`???a?l~??????? ZA????LG? IS?^??????_ TO???????? TH?E??? ?P???O??N?Y? H???¯?"????E????`´¸??? ???¸??_???C???????_??O??????M????????_?E?????????S??????????


Have you tried using an XML parser instead?


Moderator's Note

This post is locked to prevent inappropriate edits to its content. The post looks exactly as it is supposed to look - there are no problems with its content. Please do not flag it for our attention.

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Android: How to change CheckBox size?

Well i have found many answer, But they work fine without text when we require text also with checkbox like in my UIenter image description here

Here as per my UI requirement i can't not increase TextSize so other option i tried is scaleX and scaleY (Strach the check box) and custom xml selector with .png Images(its also creating problem with different screen size)

But we have another solution for that, that is Vector Drawable

Do it in 3 steps.

Step 1: Copy these three Vector Drawable to your drawable folder

checked.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="16dp"
android:height="16dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
    android:fillColor="#FF000000"
    android:pathData="M19,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.11,0 2,-0.9 2,-2L21,5c0,-1.1 -0.89,-2 -2,-2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z" />
</vector>

un_checked.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="16dp"
android:height="16dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
    android:fillColor="#FF000000"
    android:pathData="M19,5v14H5V5h14m0,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2V5c0,-1.1 -0.9,-2 -2,-2z" />
</vector>

(Note if you are workiong with Android Studio, you can also add these Vector Drawable from there, Right click on your drawable folder then New/Vector Asset, then select these drawable from there)

Step 2: Create XML selector for check_box

check_box_selector.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checked" android:state_checked="true" />
<item android:drawable="@drawable/un_checked" />
</selector>

Step 3: Set that drawable into check box

<CheckBox
android:id="@+id/suggectionNeverAskAgainCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:button="@drawable/check_box_selector"
android:textColor="#FF000000"
android:textSize="13dp"
android:text="  Never show this alert again" />

Now its like:

enter image description here


You can change its width and height or viewportHeight and viewportWidth and fillColor also


Hope it will help!

How to output JavaScript with PHP

The error you get if because you need to escape the quotes (like other answers said).

To avoid that, you can use an alternative syntax for you strings declarations, called "Heredoc"

With this syntax, you can declare a long string, even containing single-quotes and/or double-quotes, whithout having to escape thoses ; it will make your Javascript code easier to write, modify, and understand -- which is always a good thing.

As an example, your code could become :

$str = <<<MY_MARKER
<script type="text/javascript">
  document.write("Hello World!");
</script>
MY_MARKER;

echo $str;

Note that with Heredoc syntax (as with string delimited by double-quotes), variables are interpolated.

Latex - Change margins of only a few pages

I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

\usepackage{geometry}
...
... 
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...    
\restoregeometry     %so it does not affect the rest of the pages.
...
... 
...

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

How to disable an input type=text?

You can also by jquery:

$('#foo')[0].disabled = true;

Working example:

_x000D_
_x000D_
$('#foo')[0].disabled = true;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input id="foo" placeholder="placeholder" value="value" />
_x000D_
_x000D_
_x000D_

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

Convert ArrayList to String array in Android

I know im very late to answer this. But it will help others, I was also stucked on this.

Here is what i did to get it work.

String[] namesArr = (String[]) names.toArray(new String[names.size()]);

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

Does Python's time.time() return the local or UTC timestamp?

The time.time() function returns the number of seconds since the epoch, as seconds. Note that the "epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where you are "seconds past epoch" (time.time()) returns the same value at the same moment.

Here is some sample output I ran on my computer, converting it to a string as well.

Python 2.7.3 (default, Apr 24 2012, 00:00:54) 
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> ts = time.time()
>>> print ts
1355563265.81
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2012-12-15 01:21:05
>>>

The ts variable is the time returned in seconds. I then converted it to a string using the datetime library making it a string that is human readable.

How to add color to Github's README.md file

As an alternative to rendering a raster image, you can embed a SVG file:

<a><img src="http://dump.thecybershadow.net/6c736bfd11ded8cdc5e2bda009a6694a/colortext.svg"/></a>

You can then add color text to the SVG file as usual:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" 
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="100" height="50"
>
  <text font-size="16" x="10" y="20">
    <tspan fill="red">Hello</tspan>,
    <tspan fill="green">world</tspan>!
  </text>
</svg>

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

Demo: https://gist.github.com/CyberShadow/95621a949b07db295000

How to match a substring in a string, ignoring case

a = "MandY"
alow = a.lower()
if "mandy" in alow:
    print "true"

work around

What are best practices for REST nested resources?

Rails provides a solution to this: shallow nesting.

I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.

Choose File Dialog

Adding to the mix: the OI File Manager has a public api registered at openintents.org

http://www.openintents.org/filemanager

http://www.openintents.org/action/org-openintents-action-pick-file/

How to search a string in String array

Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

How can I export data to an Excel file

With Aspose.Cells library for .NET, you can easily export data of specific rows and columns from one Excel document to another. The following code sample shows how to do this in C# language.

// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");

// Create the destination excel file.
Workbook destWorkbook = new Workbook();
   
// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];

// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];

// Copy the second row of the source Workbook to the first row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 1, 0);

// Copy the fourth row of the source Workbook to the second row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 3, 1);

// Save the destination excel file.
destWorkbook.Save("Destination_Workbook.xlsx");

Copy Rows Data from one Excel Document to another

The following blog post explains in detail how to export data from different sources to an Excel document.
https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/

Linux command to check if a shell script is running or not

here a quick script to test if a shell script is running

#!/bin/sh

scripToTest="your_script_here.sh"
scriptExist=$(pgrep -f "$scripToTest")
[ -z "$scriptExist" ] && echo "$scripToTest : not running" || echo "$scripToTest : runnning"

Revert to Eclipse default settings

Try switching between different Themes option available in General->Appearance->Colors and Fonts.

I earlier used Dark theme in Juno. Then reverted to Windows 7 classic theme but was left with Black background. And that led me to this question. Having not found any solution I finally tried with Windows XP Olive and to my amazement black background was restored to default.

enter image description here

Does C# have extension properties?

Update (thanks to @chaost for pointing this update out):

Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"

Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/


I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.

Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.

So instead of doing this...

public static class IntExtensions
{
   public static bool Even(this int value)
   {
        return value % 2 == 0;
   }
}

We'll be finally able to do it like so...

public extension IntExtension extends int
{
    public bool Even => this % 2 == 0;
}

Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/

How do you convert an entire directory with ffmpeg?

To convert with subdirectories use e.g.

find . -exec ffmpeg -i {} {}.mp3 \;

How do I disable a Pylint warning?

You just have to add one line to disable what you want to disable.

E.g.,

#pylint: disable = line-too-long, too-many-lines, no-name-in-module, import-error, multiple-imports, pointless-string-statement, wrong-import-order

Add this at the very beginning of your module.

Split string into tokens and save them in an array

You can use strtok()

char string[]=  "abc/qwe/jkh";
char *array[10];
int i=0;

array[i] = strtok(string,"/");

while(array[i]!=NULL)
{
   array[++i] = strtok(NULL,"/");
}

Filter dict to contain only certain keys?

This one liner lambda should work:

dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])

Here's an example:

my_dict = {"a":1,"b":2,"c":3,"d":4}
wanted_keys = ("c","d")

# run it
In [10]: dictfilt(my_dict, wanted_keys)
Out[10]: {'c': 3, 'd': 4}

It's a basic list comprehension iterating over your dict keys (i in x) and outputs a list of tuple (key,value) pairs if the key lives in your desired key list (y). A dict() wraps the whole thing to output as a dict object.

How does the JPA @SequenceGenerator annotation work

Now, back to your questions:

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

By using the GenerationType.SEQUENCE strategy on the @GeneratedValue annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).

If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE instead, which is undesirable since the TABLE generation performs badly.

So, don't use the GenerationType.SEQUENCE strategy with MySQL.

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?

I assume you are talking about the GenerationType.IDENTITY when you say database auto-increment feature.

To use an AUTO_INCREMENT or IDENTITY column, you need to use the GenerationType.IDENTITYstrategy on the @GeneratedValue annotation.

Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?

The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:

These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.

To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled or pooled-lo instead of hi/lo. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled or pooled-lo optimizers.

Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

The sequenceName attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE DDL statement.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post"
)
private Long id;

Hibernate is going to use the seq_post database object to generate the identifier values:

SELECT nextval('hibernate_sequence')

The allocationSize defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled optimizer, to reduce the number of database sequence calls.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post",
    allocationSize = 5
)
private Long id;

Then, when you persist 5 entities:

for (int i = 1; i <= 5; i++) {
    entityManager.persist(
        new Post().setTitle(
            String.format(
                "High-Performance Java Persistence, Part %d",
                i
            )
        )
    );
}

Only 2 database sequence calls will be executed, instead of 5:

SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)

jquery get all form elements: input, textarea & select

Edit: As pointed out in comments (Mario Awad & Brock Hensley), use .find to get the children

$("form").each(function(){
    $(this).find(':input') //<-- Should return all input elements in that specific form.
});

forms also have an elements collection, sometimes this differs from children such as when the form tag is in a table and is not closed.

_x000D_
_x000D_
var summary = [];_x000D_
$('form').each(function () {_x000D_
    summary.push('Form ' + this.id + ' has ' + $(this).find(':input').length + ' child(ren).');_x000D_
    summary.push('Form ' + this.id + ' has ' + this.elements.length + ' form element(s).');_x000D_
});_x000D_
_x000D_
$('#results').html(summary.join('<br />'));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form id="A" style="display: none;">_x000D_
    <input type="text" />_x000D_
    <button>Submit</button>_x000D_
</form>_x000D_
<form id="B" style="display: none;">_x000D_
    <select><option>A</option></select>_x000D_
    <button>Submit</button>_x000D_
</form>_x000D_
_x000D_
<table bgcolor="white" cellpadding="12" border="1" style="display: none;">_x000D_
<tr><td colspan="2"><center><h1><i><b>Login_x000D_
Area</b></i></h1></center></td></tr>_x000D_
<tr><td><h1><i><b>UserID:</b></i></h1></td><td><form id="login" name="login" method="post"><input_x000D_
name="id" type="text"></td></tr>_x000D_
<tr><td><h1><i><b>Password:</b></i></h1></td><td><input name="pass"_x000D_
type="password"></td></tr>_x000D_
<tr><td><center><input type="button" value="Login"_x000D_
onClick="pasuser(this.form)"></center></td><td><center><br /><input_x000D_
type="Reset"></form></td></tr></table></center>_x000D_
<div id="results"></div>
_x000D_
_x000D_
_x000D_


May be :input selector is what you want

$("form").each(function(){ $(':input', this)//<-- Should return all input elements in that specific form. });

As pointed out in docs

To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

You can use like below,

$("form").each(function(){
    $(this).filter(':input') //<-- Should return all input elements in that specific form.
});

How to save traceback / sys.exc_info() values in a variable?

Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

Remember to import traceback.

Here's the output from traceback.extract_stack(). Formatting added for readability.

>>> traceback.extract_stack()
[
   ('<string>', 1, '<module>', None),
   ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
   ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
   ('<pyshell#1>', 1, '<module>', None)
]

Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

>>> ''.join(traceback.format_stack())
'  File "<string>", line 1, in <module>\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
       ret = method(*args, **kwargs)\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
       exec(code, self.locals)\n  File "<pyshell#2>", line 1, in <module>\n'

$rootScope.$broadcast vs. $scope.$emit

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

How can one check to see if a remote file exists using PHP?

This is not an answer to your original question, but a better way of doing what you're trying to do:

Instead of actually trying to get the site's favicon directly (which is a royal pain given it could be /favicon.png, /favicon.ico, /favicon.gif, or even /path/to/favicon.png), use google:

<img src="http://www.google.com/s2/favicons?domain=[domain]">

Done.

How to properly create an SVN tag from trunk?

Another option to tag a Subversion repository is to add the tag to the svn:log property like this:

   echo "TAG: your_tag_text" > newlog
   svn propget $REPO --revprop -r $tagged_revision >> newlog
   svn propset $REPO --revprop -r $tagged_revision -F newlog
   rm newlog

I recently started thinking that this is the most "right" way to tag. This way you don't create extra revisions (as you do with "svn cp") and still can easily extract all tags by using grep on "svn log" output:

   svn log | awk '/----/ {
                      expect_rev=1;
                      expect_tag=0;
                  }
                  /^r[[:digit:]]+/ {
                      if(expect_rev) {
                          rev=$1;
                          expect_tag=1;
                          expect_rev=0;
                      }
                  }
                  /^TAG:/ {
                      if(expect_tag) {
                          print "Revision "rev", Tag: "$2;
                      }
                      expect_tag=0;
                  }'

Also, this way you may seamlessly delete tags if you need to. So the tags become a complete meta-information, and I like it.

How to print colored text to the terminal?

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

Adding items to end of linked list

loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null

Add up a column of numbers at the Unix shell

Instead of using cut to get the file size from output of ls -l, you can use directly:

$ cat files.txt | xargs ls -l | awk '{total += $5} END {print "Total:", total, "bytes"}'

Awk interprets "$5" as the fifth column. This is the column from ls -l that gives you the file size.

How to debug a bash script?

set +x = @ECHO OFF, set -x = @ECHO ON.


You can add -xv option to the standard Shebang as follows:

#!/bin/bash -xv  

-x : Display commands and their arguments as they are executed.
-v : Display shell input lines as they are read.


ltrace is another Linux Utility similar to strace. However, ltrace lists all the library calls being called in an executable or a running process. Its name itself comes from library-call tracing. For example:

ltrace ./executable <parameters>  
ltrace -p <PID>  

Source

Count number of 1's in binary representation

That will be the shortest answer in my SO life: lookup table.

Apparently, I need to explain a bit: "if you have enough memory to play with" means, we've got all the memory we need (nevermind technical possibility). Now, you don't need to store lookup table for more than a byte or two. While it'll technically be O(log(n)) rather than O(1), just reading a number you need is O(log(n)), so if that's a problem, then the answer is, impossible—which is even shorter.

Which of two answers they expect from you on an interview, no one knows.

There's yet another trick: while engineers can take a number and talk about O(log(n)), where n is the number, computer scientists will say that actually we're to measure running time as a function of a length of an input, so what engineers call O(log(n)) is actually O(k), where k is the number of bytes. Still, as I said before, just reading a number is O(k), so there's no way we can do better than that.

Internet Explorer 11 detection

Using this RegExp seems works for IE 10 and IE 11:

function isIE(){
    return /Trident\/|MSIE/.test(window.navigator.userAgent);
}

I do not have a IE older than IE 10 to test this.

How do I add a simple jQuery script to WordPress?

"We have Google" cit. For properly use script inside wordpress just add hosted libraries. Like Google

After selected library that you need link it before your custom script: exmpl

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

and after your own script

<script type="text/javascript">
    $(document).ready(function () {
        $('.text_container').addClass("hidden");
    });
</script>

Is it possible to use jQuery to read meta tags

jQuery now supports .data();, so if you have

<div id='author' data-content='stuff!'>

use

var author = $('#author').data("content"); // author = 'stuff!'

"Cloning" row or column vectors

Here's an elegant, Pythonic way to do it:

>>> array([[1,2,3],]*3)
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

the problem with [16] seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:

>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
        [2],
        [3]])

Convert json data to a html table

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

Tensorflow import error: No module named 'tensorflow'

The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.

create a new separate environment in Anaconda dedicated to TensorFlow as follows:

conda create -n newenvt anaconda python=python_version

replace python_version by your python version

activate the new environment as follows:

activate newenvt

Then install tensorflow into the new environment (newenvt) as follows:

conda install tensorflow

Now you can check it by issuing the following python code and it will work fine.

import tensorflow

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

The message is saying that your configuration file is corrupt in some way. However it also says that it can't actually access the config file. So I'd ignore the original message about corruption/lack of validity as this is most likely just the effect of not being able to read the file due to a lack of authorization.

The reason it cannot read the config file is because the process running your web app does not have permission to access the file/directory. So you need to give the process running your web app those permissions.

The access rights should be fairly straightforward, i.e. at least Read, and, depending on your app, maybe Write.

Above, you mention IUSR etc. not being in the properties for web.config. If by that you mean that IUSR is not listed in the security tab of the file then it's a good thing. One doesn't want to give IUSR any kind of permission to web.config. The role IUSR is an anonymous internet user.

The file web.config should only be accessible through your application.

The problem is you haven't said which OS and IIS version you are using so it's difficult to advise which steps to take.

I.e. in IIS 7.5, the error message you're quoting is likely to occur due to your ApplicationPoolIdentity not being assigned the permissions. Your web application belongs to an application pool and so you need to give the permissions to the OS account that your web application's application pool runs under. Often this is something like NetworkService but you may have customized it to run under a purpose made account. Without more info it's difficult to help you.

How to convert enum names to string in c

I found a C preprocessor trick that is doing the same job without declaring a dedicated array string (Source: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/c_preprocessor_applications_en).

Sequential enums

Following the invention of Stefan Ram, sequential enums (without explicitely stating the index, e.g. enum {foo=-1, foo1 = 1}) can be realized like this genius trick:

#include <stdio.h>

#define NAMES C(RED)C(GREEN)C(BLUE)
#define C(x) x,
enum color { NAMES TOP };
#undef C

#define C(x) #x,    
const char * const color_name[] = { NAMES };

This gives the following result:

int main( void )  { 
    printf( "The color is %s.\n", color_name[ RED ]);  
    printf( "There are %d colors.\n", TOP ); 
}

The color is RED.
There are 3 colors.

Non-Sequential enums

Since I wanted to map error codes definitions to are array string, so that I can append the raw error definition to the error code (e.g. "The error is 3 (LC_FT_DEVICE_NOT_OPENED)."), I extended the code in that way that you can easily determine the required index for the respective enum values:

#define LOOPN(n,a) LOOP##n(a)
#define LOOPF ,
#define LOOP2(a) a LOOPF a LOOPF
#define LOOP3(a) a LOOPF a LOOPF a LOOPF
#define LOOP4(a) a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP5(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP6(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP7(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP8(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP9(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF


#define LC_ERRORS_NAMES \
    Cn(LC_RESPONSE_PLUGIN_OK, -10) \
    Cw(8) \
    Cn(LC_RESPONSE_GENERIC_ERROR, -1) \
    Cn(LC_FT_OK, 0) \
    Ci(LC_FT_INVALID_HANDLE) \
    Ci(LC_FT_DEVICE_NOT_FOUND) \
    Ci(LC_FT_DEVICE_NOT_OPENED) \
    Ci(LC_FT_IO_ERROR) \
    Ci(LC_FT_INSUFFICIENT_RESOURCES) \
    Ci(LC_FT_INVALID_PARAMETER) \
    Ci(LC_FT_INVALID_BAUD_RATE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_ERASE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_WRITE) \
    Ci(LC_FT_FAILED_TO_WRITE_DEVICE) \
    Ci(LC_FT_EEPROM_READ_FAILED) \
    Ci(LC_FT_EEPROM_WRITE_FAILED) \
    Ci(LC_FT_EEPROM_ERASE_FAILED) \
    Ci(LC_FT_EEPROM_NOT_PRESENT) \
    Ci(LC_FT_EEPROM_NOT_PROGRAMMED) \
    Ci(LC_FT_INVALID_ARGS) \
    Ci(LC_FT_NOT_SUPPORTED) \
    Ci(LC_FT_OTHER_ERROR) \
    Ci(LC_FT_DEVICE_LIST_NOT_READY)


#define Cn(x,y) x=y,
#define Ci(x) x,
#define Cw(x)
enum LC_errors { LC_ERRORS_NAMES TOP };
#undef Cn
#undef Ci
#undef Cw
#define Cn(x,y) #x,
#define Ci(x) #x,
#define Cw(x) LOOPN(x,"")
static const char* __LC_errors__strings[] = { LC_ERRORS_NAMES };
static const char** LC_errors__strings = &__LC_errors__strings[10];

In this example, the C preprocessor will generate the following code:

enum LC_errors { LC_RESPONSE_PLUGIN_OK=-10,  LC_RESPONSE_GENERIC_ERROR=-1, LC_FT_OK=0, LC_FT_INVALID_HANDLE, LC_FT_DEVICE_NOT_FOUND, LC_FT_DEVICE_NOT_OPENED, LC_FT_IO_ERROR, LC_FT_INSUFFICIENT_RESOURCES, LC_FT_INVALID_PARAMETER, LC_FT_INVALID_BAUD_RATE, LC_FT_DEVICE_NOT_OPENED_FOR_ERASE, LC_FT_DEVICE_NOT_OPENED_FOR_WRITE, LC_FT_FAILED_TO_WRITE_DEVICE, LC_FT_EEPROM_READ_FAILED, LC_FT_EEPROM_WRITE_FAILED, LC_FT_EEPROM_ERASE_FAILED, LC_FT_EEPROM_NOT_PRESENT, LC_FT_EEPROM_NOT_PROGRAMMED, LC_FT_INVALID_ARGS, LC_FT_NOT_SUPPORTED, LC_FT_OTHER_ERROR, LC_FT_DEVICE_LIST_NOT_READY, TOP };

static const char* __LC_errors__strings[] = { "LC_RESPONSE_PLUGIN_OK", "" , "" , "" , "" , "" , "" , "" , "" "LC_RESPONSE_GENERIC_ERROR", "LC_FT_OK", "LC_FT_INVALID_HANDLE", "LC_FT_DEVICE_NOT_FOUND", "LC_FT_DEVICE_NOT_OPENED", "LC_FT_IO_ERROR", "LC_FT_INSUFFICIENT_RESOURCES", "LC_FT_INVALID_PARAMETER", "LC_FT_INVALID_BAUD_RATE", "LC_FT_DEVICE_NOT_OPENED_FOR_ERASE", "LC_FT_DEVICE_NOT_OPENED_FOR_WRITE", "LC_FT_FAILED_TO_WRITE_DEVICE", "LC_FT_EEPROM_READ_FAILED", "LC_FT_EEPROM_WRITE_FAILED", "LC_FT_EEPROM_ERASE_FAILED", "LC_FT_EEPROM_NOT_PRESENT", "LC_FT_EEPROM_NOT_PROGRAMMED", "LC_FT_INVALID_ARGS", "LC_FT_NOT_SUPPORTED", "LC_FT_OTHER_ERROR", "LC_FT_DEVICE_LIST_NOT_READY", };

This results to the following implementation capabilities:

LC_errors__strings[-1] ==> LC_errors__strings[LC_RESPONSE_GENERIC_ERROR] ==> "LC_RESPONSE_GENERIC_ERROR"

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

I think you just need 'git show -c $ref'. Trying this on the git repository on a8e4a59 shows a combined diff (plus/minus chars in one of 2 columns). As the git-show manual mentions, it pretty much delegates to 'git diff-tree' so those options look useful.

Trim leading and trailing spaces from a string in awk

If you want to trim all spaces, only in lines that have a comma, and use awk, then the following will work for you:

awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt

If you only want to remove spaces in the second column, change the expression to

awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt

Note that gsub substitutes the character in // with the second expression, in the variable that is the third parameter - and does so in-place - in other words, when it's done, the $0 (or $2) has been modified.

Full explanation:

-F,            use comma as field separator 
               (so the thing before the first comma is $1, etc)
/,/            operate only on lines with a comma 
               (this means empty lines are skipped)
gsub(a,b,c)    match the regular expression a, replace it with b, 
               and do all this with the contents of c
print$1","$2   print the contents of field 1, a comma, then field 2
input.txt      use input.txt as the source of lines to process

EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub commands. Whilst giving credit I will give an explanation of how it works.

gsub(/^[ \t]+/,"",$2);    - starting at the beginning (^) replace all (+ = zero or more, greedy)
                             consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)}    - do the same, but now for all space up to the end of string ($)
1                         - ="true". Shorthand for "use default action", which is print $0
                          - that is, print the entire (modified) line