Programs & Examples On #Clr

The Common Language Runtime (CLR) is a core component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. In the CLR, code is expressed in a form of bytecode called the Common Intermediate Language (CIL, previously known as MSIL—Microsoft Intermediate Language).

What are major differences between C# and Java?

The following is a great in depth reference by Dare Obasanjo on the differences between C# and Java. I always find myself referring to this article when switching between the two.

http://www.25hoursaday.com/CsharpVsJava.html

SQL Server: How to check if CLR is enabled?

SELECT * FROM sys.configurations
WHERE name = 'clr enabled'

Try-catch speeding up my code?

Well, the way you're timing things looks pretty nasty to me. It would be much more sensible to just time the whole loop:

var stopwatch = Stopwatch.StartNew();
for (int i = 1; i < 100000000; i++)
{
    Fibo(100);
}
stopwatch.Stop();
Console.WriteLine("Elapsed time: {0}", stopwatch.Elapsed);

That way you're not at the mercy of tiny timings, floating point arithmetic and accumulated error.

Having made that change, see whether the "non-catch" version is still slower than the "catch" version.

EDIT: Okay, I've tried it myself - and I'm seeing the same result. Very odd. I wondered whether the try/catch was disabling some bad inlining, but using [MethodImpl(MethodImplOptions.NoInlining)] instead didn't help...

Basically you'll need to look at the optimized JITted code under cordbg, I suspect...

EDIT: A few more bits of information:

  • Putting the try/catch around just the n++; line still improves performance, but not by as much as putting it around the whole block
  • If you catch a specific exception (ArgumentException in my tests) it's still fast
  • If you print the exception in the catch block it's still fast
  • If you rethrow the exception in the catch block it's slow again
  • If you use a finally block instead of a catch block it's slow again
  • If you use a finally block as well as a catch block, it's fast

Weird...

EDIT: Okay, we have disassembly...

This is using the C# 2 compiler and .NET 2 (32-bit) CLR, disassembling with mdbg (as I don't have cordbg on my machine). I still see the same performance effects, even under the debugger. The fast version uses a try block around everything between the variable declarations and the return statement, with just a catch{} handler. Obviously the slow version is the same except without the try/catch. The calling code (i.e. Main) is the same in both cases, and has the same assembly representation (so it's not an inlining issue).

Disassembled code for fast version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret

Disassembled code for slow version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        esi
 [0004] sub         esp,18h
*[0007] mov         dword ptr [ebp-14h],1
 [000e] mov         dword ptr [ebp-10h],0
 [0015] mov         dword ptr [ebp-1Ch],1
 [001c] mov         dword ptr [ebp-18h],0
 [0023] inc         ecx
 [0024] mov         esi,2
 [0029] cmp         ecx,2
 [002c] jle         00000031
 [002e] mov         eax,dword ptr [ebp-14h]
 [0031] mov         edx,dword ptr [ebp-10h]
 [0034] mov         dword ptr [ebp-0Ch],eax
 [0037] mov         dword ptr [ebp-8],edx
 [003a] mov         eax,dword ptr [ebp-1Ch]
 [003d] mov         edx,dword ptr [ebp-18h]
 [0040] mov         dword ptr [ebp-14h],eax
 [0043] mov         dword ptr [ebp-10h],edx
 [0046] mov         eax,dword ptr [ebp-0Ch]
 [0049] mov         edx,dword ptr [ebp-8]
 [004c] add         eax,dword ptr [ebp-1Ch]
 [004f] adc         edx,dword ptr [ebp-18h]
 [0052] mov         dword ptr [ebp-1Ch],eax
 [0055] mov         dword ptr [ebp-18h],edx
 [0058] inc         esi
 [0059] cmp         esi,ecx
 [005b] jl          FFFFFFD3
 [005d] mov         eax,dword ptr [ebp-1Ch]
 [0060] mov         edx,dword ptr [ebp-18h]
 [0063] lea         esp,[ebp-4]
 [0066] pop         esi
 [0067] pop         ebp
 [0068] ret

In each case the * shows where the debugger entered in a simple "step-into".

EDIT: Okay, I've now looked through the code and I think I can see how each version works... and I believe the slower version is slower because it uses fewer registers and more stack space. For small values of n that's possibly faster - but when the loop takes up the bulk of the time, it's slower.

Possibly the try/catch block forces more registers to be saved and restored, so the JIT uses those for the loop as well... which happens to improve the performance overall. It's not clear whether it's a reasonable decision for the JIT to not use as many registers in the "normal" code.

EDIT: Just tried this on my x64 machine. The x64 CLR is much faster (about 3-4 times faster) than the x86 CLR on this code, and under x64 the try/catch block doesn't make a noticeable difference.

In C#, why is String a reference type that behaves like a value type?

At the risk of getting yet another mysterious down-vote...the fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.

Floating-point primitive types are handled by the FPU, which is 80 bits wide.

This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

I had the same error and could not figure it out with the other answers. I found that we can "Consolidate" NuGet packages.

  1. Right click on the solution
  2. Click Manage Nuget Packages
  3. Consolidate tab and update to the same version.

Reference jars inside a jar

Add the jar files to your library(if using netbeans) and modify your manifest's file classpath as follows:

Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar

a similar answer exists here

How to get relative path of a file in visual studio?

I also met the same problem and I was able to get it through. So let me explain the steps I applied. I shall explain it according to your scenario.

According to my method we need to use 'Path' class and 'Assembly' class in order to get the relative path.

So first Import System.IO and System.Reflection in using statements.

Then type the below given code line.

        var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly(). CodeBase);

Actually above given line stores the path of the output directory of your project.(Here 'output' directory refers to the Debug folder of your project).

Now copy your FolderIcon directory in to the Debug folder. Then type the below given Line.

var iconPath = Path.Combine(outPutDirectory, "FolderIcon\\Folder.ico");

Now this 'iconPath ' variable contains the entire path of your Folder.ico. All you have to do is store it in a string variable. Use the line of code below for that.

string icon_path = new Uri(iconPath ).LocalPath;

Now you can use this icon_path string variable as your relative path to the icon.

Thanks.

PHP random string generator

I liked the last comment which used openssl_random_pseudo_bytes, but it wasn't a solution for me as I still had to remove the characters I didn't want, and I wasn't able to get a set length string. Here is my solution...

function rndStr($len = 20) {
    $rnd='';
    for($i=0;$i<$len;$i++) {
        do {
            $byte = openssl_random_pseudo_bytes(1);
            $asc = chr(base_convert(substr(bin2hex($byte),0,2),16,10));
        } while(!ctype_alnum($asc));
        $rnd .= $asc;
    }
    return $rnd;
}

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

How to create JSON string in C#

If you need complex result (embedded) create your own structure:

class templateRequest
{
    public String[] registration_ids;
    public Data data;
    public class Data
    {
        public String message;
        public String tickerText;
        public String contentTitle;
        public Data(String message, String tickerText, string contentTitle)
        {
            this.message = message;
            this.tickerText = tickerText;
            this.contentTitle = contentTitle;
        }                
    };
}

and then you can obtain JSON string with calling

List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");

string json = new JavaScriptSerializer().Serialize(request);

The result will be like this:

json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"

Hope it helps!

how to get the host url using javascript from the current page

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"

How can I convert radians to degrees with Python?

Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.

To match the output of your calculator you need:

>>> math.cos(math.radians(1))
0.9998476951563913

Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.

Can I catch multiple Java exceptions in the same catch clause?

In pre-7 how about:

  Boolean   caught = true;
  Exception e;
  try {
     ...
     caught = false;
  } catch (TransformerException te) {
     e = te;
  } catch (SocketException se) {
     e = se;
  } catch (IOException ie) {
     e = ie;
  }
  if (caught) {
     someCode(); // You can reference Exception e here.
  }

MySQL maximum memory usage

MySQL's maximum memory usage very much depends on hardware, your settings and the database itself.

Hardware

The hardware is the obvious part. The more RAM the merrier, faster disks ftw. Don't believe those monthly or weekly news letters though. MySQL doesn't scale linear - not even on Oracle hardware. It's a little trickier than that.

The bottom line is: there is no general rule of thumb for what is recommend for your MySQL setup. It all depends on the current usage or the projections.

Settings & database

MySQL offers countless variables and switches to optimize its behavior. If you run into issues, you really need to sit down and read the (f'ing) manual.

As for the database -- a few important constraints:

  • table engine (InnoDB, MyISAM, ...)
  • size
  • indices
  • usage

Most MySQL tips on stackoverflow will tell you about 5-8 so called important settings. First off, not all of them matter - e.g. allocating a lot of resources to InnoDB and not using InnoDB doesn't make a lot of sense because those resources are wasted.

Or - a lot of people suggest to up the max_connection variable -- well, little do they know it also implies that MySQL will allocate more resources to cater those max_connections -- if ever needed. The more obvious solution might be to close the database connection in your DBAL or to lower the wait_timeout to free those threads.

If you catch my drift -- there's really a lot, lot to read up on and learn.

Engines

Table engines are a pretty important decision, many people forget about those early on and then suddenly find themselves fighting with a 30 GB sized MyISAM table which locks up and blocks their entire application.

I don't mean to say MyISAM sucks, but InnoDB can be tweaked to respond almost or nearly as fast as MyISAM and offers such thing as row-locking on UPDATE whereas MyISAM locks the entire table when it is written to.

If you're at liberty to run MySQL on your own infrastructure, you might also want to check out the percona server because among including a lot of contributions from companies like Facebook and Google (they know fast), it also includes Percona's own drop-in replacement for InnoDB, called XtraDB.

See my gist for percona-server (and -client) setup (on Ubuntu): http://gist.github.com/637669

Size

Database size is very, very important -- believe it or not, most people on the Intarwebs have never handled a large and write intense MySQL setup but those do really exist. Some people will troll and say something like, "Use PostgreSQL!!!111", but let's ignore them for now.

The bottom line is: judging from the size, decision about the hardware are to be made. You can't really make a 80 GB database run fast on 1 GB of RAM.

Indices

It's not: the more, the merrier. Only indices needed are to be set and usage has to be checked with EXPLAIN. Add to that that MySQL's EXPLAIN is really limited, but it's a start.

Suggested configurations

About these my-large.cnf and my-medium.cnf files -- I don't even know who those were written for. Roll your own.

Tuning primer

A great start is the tuning primer. It's a bash script (hint: you'll need linux) which takes the output of SHOW VARIABLES and SHOW STATUS and wraps it into hopefully useful recommendation. If your server has ran some time, the recommendation will be better since there will be data to base them on.

The tuning primer is not a magic sauce though. You should still read up on all the variables it suggests to change.

Reading

I really like to recommend the mysqlperformanceblog. It's a great resource for all kinds of MySQL-related tips. And it's not just MySQL, they also know a lot about the right hardware or recommend setups for AWS, etc.. These guys have years and years of experience.

Another great resource is planet-mysql, of course.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true

$.ajax({

    url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});

jQuery UI accordion that keeps multiple sections open?

Without jQuery-UI accordion, one can simply do this:

<div class="section">
  <div class="section-title">
    Section 1
  </div>
  <div class="section-content">
    Section 1 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
  </div>
</div>

<div class="section">
  <div class="section-title">
    Section 2
  </div>
  <div class="section-content">
    Section 2 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
  </div>
</div>

And js

$( ".section-title" ).click(function() {
    $(this).parent().find( ".section-content" ).slideToggle();
});

https://jsfiddle.net/gayan_dasanayake/6ogxL7nm/

What is the difference between properties and attributes in HTML?

When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.

For instance, this HTML element:

<input type="text" value="Name:">

has 2 attributes (type and value).

Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.

For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:

<input id="the-input" type="text" value="Name:">

the corresponding DOM node will have id,type, and value properties (among others):

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn't modify or limit the value.

  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">, then theInput.getAttribute("type") gives you "foo" but theInput.type gives you "text".

  • In contrast, the value property doesn't reflect the value attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
    

    The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

    So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue property, which is a pure reflection of the value attribute:

    theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
    

There are several properties that directly reflect their attribute (rel, id), some are direct reflections with slightly-different names (htmlFor reflects the for attribute, className reflects the class attribute), many that reflect their attribute but with restrictions/modifications (src, href, disabled, multiple), and so on. The spec covers the various kinds of reflection.

Eclipse CDT: Symbol 'cout' could not be resolved

Thanks loads for the answers above. I'm adding an answer for a specific use-case...

On a project with two target architectures each with its own build configuration (the main target is an embedded AVR platform; the second target is my local Linux PC for running unit tests) I found it necessary to set Preferences -> C/C++ -> Indexer -> Use active build configuration as well as to add /usr/include/c++/4.7, /usr/include and /usr/include/c++/4.7/x86_64-linux-gnu to Project Properties -> C/C++ General -> Paths and Symbols and then to rebuild the index.

python: urllib2 how to send cookie with urlopen request

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

You may also use. This is by using the new datatype DATE. May not work in all previous versions, but greatly simplified to use in later version.

SELECT CAST(getdate() AS DATE)
SELECT LEFT(CAST(getdate() AS DATE), 7)

PuTTY scripting to log onto host

mputty can do that but it does not seem to work always. (if that wait period is too slow)

mputty uses putty and it extends putty. There is an option to run a script. If it does not work, make sure that wait period before typing is a high value or increase that value. See putty sessions , then name of session, right mouse button,properties/script page.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

Unfortunately, there's no way to validate the captcha on the client-side only (web browser), because the nature of captcha itself requires at least two actors (sides) to complete the process. The client-side - asks a human to solve some puzzle, math equitation, text recognition, and the response is being encoded by an algorithm alongside with some metadata like captcha solving timestamp, pseudo-random challenge code. Once the client-side submits the form with a captcha response code, the server-side needs to validate this captcha response code with a predefined set of rules, ie. if captcha solved within 5 min period, if the client's IP addresses are the same and so on. This a very general description, how captchas works, every single implementation (like Google's ReCaptcha, some basic math equitation solving self-made captchas), but the only one thing is common - client-side (web browser) captures users' response and server-side (webserver) validates this response in order to know if the form submission was made by a human or a robot.

NB. The client (web browser) has an option to disable the execution of JavaScript code, which means that the proposed solutions are completely useless.

How should I cast in VB.NET?

MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)

When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.

One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.

Updating a dataframe column in spark

Commonly when updating a column, we want to map an old value to a new value. Here's a way to do that in pyspark without UDF's:

# update df[update_col], mapping old_value --> new_value
from pyspark.sql import functions as F
df = df.withColumn(update_col,
    F.when(df[update_col]==old_value,new_value).
    otherwise(df[update_col])).

Script Tag - async & defer

HTML5: async, defer

In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
  1. Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.

  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.

  3. With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)

What is the C# Using block and why should I use it?

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
   ...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
    OperateOnType(t);
}
finally {
    if (t != null) {
        ((IDisposable)t).Dispose();
    }
}
using (SomeDisposableType u = new SomeDisposableType()) {
    OperateOnType(u);
}

The second is easier to read and maintain.

Checkout multiple git repos into same Jenkins workspace

Since Multiple SCMs Plugin is deprecated.

With Jenkins Pipeline its possible to checkout multiple git repos and after building it using gradle

node {   
def gradleHome

stage('Prepare/Checkout') { // for display purposes
    git branch: 'develop', url: 'https://github.com/WtfJoke/Any.git'

    dir('a-child-repo') {
       git branch: 'develop', url: 'https://github.com/WtfJoke/AnyChild.git'
    }

    env.JAVA_HOME="${tool 'JDK8'}"
    env.PATH="${env.JAVA_HOME}/bin:${env.PATH}" // set java home in jdk environment
    gradleHome = tool '3.4.1' 
}

stage('Build') {
  // Run the gradle build
  if (isUnix()) {
     sh "'${gradleHome}/bin/gradle' clean build"
  } else {
     bat(/"${gradleHome}\bin\gradle" clean build/)
  }
}
}

You might want to consider using git submodules instead of a custom pipeline like this.

Where is android_sdk_root? and how do I set it.?

In Android Studio 3.2.1 I got this error because I installed a new API(28) level emulator without installing that API SDK components. After I installed SDK platform and SDK platform tools for the API level 28 and updated Android Emulator the emulator started running.

Hope it may help someone.

How to get char from string by index?

First make sure the required number is a valid index for the string from beginning or end , then you can simply use array subscript notation. use len(s) to get string length

>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> 

Split function in oracle to comma separated values with automatic sequence

This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.

Note: MYSTRING should end with the separator.

create or replace FUNCTION PK_GET_NTH_PART(MYSTRING VARCHAR2,SEPARATOR_OF_SUBSTR VARCHAR2,NTH_PART NUMBER)
RETURN VARCHAR2
IS
NTH_SUBSTR VARCHAR2(500);
POS1 NUMBER(4);
POS2 NUMBER(4);
BEGIN
IF NTH_PART=1 THEN
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, 1)  INTO POS1 FROM DUAL; 
SELECT SUBSTR(MYSTRING,0,POS1-1) INTO NTH_SUBSTR FROM DUAL;
ELSE
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART-1) INTO  POS1 FROM DUAL; 
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART)  INTO POS2 FROM DUAL; 
SELECT SUBSTR(MYSTRING,POS1+1,(POS2-POS1-1)) INTO NTH_SUBSTR FROM DUAL;
END IF;
RETURN NTH_SUBSTR;
END;

Hope this helps some body, you can use this function like this in a loop to get all the values separated:

SELECT REGEXP_COUNT(MYSTRING, '~', 1, 'i') INTO NO_OF_RECORDS FROM DUAL;
WHILE NO_OF_RECORDS>0
LOOP
    PK_RECORD    :=PK_GET_NTH_PART(MYSTRING,'~',NO_OF_RECORDS);
    -- do some thing
    NO_OF_RECORDS  :=NO_OF_RECORDS-1;
END LOOP;

Here NO_OF_RECORDS,PK_RECORD are temp variables.

Hope this helps.

Find in Files: Search all code in Team Foundation Server

This search for a file link explains how to find a file. I did have to muck around with the advice to make it work.

  1. cd "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE"
  2. tf dir "$/*.sql" /recursive /server:http://mytfsserver:8080/tfs

In the case of the cd command, I performed the cd command because I was looking for the tf.exe file. It was easier to just start from that directory verses adding the whole path. Now that I understand how to make this work, I'd use the absolute path in quotes.

In case of the tf search, I started at the root of the server with $/ and I searched for all files that ended with sql i.e. *.sql. If you don't want to start at the root, then use "$/myproject/*.sql" instead.

Oh! This does not solve the search in file part of the question but my Google search brought me here to find files among other links.

memory error in python

If you get an unexpected MemoryError and you think you should have plenty of RAM available, it might be because you are using a 32-bit python installation.

The easy solution, if you have a 64-bit operating system, is to switch to a 64-bit installation of python.

The issue is that 32-bit python only has access to ~4GB of RAM. This can shrink even further if your operating system is 32-bit, because of the operating system overhead.

You can learn more about why 32-bit operating systems are limited to ~4GB of RAM here: https://superuser.com/questions/372881/is-there-a-technical-reason-why-32-bit-windows-is-limited-to-4gb-of-ram

How to send UTF-8 email?

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
    return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
    {
        mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
        "From: $form\r\n".
        "Reply-To: $reply\r\n".
        "X-Mailer: PHP/" . phpversion());
    }

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
    $s= "=?utf-8?b?".base64_encode($s)."?=";
    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
    $headers.= "Content-Type: text/plain;charset=utf-8\r\n";
    $headers.= "Reply-To: $reply\r\n";  
    $headers.= "X-Mailer: PHP/" . phpversion();
    mail($to, $s, $body, $headers);
}

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

Check that there isn't a firewall that is ending the connection after certain period of time (this was the cause of a similar problem we had)

How to create a library project in Android Studio and an application project that uses the library project

Had the same question and solved it the following way:

Start situation:

FrigoShare (root)
|-Modules:    frigoshare,   frigoShare-backend

Target: want to add a module named dataformats

  1. Add a new module (e.g.: Java Library)
  2. Make sure your settings.gradle look like this (normally automatically):

    include ':frigoshare', ':frigoShare-backend', ':dataformats'

  3. Make sure (manually) that the build.gradle files of the modules that need to use your library have the following dependency:

    dependencies { ... compile project(':dataformats') }

How to split a String by space

What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:

str = "Hello I'm your String";
String[] splited = str.split("\\s+");

This will cause any number of consecutive spaces to split your string into tokens.

As a side note, I'm not sure "splited" is a word :) I believe the state of being the victim of a split is also "split". It's one of those tricky grammar things :-) Not trying to be picky, just figured I'd pass it on!

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

Python SQLite: database is locked

I had this problem while working with Pycharm and with a database that was originally given to me by another user.

So, this is how I solve it in my case:

  1. Closed all tabs in Pycharm that operate with the problematic database.
  2. Stop all running processes from the red square botton in the top right corner of Pycharm.
  3. Delete the problematic database from the directory.
  4. Upload again the original database. And it worked again.

How can I get current date in Android?

I am providing the modern answer.

java.time and ThreeTenABP

To get the current date:

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

This gives you a LocalDate object, which is what you should use for keeping a date in your program. A LocalDate is a date without time of day.

Only when you need to display the date to a user, format it into a string suitable for the user’s locale:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

When I ran this snippet today in US English locale, output was:

July 13, 2019

If you want it shorter, specify FormatStyle.MEDIUM or even FormatStyle.SHORT. DateTimeFormatter.ofLocalizedDate uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.

If your user has very special requirements for the output format, use a format pattern string:

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

13-???-2019

I am using and recommending java.time, the modern Java date and time API. DateFormat, SimpleDateFormat, Date and Calendar used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

SQL to Query text in access with an apostrophe in it

Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

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...).

How would you implement an LRU cache in Java?

Have a look at ConcurrentSkipListMap. It should give you log(n) time for testing and removing an element if it is already contained in the cache, and constant time for re-adding it.

You'd just need some counter etc and wrapper element to force ordering of the LRU order and ensure recent stuff is discarded when the cache is full.

Node.js check if path is file or directory

Here's a function that I use. Nobody is making use of promisify and await/async feature in this post so I thought I would share.

const promisify = require('util').promisify;
const lstat = promisify(require('fs').lstat);

async function isDirectory (path) {
  try {
    return (await lstat(path)).isDirectory();
  }
  catch (e) {
    return false;
  }
}

Note : I don't use require('fs').promises; because it has been experimental for one year now, better not rely on it.

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

For Chrome on Android, you can use the -webkit-tap-highlight-color CSS property:

-webkit-tap-highlight-color is a non-standard CSS property that sets the color of the highlight that appears over a link while it's being tapped. The highlighting indicates to the user that their tap is being successfully recognized, and indicates which element they're tapping on.

To remove the highlighting completely, you can set the value to transparent:

-webkit-tap-highlight-color: transparent;

Be aware that this might have consequences on accessibility: see outlinenone.com

Mapping over values in a python dictionary

Just came accross this use case. I implemented gens's answer, adding a recursive approach for handling values that are also dicts:

def mutate_dict_in_place(f, d):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            mutate_dict_in_place(f, v)
        else:
            d[k] = f(v)

# Exemple handy usage
def utf8_everywhere(d):
    mutate_dict_in_place((
        lambda value:
            value.decode('utf-8')
            if isinstance(value, bytes)
            else value
        ),
        d
    )

my_dict = {'a': b'byte1', 'b': {'c': b'byte2', 'd': b'byte3'}}
utf8_everywhere(my_dict)
print(my_dict)

This can be useful when dealing with json or yaml files that encode strings as bytes in Python 2

How to test if list element exists?

A slight modified version of @salient.salamander , if one wants to check on full path, this can be used.

Element_Exists_Check = function( full_index_path ){
  tryCatch({
    len_element = length(full_index_path)
    exists_indicator = ifelse(len_element > 0, T, F)
      return(exists_indicator)
  }, error = function(e) {
    return(F)
  })
}

How to upload and parse a CSV file in php

You can try with this:

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}

Session state can only be used when enableSessionState is set to true either in a configuration

  1. Could be your skype intercepting your requests at 80 port, in Skype options uncheck
  2. Or Your IE has connection checked for Proxy when there is no proxy
  3. Or your fiddler could intercept and act as proxy, uncheck it!

Solves the above problem, It solved mine!

HydTechie

Stopping python using ctrl+c

For the record, what killed the process on my Raspberry 3B+ (running raspbian) was Ctrl+'. On my French AZERTY keyboard, the touch ' is also number 4.

What are the sizes used for the iOS application splash screen?

With universal app I had iPad splash screen showing up in simulator but not on device. The iPad would instead show the Default.png splash for the iPhone. The Default-Landscape.png and Default-Portrait.png files existing, so wth? Resolution should be correct since I created the screen captures using Window | Organizer | Screenshots and used 'Save as Default Image' for the iPad, then just renamed it.

Turns out (from my one app anyways) the two iPad screen shots have to be moved to the Resources-iPad directory. Then it all works fine. Seems obvious now, but in case anyone else has lost sleep over this... -Larry

?: ?? Operators Instead Of IF|ELSE

I don't think you can its an operator and its suppose to return one or the other. It's not if else statement replacement although it can be use for that on certain case.

Regex expressions in Java, \\s vs. \\s+

First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.

However x.replaceAll("\\s+", ""); will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+ matches 1 or more spaces at once and replaces them with empty string.

So even though you get the same output from both it is better to use:

x.replaceAll("\\s+", "");

How to check if AlarmManager already has an alarm set?

    Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    sqlitewraper.context, 0, intent,
                    PendingIntent.FLAG_NO_CREATE);

FLAG_NO_CREATE is not create pending intent so that it gives boolean value false.

            boolean alarmUp = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_NO_CREATE) != null);

            if (alarmUp) {
                System.out.print("k");

            }

            AlarmManager alarmManager = (AlarmManager) sqlitewraper.context
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), 1000 * 60, pendingIntent);

After the AlarmManager check the value of Pending Intent it gives true because AlarmManager Update The Flag of Pending Intent.

            boolean alarmUp1 = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_UPDATE_CURRENT) != null);
            if (alarmUp1) {
                System.out.print("k");

            }

How to check whether a int is not null or empty?

I think you can initialize the variables a value like -1, because if the int type variables is not initialized it can't be used. When you want to check if it is not the value you want you can check if it is -1.

Regular expression to get a string between two strings in Javascript

The chosen answer didn't work for me...hmm...

Just add space after cow and/or before milk to trim spaces from " always gives "

/(?<=cow ).*(?= milk)/

enter image description here

Android Stop Emulator from Command Line

If you don't want to have to know the serial name of your device for adb -s emulator-5554 emu kill, then you can just use adb -e emu kill to kill a single emulator. This won't kill anything if you have more than one emulator running at once, but it's useful for automation where you start and stop a single emulator for a test.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

How do I analyze a .hprof file?

YourKit Java Profiler seems to handle them too.

What does the "On Error Resume Next" statement do?

It enables error handling. The following is partly from https://msdn.microsoft.com/en-us/library/5hsw66as.aspx

' Enable error handling. When a run-time error occurs, control goes to the statement 
' immediately following the statement where the error occurred, and execution
' continues from that point.
On Error Resume Next

SomeCodeHere

If Err.Number = 0 Then
    WScript.Echo "No Error in SomeCodeHere."
Else
  WScript.Echo "Error in SomeCodeHere: " & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

SomeMoreCodeHere

If Err.Number <> 0 Then
  WScript.Echo "Error in SomeMoreCodeHere:" & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

' Disables enabled error handler in the current procedure and resets it to Nothing.
On Error Goto 0

' There are also `On Error Goto -1`, which disables the enabled exception in the current 
' procedure and resets it to Nothing, and `On Error Goto line`, 
' which enables the error-handling routine that starts at the line specified in the 
' required line argument. The line argument is any line label or line number. If a run-time 
' error occurs, control branches to the specified line, making the error handler active. 
' The specified line must be in the same procedure as the On Error statement, 
' or a compile-time error will occur.

How to convert a string into double and vice versa?

// Converting String in to Double

double doubleValue = [yourString doubleValue];

// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal

// Converting double to int

int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

First, install QEMU. On Debian-based distributions like Ubuntu, run:

$ apt-get install qemu

Then run the following command:

$ qemu-img convert -O vmdk imagefile.dd vmdkname.vmdk

I’m assuming a flat disk image is a dd-style image. The convert operation also handles numerous other formats.

For more information about the qemu-img command, see the output of

$ qemu-img -h

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

Create an ArrayList with multiple object types?

You can just add objects of diffefent "Types" to an instance of ArrayList. No need create an ArrayList. Have a look at the below example, You will get below output:

Beginning....
Contents of array: [String, 1]
Size of the list: 2
This is not an Integer String
This is an Integer 1

package com.viswa.examples.programs;

import java.util.ArrayList;
import java.util.Arrays;

public class VarArrayListDemo {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        System.out.println(" Beginning....");

        ArrayList varTypeArray = new ArrayList();
        varTypeArray.add("String");
        varTypeArray.add(1); //Stored as Integer

        System.out.println(" Contents of array: " + varTypeArray + "\n Size of the list: " + varTypeArray.size());

        Arrays.stream(varTypeArray.toArray()).forEach(VarArrayListDemo::checkType);
    }

    private static <T> void checkType(T t) {

        if (Integer.class.isInstance(t)) {
            System.out.println(" This is an Integer " + t);
        } else {
            System.out.println(" This is not an Integer" + t);
        }
    }

}

Calculate last day of month in JavaScript

I would use an intermediate date with the first day of the next month, and return the date from the previous day:

int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);

PHP, pass array through POST

There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).

XSS

XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:

" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="

This would be written into your form like so:

<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>

The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into &lt;. For example:

<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>

You can read more about XSS here: https://www.owasp.org/index.php/XSS

Form Modification

If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.

I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).

In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.

Error 1022 - Can't write; duplicate key in table

I had this problem when creating a new table. It turns out the Foreign Key name I gave was already in use. Renaming the key fixed it.

How to remove commits from a pull request

If you're removing a commit and don't want to keep its changes @ferit has a good solution.

If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:

  1. use git rebase -i HEAD~n
  2. Swap the commit you want to remove to the bottom (most recent) position
  3. Save and exit
  4. use git reset HEAD^ --soft to uncommit the changes and get them back in a staged state.
  5. use git push --force to update the remote branch without your removed commit.

Now you'll have removed the commit from your remote, but will still have the changes locally.

Uninstall all installed gems, in OSX?

When trying to remove gems installed as root, xargs seems to halt when it encounters an error trying to uninstall a default gem:

sudo gem list | cut -d" " -f1 | xargs gem uninstall -aIx
# ERROR:  While executing gem ... (Gem::InstallError)
#    gem "test-unit" cannot be uninstalled because it is a default gem


This won't work for everyone, but here's what I used instead:

sudo for gem (`gem list | cut -d" " -f1`); do gem uninstall $gem -aIx; done

Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR

Don't rescue Exception => e (and not re-raise the exception) - or you might drive off a bridge.


Let's say you are in a car (running Ruby). You recently installed a new steering wheel with the over-the-air upgrade system (which uses eval), but you didn't know one of the programmers messed up on syntax.

You are on a bridge, and realize you are going a bit towards the railing, so you turn left.

def turn_left
  self.turn left:
end

oops! That's probably Not Good™, luckily, Ruby raises a SyntaxError.

The car should stop immediately - right?

Nope.

begin
  #...
  eval self.steering_wheel
  #...
rescue Exception => e
  self.beep
  self.log "Caught #{e}.", :warn
  self.log "Logged Error - Continuing Process.", :info
end

beep beep

Warning: Caught SyntaxError Exception.

Info: Logged Error - Continuing Process.

You notice something is wrong, and you slam on the emergency breaks (^C: Interrupt)

beep beep

Warning: Caught Interrupt Exception.

Info: Logged Error - Continuing Process.

Yeah - that didn't help much. You're pretty close to the rail, so you put the car in park (killing: SignalException).

beep beep

Warning: Caught SignalException Exception.

Info: Logged Error - Continuing Process.

At the last second, you pull out the keys (kill -9), and the car stops, you slam forward into the steering wheel (the airbag can't inflate because you didn't gracefully stop the program - you terminated it), and the computer in the back of your car slams into the seat in front of it. A half-full can of Coke spills over the papers. The groceries in the back are crushed, and most are covered in egg yolk and milk. The car needs serious repair and cleaning. (Data Loss)

Hopefully you have insurance (Backups). Oh yeah - because the airbag didn't inflate, you're probably hurt (getting fired, etc).


But wait! There's more reasons why you might want to use rescue Exception => e!

Let's say you're that car, and you want to make sure the airbag inflates if the car is exceeding its safe stopping momentum.

 begin 
    # do driving stuff
 rescue Exception => e
    self.airbags.inflate if self.exceeding_safe_stopping_momentum?
    raise
 end

Here's the exception to the rule: You can catch Exception only if you re-raise the exception. So, a better rule is to never swallow Exception, and always re-raise the error.

But adding rescue is both easy to forget in a language like Ruby, and putting a rescue statement right before re-raising an issue feels a little non-DRY. And you do not want to forget the raise statement. And if you do, good luck trying to find that error.

Thankfully, Ruby is awesome, you can just use the ensure keyword, which makes sure the code runs. The ensure keyword will run the code no matter what - if an exception is thrown, if one isn't, the only exception being if the world ends (or other unlikely events).

 begin 
    # do driving stuff
 ensure
    self.airbags.inflate if self.exceeding_safe_stopping_momentum?
 end

Boom! And that code should run anyways. The only reason you should use rescue Exception => e is if you need access to the exception, or if you only want code to run on an exception. And remember to re-raise the error. Every time.

Note: As @Niall pointed out, ensure always runs. This is good because sometimes your program can lie to you and not throw exceptions, even when issues occur. With critical tasks, like inflating airbags, you need to make sure it happens no matter what. Because of this, checking every time the car stops, whether an exception is thrown or not, is a good idea. Even though inflating airbags is a bit of an uncommon task in most programming contexts, this is actually pretty common with most cleanup tasks.

Android Studio - Failed to apply plugin [id 'com.android.application']

First of all, before trying the most complicated things you should make the step easier, in my case this bug just happened on my way until the project contained 'spaces' for example:

Replace:

C://Users/Silva Neto/OneDrive/Work space/project

With:

C://Users/SilvaNeto/OneDrive/Workspace/project

Notice that we replaced spaces with camelCase but you can choose any naming scheme you like, and hopefully this could solve your issue.

I hope this will help.

Create a GUID in Java

java.util.UUID.randomUUID();

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Java getting the Enum name given the Enum Value

Try, the following code..

    @Override
    public String toString() {
    return this.name();
    }

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

As far as I know, apart from setting the command or connection timeouts in the client, there is no way to change timeouts on a query by query basis in the server.

You can indeed change the default 600 seconds using sp_configure, but these are server scoped.

H2 database error: Database may be already in use: "Locked by another process"

H2 is still running (I can guarantee it). You need to use a TCP connection for multiple users such as ->

<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/>

OR

DriverManager.getConnection("jdbc:h2:tcp://localhost/server~/dbname","username","password");

It also means you need to start the server in TCP mode. Honesetly, it is pretty straight forward in the documentation.

Force kill the process (javaw.exe for Windows), and make sure that any application that might have started it is shut down. You have an active lock.

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

Pass table as parameter into sql server UDF

Unfortunately, there is no simple way in SQL Server 2005. Lukasz' answer is correct for SQL Server 2008 though and the feature is long overdue

Any solution would involve temp tables, or passing in xml/CSV and parsing in the UDF. Example: change to xml, parse in udf

DECLARE @psuedotable xml

SELECT
    @psuedotable = ...
FROM
    ...
FOR XML ...

SELECT ... dbo.MyUDF (@psuedotable)

What do you want to do in the bigger picture though? There may be another way to do this...

Edit: Why not pass in the query as a string and use a stored proc with output parameter

Note: this is an untested bit of code, and you'd need to think about SQL injection etc. However, it also satisfies your "one column" requirement and should help you along

CREATE PROC dbo.ToCSV (
    @MyQuery varchar(2000),
    @CSVOut varchar(max)
)
AS
SET NOCOUNT ON

CREATE TABLE #foo (bar varchar(max))

INSERT #foo
EXEC (@MyQuery)

SELECT
    @CSVOut = SUBSTRING(buzz, 2, 2000000000)
FROM
    (
    SELECT 
        bar -- maybe CAST(bar AS varchar(max))??
    FROM 
        #foo
    FOR XML PATH (',')
    ) fizz(buzz)
GO

How to get a value from a cell of a dataframe?

Not sure if this is a good practice, but I noticed I can also get just the value by casting the series as float.

e.g.

rate

3 0.042679

Name: Unemployment_rate, dtype: float64

float(rate)

0.0426789

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

Good tool to visualise database schema?

I usually use SchemaSpy to do this, but recently I found a really simple article on sqlfairy that just uses the dump file to create the structure graph

Get int from String, also containing letters, in Java

You can also use Scanner :

Scanner s = new Scanner(MyString);
s.nextInt();

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

1) Server.MapPath(".") -- Returns the "Current Physical Directory" of the file (e.g. aspx) being executed.

Ex. Suppose D:\WebApplications\Collage\Departments

2) Server.MapPath("..") -- Returns the "Parent Directory"

Ex. D:\WebApplications\Collage

3) Server.MapPath("~") -- Returns the "Physical Path to the Root of the Application"

Ex. D:\WebApplications\Collage

4) Server.MapPath("/") -- Returns the physical path to the root of the Domain Name

Ex. C:\Inetpub\wwwroot

Convert from days to milliseconds

In addition to the other answers, there is also the TimeUnit class which allows you to convert one time duration to another. For example, to find out how many milliseconds make up one day:

TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); //gives 86400000

Note that this method takes a long, so if you have a fraction of a day, you will have to multiply it by the number of milliseconds in one day.

Java 8 Lambda function that throws exception?

This is not specific to Java 8. You are trying to compile something equivalent to:

interface I {
    void m();
}
class C implements I {
    public void m() throws Exception {} //can't compile
}

What is difference between png8 and png24

Basic difference : a 8-bit PNG comprises a max. of 256 colors. PNG-24 is a loss-less format and can contain up to 16 million colors.

Impacts:

  1. If you are using any round corner image then edges might visible in png8 format.
  2. ie6 doesnt support png24 format.

Remove values from select list based on condition

The index I will change as soon as it removes the 1st element. This code will remove values 52-140 from wifi channel combo box

obj = document.getElementById("id");
if (obj)
{
        var l = obj.length;
        for (var i=0; i < l; i++)
        {
            var channel = obj.options[i].value;

            if ( channel >= 52 &&  channel <= 140 )
            {
                obj.remove(i);
                i--;//after remove the length will decrease by 1 
            }
        }
    }

How do I edit $PATH (.bash_profile) on OSX?

In Macbook, step by step:

  1. First of all open terminal and write it: cd ~/
  2. Create your bash file: touch .bash_profile

You created your ".bash_profile" file but if you would like to edit it, you should write it;

  1. Edit your bash profile: open -e .bash_profile

After you can save from top-left corner of screen: File > Save

@canerkaseler

Twitter Bootstrap inline input with dropdown

Search for the "datalist" tag.

<input list="texto_pronto" name="input_normal">
<datalist id="texto_pronto">
    <option value="texto A">
    <option value="texto B">
</datalist>

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Right-Click on your project -> Properties -> Deployment Assembly.

On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.

'Project and External Dependencies' will have all the spring related jars deployed along with your application

Add vertical whitespace using Twitter Bootstrap?

I merely created a div class using various heights i.e.

<div class="divider-10"></div>

The CSS is:

.divider-10 {
    width:100%; 
    min-height:1px; 
    margin-top:10px; 
    margin-bottom:10px;  
    display:inline-block; 
    position:relative;
}

Just create a divider class for what ever heights are needed.

Check if table exists without using "select from"

Rather than relying on errors, you can query INFORMATION_SCHEMA.TABLES to see if the table exists. If there's a record, it exists. If there's no record, it doesn't exist.

jQuery - Trigger event when an element is removed from the DOM

Hooking .remove() is not the best way to handle this as there are many ways to remove elements from the page (e.g. by using .html(), .replace(), etc).

In order to prevent various memory leak hazards, internally jQuery will try to call the function jQuery.cleanData() for each removed element regardless of the method used to remove it.

See this answer for more details: javascript memory leaks

So, for best results, you should hook the cleanData function, which is exactly what the jquery.event.destroyed plugin does:

http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js

How do I get a UTC Timestamp in JavaScript?

I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.

In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().

More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.

Restoring Nuget References?

In Visual Studio 2015 (Soulution is under source control, MVC-Project), csano's Update-Package -Reinstall -ProjectName Your.Project.Name worked, but it messed up with some write locks.

I had to delete the "packages"-Folder manually before. (It seemed to be locked because of the source control).

Also, I had to re-install the MVC-Package from the NuGet Package Manager.

How to request Administrator access inside a batch file

Here is my code! It looks big but it is mostly comment lines (the lines starting with ::).

Features:

  • Full argument forwarding
  • Does not change working folder
  • Error handling
  • Accepts paths with parenthesis (except for %TEMP% folder)
  • Supports UNC paths
  • Mapped folder check (Warn´s you if admin can´t access mapped drive)

  • Can be used as an external library (check my post at this topic: https://stackoverflow.com/a/30417025/4932683)

  • Can be called when/if needed anywhere in your code

Just attach this to the end of your batch file, or save it as a library (check above)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:RequestAdminElevation FilePath %* || goto:eof
:: 
:: By:   Cyberponk,     v1.5 - 10/06/2016 - Changed the admin rights test method from cacls to fltmc
::          v1.4 - 17/05/2016 - Added instructions for arguments with ! char
::          v1.3 - 01/08/2015 - Fixed not returning to original folder after elevation successful
::          v1.2 - 30/07/2015 - Added error message when running from mapped drive
::          v1.1 - 01/06/2015
:: 
:: Func: opens an admin elevation prompt. If elevated, runs everything after the function call, with elevated rights.
:: Returns: -1 if elevation was requested
::           0 if elevation was successful
::           1 if an error occured
:: 
:: USAGE:
:: If function is copied to a batch file:
::     call :RequestAdminElevation "%~dpf0" %* || goto:eof
::
:: If called as an external library (from a separate batch file):
::     set "_DeleteOnExit=0" on Options
::     (call :RequestAdminElevation "%~dpf0" %* || goto:eof) && CD /D %CD%
::
:: If called from inside another CALL, you must set "_ThisFile=%~dpf0" at the beginning of the file
::     call :RequestAdminElevation "%_ThisFile%" %* || goto:eof
::
:: If you need to use the ! char in the arguments, the calling must be done like this, and afterwards you must use %args% to get the correct arguments:
::      set "args=%* "
::      call :RequestAdminElevation .....   use one of the above but replace the %* with %args:!={a)%
::      set "args=%args:{a)=!%" 
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
setlocal ENABLEDELAYEDEXPANSION & set "_FilePath=%~1"
  if NOT EXIST "!_FilePath!" (echo/Read RequestAdminElevation usage information)
  :: UAC.ShellExecute only works with 8.3 filename, so use %~s1
  set "_FN=_%~ns1" & echo/%TEMP%| findstr /C:"(" >nul && (echo/ERROR: %%TEMP%% path can not contain parenthesis &pause &endlocal &fc;: 2>nul & goto:eof)
  :: Remove parenthesis from the temp filename
  set _FN=%_FN:(=%
  set _vbspath="%temp:~%\%_FN:)=%.vbs" & set "_batpath=%temp:~%\%_FN:)=%.bat"

  :: Test if we gave admin rights
  fltmc >nul 2>&1 || goto :_getElevation

  :: Elevation successful
  (if exist %_vbspath% ( del %_vbspath% )) & (if exist %_batpath% ( del %_batpath% )) 
  :: Set ERRORLEVEL 0, set original folder and exit
  endlocal & CD /D "%~dp1" & ver >nul & goto:eof

  :_getElevation
  echo/Requesting elevation...
  :: Try to create %_vbspath% file. If failed, exit with ERRORLEVEL 1
  echo/Set UAC = CreateObject^("Shell.Application"^) > %_vbspath% || (echo/&echo/Unable to create %_vbspath% & endlocal &md; 2>nul &goto:eof) 
  echo/UAC.ShellExecute "%_batpath%", "", "", "runas", 1 >> %_vbspath% & echo/wscript.Quit(1)>> %_vbspath%
  :: Try to create %_batpath% file. If failed, exit with ERRORLEVEL 1
  echo/@%* > "%_batpath%" || (echo/&echo/Unable to create %_batpath% & endlocal &md; 2>nul &goto:eof)
  echo/@if %%errorlevel%%==9009 (echo/^&echo/Admin user could not read the batch file. If running from a mapped drive or UNC path, check if Admin user can read it.)^&echo/^& @if %%errorlevel%% NEQ 0 pause >> "%_batpath%"

  :: Run %_vbspath%, that calls %_batpath%, that calls the original file
  %_vbspath% && (echo/&echo/Failed to run VBscript %_vbspath% &endlocal &md; 2>nul & goto:eof)

  :: Vbscript has been run, exit with ERRORLEVEL -1
  echo/&echo/Elevation was requested on a new CMD window &endlocal &fc;: 2>nul & goto:eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example on how to use it

:EXAMPLE
@echo off

 :: Run this script with elevation
 call :RequestAdminElevation "%~dpfs0" %* || goto:eof

  echo/I now have Admin rights!
  echo/
  echo/Arguments using %%args%%:    %args%
  echo/Arguments using %%*: %*
  echo/%%1= %~1
  echo/%%2= %~2
  echo/%%3= %~3

  echo/
  echo/Current Directory: %CD%
  echo/
  echo/This file: %0
  echo/

pause &goto:eof

[here you paste the RequestAdminElevation function code]

Array length in angularjs returns undefined

use:

$scope.users.length;

Instead of:

$scope.users.lenght;

And next time "spell-check" your code.

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

What's the difference between REST & RESTful

Think of REST as an architectural "class" while RESTful is the well known "instance" of that class.

Please mind the ""; we are not dealing with "real" programming objects here.

RESTful call in Java

Most Easy Solution will be using Apache http client library. refer following sample code.. this code uses basic security for authenticating.

Add following Dependency.

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("username", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpPost request = new HttpPost("https://api.plivo.com/v1/Account/MAYNJ3OT/Message/");HttpResponse response = client.execute(request);
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {    
    textView = textView + line;
    }
    System.out.println(textView);

Fastest way to iterate over all the chars in a String

Despite @Saint Hill's answer if you consider the time complexity of str.toCharArray(),

the first one is faster even for very large strings. You can run the code below to see it for yourself.

        char [] ch = new char[1_000_000_00];
    String str = new String(ch); // to create a large string

    // ---> from here
    long currentTime = System.nanoTime();
    for (int i = 0, n = str.length(); i < n; i++) {
        char c = str.charAt(i);
    }
    // ---> to here
    System.out.println("str.charAt(i):"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");

    /**
     *   ch = str.toCharArray() itself takes lots of time   
     */
    // ---> from here
    currentTime = System.nanoTime();
    ch = str.toCharArray();
    for (int i = 0, n = str.length(); i < n; i++) {
        char c = ch[i];
    }
    // ---> to  here
    System.out.println("ch = str.toCharArray() + c = ch[i] :"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");

output:

str.charAt(i):5.492102 (ms)
ch = str.toCharArray() + c = ch[i] :79.400064 (ms)

How to get the current logged in user Id in ASP.NET Core

use can use

string userid = User.FindFirst("id").Value;

for some reason NameIdentifier now retrieve the username (.net core 2.2)

How to check if a String contains any letter from a to z?

For a minimal change:

for(int i=0; i<str.Length; i++ )
   if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
      errorCount++;

You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.

Learning to write a compiler

I remember asking this question about seven years ago when I was rather new to programming.

I was very careful when I asked and surprisingly I didn't get as much criticism as you are getting here. They did however point me in the direction of the "Dragon Book" which is in my opinion, a really great book that explains everything you need to know to write a compiler (you will of course have to master a language or two. The more languages you know, the merrier.).

And yes, many people say reading that book is crazy and you won't learn anything from it, but I disagree completely with that.

Many people also say that writing compilers is stupid and pointless. Well, there are a number of reasons why compiler development are useful:

  • Because it's fun.
  • It's educational, when learning how to write compilers you will learn a lot about computer science and other techniques that are useful when writing other applications.
  • If nobody wrote compilers the existing languages wouldn't get any better.

I didn't write my own compiler right away, but after asking I knew where to start. And now, after learning many different languages and reading the Dragon Book, writing isn't that much of a problem. (I'm also studying computer engineering atm, but most of what I know about programming is self taught.)

In conclusion, The Dragon Book is a great "tutorial". But spend some time mastering a language or two before attempting to write a compiler. Don't expect to be a compiler guru within the next decade or so though.

The book is also good if you want to learn how to write parsers/interpreters.

Case insensitive access for generic dictionary

Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:

var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
    if (item != null)
    {
        TheValue = item.Value;
    }

trying to align html button at the center of the my page

I've really taken recently to display: table to give things a fixed size such as to enable margin: 0 auto to work. Has made my life a lot easier. You just need to get past the fact that 'table' display doesn't mean table html.

It's especially useful for responsive design where things just get hairy and crazy 50% left this and -50% that just become unmanageable.

style
{
   display: table;
   margin: 0 auto
}

JsFiddle

In addition if you've got two buttons and you want them the same width you don't even need to know the size of each to get them to be the same width - because the table will magically collapse them for you.

enter image description here

JsFiddle

(this also works if they're inline and you want to center two buttons side to side - try doing that with percentages!).

SQL "between" not inclusive

Dyamic date BETWEEN sql query

var startDate = '2019-08-22';
var Enddate = '2019-10-22'
     let sql = "SELECT * FROM Cases WHERE created_at BETWEEN '?' AND '?'";
     const users = await mysql.query( sql, [startDate, Enddate]);

Explode PHP string by new line

It doesn't matter what your system uses as newlines if the content might be generated outside of the system.

I am amazed after receiving all of these answers, that no one has simply advised the use of the \R escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R provides the most succinct and direct approach.

https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break:%20matches%20\n,%20\r%20and%20\r\n

Code: (Demo)

$text = "one\ntwo\r\nthree\rfour\r\n\nfive";

var_export(preg_split('~\R~', $text));

Output:

array (
  0 => 'one',
  1 => 'two',
  2 => 'three',
  3 => 'four',
  4 => '',
  5 => 'five',
)

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

Here is a jsfiddle HERE (not created by me) that does what you are looking for with pure css in a table. The thing to note here is the th header is set to a height of 0. Inside each th is and absolute positioned div that puts the header above the table and the scollable div that the table is in.

<thead>
  <tr>
    <th>#<div>#</div></th>
    <th>First Name<div>First Name</div></th>
    <th>Last Name<div>Last Name</div></th>
    <th>Username<div>Username</div></th>
  </tr>
</thead>

Hibernate Delete query

The reason is that for deleting an object, Hibernate requires that the object is in persistent state. Thus, Hibernate first fetches the object (SELECT) and then removes it (DELETE).

Why Hibernate needs to fetch the object first? The reason is that Hibernate interceptors might be enabled (http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html), and the object must be passed through these interceptors to complete its lifecycle. If rows are delete directly in the database, the interceptor won't run.

On the other hand, it's possible to delete entities in one single SQL DELETE statement using bulk operations:

Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();

VBA: Convert Text to Number

I had this problem earlier and this was my solution.

With Worksheets("Sheet1").Columns(5)
    .NumberFormat = "0"
    .Value = .Value
End With

How to fast get Hardware-ID in C#?

Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo

(text grabbed from original web site)
It works with C#.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

I've been having this problem too and I'm not sure why. Some people suggest removing your Google account and re-adding it and/or deleting the Play Store cache. I'm looking for more solutions, but it happens for all apps free, paid, whatever.

EDIT: just found this http://www.droid-life.com/2012/11/14/after-4-2-update-is-your-nexus-7-having-troubles-updating-apps-in-google-play/

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

How to enable TLS 1.2 in Java 7

You should probably be looking to the configuration that controls the underlying platform TLS implementation via -Djdk.tls.client.protocols=TLSv1.2.

Best way to change the background color for an NSView

If you setWantsLayer to YES first, you can directly manipulate the layer background.

[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Giving UIView rounded corners

if round corner not working in viewDidload() it's better to write code in viewDidLayoutSubview()

-(void)viewDidLayoutSubviews
{
    viewTextfield.layer.cornerRadius = 10.0 ;                                               
    viewTextfield.layer.borderWidth = 1.0f;
    viewTextfield.layer.masksToBounds =  YES;
    viewTextfield.layer.shadowRadius = 5;
    viewTextfield.layer.shadowOpacity = 0.3;
    viewTextfield.clipsToBounds = NO;
    viewTextfield.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
}

Hope this helps!

Show git diff on file in staging area

In order to see the changes that have been staged already, you can pass the -–staged option to git diff (in pre-1.6 versions of Git, use –-cached).

git diff --staged
git diff --cached

Why doesn't TFS get latest get the latest?

Unfortunately, there has to be one or more bugs in TFS 2008, since this problem regularly crop up on developer machines and build servers where I work as well.

I can do Get Latest, I can see in the history list of the project that there have been commits after I last did a Get Latest, I have not touched the files on disk in any way, but after the "Get Latest" function has completed, when I check the TFS tab, some of the files still says that they're not the latest version.

Obviously TFS is able to determine that I have old files locally, since the list says so. Yet, Get Latest fails to do that, get the latest version. If I do what you did, use the Get Specific version, and check the two checkboxes at the bottom of the dialog, then the files are retrieved.

We changed our build servers to always use the Get Specific version type of function instead, so this part now works, but since our build server (TeamCity) also relies on checking if there have been changes to the files in order to kick off a build, sometimes it lapses into a "nothing changed, nothing to see here, move along" mode and does nothing until we forcibly run the build configuration.

Note that I have experienced this problem on a machine that is never touched, except for get latest + build, both manually, so there's nothing tampering with the files. It's just TFS getting confused.

One time this cropped up I verified that the files on disk was indeed binary identical to the version previously retrieved, so no manual tampering had been done with the files.

Also, I fail to see how TFS can "know" whether files have changed on disk or not without actually looking at the contents. If one part of TFS can see that the files are indeed not the latest version, then the Get Latest version should absolutely be able to get the latest version. This in reference to comments to other answers here.

Changing the page title with Jquery

I use this one:

document.title = "your_customize_title";

How to playback MKV video in web browser?

You can use this following code. work just on chrome browser.

_x000D_
_x000D_
 function failed(e) {_x000D_
   // video playback failed - show a message saying why_x000D_
   switch (e.target.error.code) {_x000D_
     case e.target.error.MEDIA_ERR_ABORTED:_x000D_
       alert('You aborted the video playback.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_NETWORK:_x000D_
       alert('A network error caused the video download to fail part-way.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_DECODE:_x000D_
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
       break;_x000D_
     default:_x000D_
       alert('An unknown error occurred.');_x000D_
       break;_x000D_
   }_x000D_
 }
_x000D_
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
 <meta name="author" content="Amin Developer!" />_x000D_
_x000D_
 <title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Register DLL file on Windows Server 2008 R2

That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.

What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.

To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.

How would one write object-oriented code in C?

Object oriented C, can be done, I've seen that type of code in production in Korea, and it was the most horrible monster I'd seen in years (this was like last year(2007) that I saw the code). So yes it can be done, and yes people have done it before, and still do it even in this day and age. But I'd recommend C++ or Objective-C, both are languages born from C, with the purpose of providing object orientation with different paradigms.

Maximum number of rows in an MS Access database engine table?

Here's my attempt:

I created a single-column (INTEGER) table with no key:

CREATE TABLE a (a INTEGER NOT NULL);

Inserted integers in sequence starting at 1.

I stopped it (arbitrarily after many hours) when it had inserted 65,632,875 rows. The file size was 1,029,772 KB.

I compacted the file which reduced it very slightly to 1,029,704 KB.

I added a PK:

ALTER TABLE a ADD CONSTRAINT p PRIMARY KEY (a);

which increased the file size to 1,467,708 KB.

This suggests the maximum is somewhere around the 80 million mark.

Is there a list of Pytz Timezones?

In my opinion this is a design flaw of pytz library. It should be more reliable to specify a timezone using the offset, e.g.

pytz.construct("UTC-07:00")

which gives you Canada/Pacific timezone.

Remove duplicates from a List<T> in C#

As a helper method (without Linq):

public static List<T> Distinct<T>(this List<T> list)
{
    return (new HashSet<T>(list)).ToList();
}

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

How to generate a simple popup using jQuery

Try the Magnific Popup, it's responsive and weights just around 3KB.

TSQL CASE with if comparison in SELECT statement

You can try with this:

WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID  as UserID FROM Articles A
           Inner Join Users U
           on  A.userId = U.userId 
           Group By A.userId , U.userId   ),

B as (Select us.registrationDate,

      CASE
         WHEN CTE_A.articleNumber < 2 THEN 'Ama'
         WHEN CTE_A.articleNumber < 5 THEN 'SemiAma' 
         WHEN CTE_A.articleNumber < 7 THEN 'Good'  
         WHEN CTE_A.articleNumber < 9 THEN 'Better' 
         WHEN CTE_A.articleNumber < 12 THEN 'Best'
         ELSE 'Outstanding'
         END as Ranking,
         us.hobbies, etc...
         FROM USERS Us Inner Join CTE_A 
         on CTE_A.UserID=us.UserID)

Select * from B

How do I get the current username in .NET using C#?

I tried several combinations from existing answers, but they were giving me

DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool

I ended up using

string vUserName = User.Identity.Name;

Which gave me the actual users domain username only.

Best way to convert an ArrayList to a string

Android has a TextUtil class you can use http://developer.android.com/reference/android/text/TextUtils.html

String implode = TextUtils.join("\t", list);

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

if The given id is not exist in the DB ,then you may get this exception.

Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Add JsonArray to JsonObject

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

SQL Error with Order By in Subquery

A subquery (nested view) as you have it returns a dataset that you can then order in your calling query. Ordering the subquery itself will make no (reliable) difference to the order of the results in your calling query.

As for your SQL itself: a) I seen no reason for an order by as you are returning a single value. b) I see no reason for the sub query anyway as you are only returning a single value.

I'm guessing there is a lot more information here that you might want to tell us in order to fix the problem you have.

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

How to implement a SQL like 'LIKE' operator in java?

Check out https://github.com/hrakaroo/glob-library-java.

It's a zero dependency library in Java for doing glob (and sql like) type of comparisons. Over a large data set it is faster than translating to a regular expression.

Basic syntax

MatchingEngine m = GlobPattern.compile("dog%cat\%goat_", '%', '_', GlobPattern.HANDLE_ESCAPES);
if (m.matches(str)) { ... }

Android list view inside a scroll view

Update

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:fillViewport="true"
android:gravity="top" >

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

to

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:fillViewport="true"
android:gravity="top" >

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

The point here is you are trying to set height to 0dp (fixed)

Git: How to reset a remote Git repository to remove all commits?

Were I you I would do something like this:

Before doing anything please keep a copy (better safe than sorry)

git checkout master
git checkout -b temp 
git reset --hard <sha-1 of your first commit> 
git add .
git commit -m 'Squash all commits in single one'
git push origin temp

After doing that you can delete other branches.

Result: You are going to have a branch with only 2 commits.

Use git log --oneline to see your commits in a minimalistic way and to find SHA-1 for commits!

Get random item from array

Use PHP Rand function

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>

More Help

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

Freeze the top row for an html table only (Fixed Table Header Scrolling)

My concern was not to have the cells with fixed width. Which seemed to be not working in any case. I found this solution which seems to be what I need. I am posting it here for others who are searching of a way. Check out this fiddle

Working Snippet:

_x000D_
_x000D_
html, body{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
}_x000D_
section {_x000D_
  position: relative;_x000D_
  border: 1px solid #000;_x000D_
  padding-top: 37px;_x000D_
  background: #500;_x000D_
}_x000D_
section.positioned {_x000D_
  position: absolute;_x000D_
  top:100px;_x000D_
  left:100px;_x000D_
  width:800px;_x000D_
  box-shadow: 0 0 15px #333;_x000D_
}_x000D_
.container {_x000D_
  overflow-y: auto;_x000D_
  height: 160px;_x000D_
}_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  width:100%;_x000D_
}_x000D_
td + td {_x000D_
  border-left:1px solid #eee;_x000D_
}_x000D_
td, th {_x000D_
  border-bottom:1px solid #eee;_x000D_
  background: #ddd;_x000D_
  color: #000;_x000D_
  padding: 10px 25px;_x000D_
}_x000D_
th {_x000D_
  height: 0;_x000D_
  line-height: 0;_x000D_
  padding-top: 0;_x000D_
  padding-bottom: 0;_x000D_
  color: transparent;_x000D_
  border: none;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
th div{_x000D_
  position: absolute;_x000D_
  background: transparent;_x000D_
  color: #fff;_x000D_
  padding: 9px 25px;_x000D_
  top: 0;_x000D_
  margin-left: -25px;_x000D_
  line-height: normal;_x000D_
  border-left: 1px solid #800;_x000D_
}_x000D_
th:first-child div{_x000D_
  border: none;_x000D_
}
_x000D_
<section class="">_x000D_
  <div class="container">_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr class="header">_x000D_
          <th>_x000D_
            Table attribute name_x000D_
            <div>Table attribute name</div>_x000D_
          </th>_x000D_
          <th>_x000D_
            Value_x000D_
            <div>Value</div>_x000D_
          </th>_x000D_
          <th>_x000D_
            Description_x000D_
            <div>Description</div>_x000D_
          </th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>align</td>_x000D_
          <td>left, center, right</td>_x000D_
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>bgcolor</td>_x000D_
          <td>rgb(x,x,x), #xxxxxx, colorname</td>_x000D_
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>border</td>_x000D_
          <td>1,""</td>_x000D_
          <td>Specifies whether the table cells should have borders or not</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>cellpadding</td>_x000D_
          <td>pixels</td>_x000D_
          <td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>cellspacing</td>_x000D_
          <td>pixels</td>_x000D_
          <td>Not supported in HTML5. Specifies the space between cells</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>frame</td>_x000D_
          <td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>_x000D_
          <td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>rules</td>_x000D_
          <td>none, groups, rows, cols, all</td>_x000D_
          <td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>summary</td>_x000D_
          <td>text</td>_x000D_
          <td>Not supported in HTML5. Specifies a summary of the content of a table</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>width</td>_x000D_
          <td>pixels, %</td>_x000D_
          <td>Not supported in HTML5. Specifies the width of a table</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

hide/show a image in jquery

With image class name:

$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image

With image Id :

$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image

How to remove illegal characters from path and filenames?

Scanning over the answers here, they all** seem to involve using a char array of invalid filename characters.

Granted, this may be micro-optimising - but for the benefit of anyone who might be looking to check a large number of values for being valid filenames, it's worth noting that building a hashset of invalid chars will bring about notably better performance.

I have been very surprised (shocked) in the past just how quickly a hashset (or dictionary) outperforms iterating over a list. With strings, it's a ridiculously low number (about 5-7 items from memory). With most other simple data (object references, numbers etc) the magic crossover seems to be around 20 items.

There are 40 invalid characters in the Path.InvalidFileNameChars "list". Did a search today and there's quite a good benchmark here on StackOverflow that shows the hashset will take a little over half the time of an array/list for 40 items: https://stackoverflow.com/a/10762995/949129

Here's the helper class I use for sanitising paths. I forget now why I had the fancy replacement option in it, but it's there as a cute bonus.

Additional bonus method "IsValidLocalPath" too :)

(** those which don't use regular expressions)

public static class PathExtensions
{
    private static HashSet<char> _invalidFilenameChars;
    private static HashSet<char> InvalidFilenameChars
    {
        get { return _invalidFilenameChars ?? (_invalidFilenameChars = new HashSet<char>(Path.GetInvalidFileNameChars())); }
    }


    /// <summary>Replaces characters in <c>text</c> that are not allowed in file names with the 
    /// specified replacement character.</summary>
    /// <param name="text">Text to make into a valid filename. The same string is returned if 
    /// it is valid already.</param>
    /// <param name="replacement">Replacement character, or NULL to remove bad characters.</param>
    /// <param name="fancyReplacements">TRUE to replace quotes and slashes with the non-ASCII characters ” and /.</param>
    /// <returns>A string that can be used as a filename. If the output string would otherwise be empty, "_" is returned.</returns>
    public static string ToValidFilename(this string text, char? replacement = '_', bool fancyReplacements = false)
    {
        StringBuilder sb = new StringBuilder(text.Length);
        HashSet<char> invalids = InvalidFilenameChars;
        bool changed = false;

        for (int i = 0; i < text.Length; i++)
        {
            char c = text[i];
            if (invalids.Contains(c))
            {
                changed = true;
                char repl = replacement ?? '\0';
                if (fancyReplacements)
                {
                    if (c == '"') repl = '”'; // U+201D right double quotation mark
                    else if (c == '\'') repl = '’'; // U+2019 right single quotation mark
                    else if (c == '/') repl = '/'; // U+2044 fraction slash
                }
                if (repl != '\0')
                    sb.Append(repl);
            }
            else
                sb.Append(c);
        }

        if (sb.Length == 0)
            return "_";

        return changed ? sb.ToString() : text;
    }


    /// <summary>
    /// Returns TRUE if the specified path is a valid, local filesystem path.
    /// </summary>
    /// <param name="pathString"></param>
    /// <returns></returns>
    public static bool IsValidLocalPath(this string pathString)
    {
        // From solution at https://stackoverflow.com/a/11636052/949129
        Uri pathUri;
        Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri);
        return isValidUri && pathUri != null && pathUri.IsLoopback;
    }
}

Access Google's Traffic Data through a Web Service

Apparently the information is available using the Google Directions API in its professional edition Maps for work. According to the API's documentation:

Note: Maps for Work users must include client and signature parameters with their requests instead of a key.
[...]
duration_in_traffic indicates the total duration of this leg, taking into account current traffic conditions. The duration in traffic will only be returned if all of the following are true:

  • The directions request includes a departure_time parameter set to a value within a few minutes of the current time.
  • The request includes a valid Google Maps API for Work client and signature parameter.
  • Traffic conditions are available for the requested route.
  • The directions request does not include stopover waypoints.

How to find length of dictionary values

d={1:'a',2:'b'}
sum=0
for i in range(0,len(d),1):
   sum=sum+1
i=i+1
print i

OUTPUT=2

How to start debug mode from command prompt for apache tomcat server?

A short answer is to add the following options when the JVM is started.

JAVA_OPTS=" $JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8080"

Where do you include the jQuery library from? Google JSAPI? CDN?

Without a doubt I choose to have JQuery served by Google API servers. I didn't go with the jsapi method since I don't leverage any other Google API's, however if that ever changed then I would consider it...

First: The Google api servers are distributed across the world instead of my single server location: Closer servers usually means faster response times for the visitor.

Second: Many people choose to have JQuery hosted on Google, so when a visitor comes to my site they may already have the JQuery script in their local cache. Pre-cached content usually means faster load times for the visitor.

Third: My web hosting company charges me for the bandwidth used. No sense consuming 18k per user session if the visitor can get the same file elsewhere.

I understand that I place a portion of trust on Google to serve the correct script file, and to be online and available. Up to this point I haven't been disappointed with using Google and will continue this configuration until it makes sense not to.

One thing worth pointing out... If you have a mixture of secure and insecure pages on your site you might want to dynamically change the Google source to avoid the usual warning you see when loading insecure content in a secure page:

Here's what I came up with:

<script type="text/javascript">
    document.write([
        "\<script src='",
        ("https:" == document.location.protocol) ? "https://" : "http://",
        "ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' type='text/javascript'>\<\/script>" 
    ].join(''));
</script>

UPDATE 9/8/2010 - Some suggestions have been made to reduce the complexity of the code by removing the HTTP and HTTPS and simply use the following syntax:

<script type="text/javascript">
    document.write("\<script src='//ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' type='text/javascript'>\<\/script>");
</script>

In addition you could also change the url to reflect the jQuery major number if you wanted to make sure that the latest Major version of the jQuery libraries were loaded:

<script type="text/javascript">
    document.write("\<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'>\<\/script>");
</script>

Finally, if you don't want to use Google and would prefer jQuery you could use the following source path (keep in mind that jQuery doesn't support SSL connections):

<script type="text/javascript">
    document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
</script>

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

AngularJS Error: $injector:unpr Unknown Provider

app.factory('getSettings', ['$http','$q' /*here!!!*/,function($http, $q) {

you need to declare ALL your dependencies OR none and you forgot to declare $q .

edit:

controller.js : login, dont return ""

Use CASE statement to check if column exists in table - SQL Server

Final answer was a combination of two of the above (I've upvoted both to show my appreciation!):

select case 
   when exists (
      SELECT 1 
      FROM Sys.columns c 
      WHERE c.[object_id] = OBJECT_ID('dbo.Tags') 
         AND c.name = 'ModifiedByUserId'
   ) 
   then 1 
   else 0 
end

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

Simplest code for array intersection in javascript

Here is underscore.js implementation:

_.intersection = function(array) {
  if (array == null) return [];
  var result = [];
  var argsLength = arguments.length;
  for (var i = 0, length = array.length; i < length; i++) {
    var item = array[i];
    if (_.contains(result, item)) continue;
    for (var j = 1; j < argsLength; j++) {
      if (!_.contains(arguments[j], item)) break;
    }
    if (j === argsLength) result.push(item);
  }
  return result;
};

Source: http://underscorejs.org/docs/underscore.html#section-62

Custom height Bootstrap's navbar

For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..

<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    <div class="navbar-collapse collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
        </ul>
    </div>
</nav>

Bootstrap 4 Navbar Height Demo

Java String remove all non numeric characters

For the Android folks coming here for Kotlin

val dirtyString = " Account Balance: $-12,345.67"
val cleanString = dirtyString.replace("[^\\d.]".toRegex(), "")

Output:

cleanString = "12345.67"

This could then be safely converted toDouble(), toFloat() or toInt() if needed

What is a "static" function in C?

The following is about plain C functions - in a C++ class the modifier 'static' has another meaning.

If you have just one file, this modifier makes absolutely no difference. The difference comes in bigger projects with multiple files:

In C, every "module" (a combination of sample.c and sample.h) is compiled independently and afterwards every of those compiled object files (sample.o) are linked together to an executable file by the linker.

Let's say you have several files that you include in your main file and two of them have a function that is only used internally for convenience called add(int a, b) - the compiler would easily create object files for those two modules, but the linker will throw an error, because it finds two functions with the same name and it does not know which one it should use (even if there's nothing to link, because they aren't used somewhere else but in it's own file).

This is why you make this function, which is only used internal, a static function. In this case the compiler does not create the typical "you can link this thing"-flag for the linker, so that the linker does not see this function and will not generate an error.

Error type 3 Error: Activity class {} does not exist

If you test your app on a smartphone, which has 24 hours secure app remove (like LG G6) you have to uninstall app manually in settings, because it is in bin for 24 hours after uninstalling, so Android Studio thinks that app is installed, but it is in app thrash on your smartphone. It worked for me.

C++ pass an array by reference

As you are using C++, the obligatory suggestion that's still missing here, is to use std::vector<double>.

You can easily pass it by reference:

void foo(std::vector<double>& bar) {}

And if you have C++11 support, also have a look at std::array.

For reference:

Command-line tool for finding out who is locking a file

enter image description here

Computer Management->Shared Folders->Open Files

Passing variable number of arguments around

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

For those who like Debian and prepackaged Java:

sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
sudo dpkg-reconfigure --force ca-certificates  # check your cert in curses GUI!
sudo update-ca-certificates --fresh --verbose

Don't forget to check /etc/default/cacerts for:

# enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
cacerts_updates=yes

To remove cert:

sudo rm /usr/share/ca-certificates/test/test.loc.crt
sudo rm /etc/ssl/certs/java/cacerts
sudo update-ca-certificates --fresh --verbose

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

angularjs getting previous route path

@andresh For me locationChangeSuccess worked instead of routeChangeSuccess.

//Go back to the previous stage with this back() call
var history = [];
$rootScope.$on('$locationChangeSuccess', function() {
    history.push($location.$$path);
});

$rootScope.back = function () {
          var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
          $location.path(prevUrl);
          history = []; //Delete history array after going back
      };

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

Well I guess you can always use:

np.log   -->  natural log
np.log10 -->  base 10
np.log2  -->  base 2

Slightly modifying IanVS's answer:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x, a, b, c):
  #return a * np.exp(-b * x) + c
  return a * np.log(b * x) + c

x = np.linspace(1,5,50)   # changed boundary conditions to avoid division by 0
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))

popt, pcov = curve_fit(func, x, yn)

plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()

This results in the following graph:

enter image description here

How to replace comma with a dot in the number (or any replacement)

Per the docs, replace returns the new string - it does not modify the string you pass it.

var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);

event.preventDefault() function not working in IE

if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

Tested on IE 9 and Chrome.

Android background music service

I have found two great resources to share, if anyone else come across this thread via Google, this may help them ( 2018 ). One is this video tutorial in which you'll see practically how service works, this is good for starters.

Link :- https://www.youtube.com/watch?v=p2ffzsCqrs8

Other is this website which will really help you with background audio player.

Link :- https://www.dev2qa.com/android-play-audio-file-in-background-service-example/

Good Luck :)

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:

Sub CopyPartOfFilteredRange()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim filterRange As Range
    Dim copyRange As Range
    Dim lastRow As Long

    Set src = ThisWorkbook.Sheets("Sheet1")
    Set tgt = ThisWorkbook.Sheets("Sheet2")

    ' turn off any autofilters that are already set
    src.AutoFilterMode = False

    ' find the last row with data in column A
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    ' the range that we are auto-filtering (all columns)
    Set filterRange = src.Range("A1:C" & lastRow)

    ' the range we want to copy (only columns we want to copy)
    ' in this case we are copying country from column A
    ' we set the range to start in row 2 to prevent copying the header
    Set copyRange = src.Range("A2:A" & lastRow)

    ' filter range based on column B
    filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"

    ' copy the visible cells to our target range
    ' note that you can easily find the last populated row on this sheet
    ' if you don't want to over-write your previous results
    copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")

End Sub

Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False is not necessary.

How to find sum of several integers input by user using do/while, While statement or For statement

Do note that if you're adding stuff, you might always want to check that you're not going beyond the limits of int (especially in homework exercises). Also, int main () should return an int.

Using a "do .. while" loop:

#include<iostream>
using namespace std; 
int main () 
{

  int sum = 0;
  int previous = 0;
  int number;
  int numberitems;
  int count = 0;

  cout << "Enter number of items: ";
  cin >> numberitems;

  if ( numberitems <= 0 ) 
  {
    //no request to perform sum
    cout << "Quitting without summing.\n\n";
    return 0;
  }

  do
  {
    cout << "Enter number to add : ";
    cin >> number; 

    sum+=number;

    // check here that the addition didn't break anything.
    // Negative + negative should stay negative, positive + postive should stay positive
    if ((number > 0 && previous > 0 && sum < 0) || (number < 0 && previous < 0 && sum > 0))
    {
      cout << "Error: Beyond int limits !!";
      return 1;
    }

    count++;
    previous = sum;

  }
  while ( count < numberitems);

  cout<<"sum is: "<< sum<<endl;

  return 0;
} 

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

If @papigee does solution doesn't work, maybe you don't have the permissions.

I tried @papigee solution but does't work without sudo.

I did :

sudo docker exec -it <container id or name> /bin/sh

How to press/click the button using Selenium if the button does not have the Id?

use the text and value attributes instead of the id

driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();

similarly for Next.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Converting user input string to regular expression

Thanks to earlier answers, this blocks serves well as a general purpose solution for applying a configurable string into a RegEx .. for filtering text:

var permittedChars = '^a-z0-9 _,.?!@+<>';
permittedChars = '[' + permittedChars + ']';

var flags = 'gi';
var strFilterRegEx = new RegExp(permittedChars, flags);

log.debug ('strFilterRegEx: ' + strFilterRegEx);

strVal = strVal.replace(strFilterRegEx, '');
// this replaces hard code solt:
// strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');

NSURLSession/NSURLConnection HTTP load failed on iOS 9

I found solution from here. And its working for me.

Check this, it may help you.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
         <dict>
             <key>myDomain.com</key>
                    <dict>
                      <!--Include to allow subdomains-->
                      <key>NSIncludesSubdomains</key>
                      <true/>
                      <!--Include to allow HTTP requests-->
                      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                      <true/>
                      <!--Include to specify minimum TLS version-->
                      <key>NSTemporaryExceptionMinimumTLSVersion</key>
                      <string>TLSv1.1</string>
                </dict>
          </dict>
</dict>

How do I read a date in Excel format in Python?

Incase you're using pandas and your read_excel reads in Date formatted as Excel numbers improperly and need to recover the real dates behind...

The lambda function applied on the column uses xlrd to recover the date back

import xlrd
df['possible_intdate'] = df['possible_intdate'].apply(lambda s: xlrd.xldate.xldate_as_datetime(s, 0))


>> df['possible_intdate']

   dtype('<M8[ns]')

How to get the selected row values of DevExpress XtraGrid?

Here is the way that I've followed,

int[] selRows = ((GridView)gridControl1.MainView).GetSelectedRows();
DataRowView selRow = (DataRowView)(((GridView)gridControl1.MainView).GetRow(selRows[0]));
txtName.Text = selRow["name"].ToString();

Also you can iterate through selected rows using the selRows array. Here the code describes how to get data only from first selected row. You can insert these code lines to click event of the grid.

What is the size of a boolean variable in Java?

It's virtual machine dependent.

How can I delete a query string parameter in JavaScript?

Modern browsers provide URLSearchParams interface to work with search params. Which has delete method that removes param by name.

_x000D_
_x000D_
if (typeof URLSearchParams !== 'undefined') {_x000D_
  const params = new URLSearchParams('param1=1&param2=2&param3=3')_x000D_
  _x000D_
  console.log(params.toString())_x000D_
  _x000D_
  params.delete('param2')_x000D_
  _x000D_
  console.log(params.toString())_x000D_
_x000D_
} else {_x000D_
  console.log(`Your browser ${navigator.appVersion} does not support URLSearchParams`)_x000D_
}
_x000D_
_x000D_
_x000D_

Bash: Syntax error: redirection unexpected

do it the simpler way,

direc=$(basename `pwd`)

Or use the shell

$ direc=${PWD##*/}

Reading file using fscanf() in C

scanf() and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:

#include <stdio.h>
#include <errno.h>
#include <stdbool.h>

int main(void)
{
    char item[9], status;

    FILE *fp;

    if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
        printf("No such file\n");
        exit(1);
    }

    while (true) {
        int ret = fscanf(fp, "%s %c", item, &status);
        if(ret == 2)
            printf("\n%s \t %c", item, status);
        else if(errno != 0) {
            perror("scanf:");
            break;
        } else if(ret == EOF) {
            break;
        } else {
            printf("No match.\n");
        }
    }
    printf("\n");
    if(feof(fp)) {
        puts("EOF");
    }
    return 0;
}

TypeError: method() takes 1 positional argument but 2 were given

It occurs when you don't specify the no of parameters the __init__() or any other method looking for.

For example:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme, it gives you an error like that:

TypeError: __init__() takes 1 positional argument but 6 were given

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

select2 changing items dynamically

For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830

How to write a basic swap function in Java

You can swap variables with or without using a temporary variable.

Here is an article that provides multiple methods to swap numbers without temp variable :

http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/

Bad Request, Your browser sent a request that this server could not understand

If you use Apache httpd web server in version above 2.2.15-60, then it could be also because of underscore _ in hostname.

https://ma.ttias.be/apache-httpd-2-2-15-60-underscores-hostnames-now-blocked/

How to move from one fragment to another fragment on click of an ImageView in Android?

When you are inside an activity and need to go to a fragment use below

getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

But when you are inside a fragment and need to go to a fragment then just add a getActivity(). before, so it would become

getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

as simple as that.

The *TO_BE_REPLACED_LAYOUT_ID* can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout .

@Cacheable key on multiple method arguments

This will work

@Cacheable(value="bookCache", key="#checkwarehouse.toString().append(#isbn.toString())")

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

Active Menu Highlight CSS

As the given tag to this question is CSS, I will provide the way I accomplished it.

  1. Create a class in the .css file.

    a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

  2. Nav-bar will be like:

    • Home
    • Contact Us
    • About Us

NOTE: If you are already setting the style for all Nav-Bar elements using a class, you can cascade the special-case class we created with a white-space after the generic class in the html-tag.

Example: Here, I was already importing my style from a class called 'navList' I created for all list-items . But the special-case styling-attributes are part of class 'activePage'

.CSS file:

a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

.HTML file:

<div id="sub-header">
    <ul>
        <li> <a href="index.php" class= "navList activePage" >Home</a> </li>
        <li> <a href="contact.php" class= "navList">Contact Us</a> </li>
        <li> <a href="about.php" class= "navList">About Us</a> </li>
    </ul>
</div>

Look how I've cascaded one class-name behind other.

How to delete multiple rows in SQL where id = (x to y)

If you need to delete based on a list, you can use IN:

DELETE FROM your_table
WHERE id IN (value1, value2, ...);

If you need to delete based on the result of a query, you can also use IN:

DELETE FROM your_table
WHERE id IN (select aColumn from ...);

(Notice that the subquery must return only one column)

If you need to delete based on a range of values, either you use BETWEEN or you use inequalities:

DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;

or

DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;

git stash changes apply to new branch?

Since you've already stashed your changes, all you need is this one-liner:

  • git stash branch <branchname> [<stash>]

From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):

Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.

This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.

How to see the proxy settings on windows?

An update to @rleelr:
It's possible to view proxy settings in Google Chrome:

chrome://net-internals/#http2

Then select

View live HTTP/2 sessions

Then select one of the live sessions (you need to have some tabs open). There you find:

[...]
t=504112 [st= 0] +HTTP2_SESSION  [dt=?]
                  --> host = "play.google.com:443"
                  --> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
                              ============================

Create a view with ORDER BY clause

I'm not sure what you think this ORDER BY is accomplishing? Even if you do put ORDER BY in the view in a legal way (e.g. by adding a TOP clause), if you just select from the view, e.g. SELECT * FROM dbo.TopUsersTest; without an ORDER BY clause, SQL Server is free to return the rows in the most efficient way, which won't necessarily match the order you expect. This is because ORDER BY is overloaded, in that it tries to serve two purposes: to sort the results and to dictate which rows to include in TOP. In this case, TOP always wins (though depending on the index chosen to scan the data, you might observe that your order is working as expected - but this is just a coincidence).

In order to accomplish what you want, you need to add your ORDER BY clause to the queries that pull data from the view, not to the code of the view itself.

So your view code should just be:

CREATE VIEW [dbo].[TopUsersTest] 
AS 
  SELECT 
    u.[DisplayName], SUM(a.AnswerMark) AS Marks
  FROM
    dbo.Users_Questions AS uq
    INNER JOIN [dbo].[Users] AS u
      ON u.[UserID] = us.[UserID] 
    INNER JOIN [dbo].[Answers] AS a
      ON a.[AnswerID] = uq.[AnswerID]
    GROUP BY u.[DisplayName];

The ORDER BY is meaningless so should not even be included.


To illustrate, using AdventureWorks2012, here is an example:

CREATE VIEW dbo.SillyView
AS
  SELECT TOP 100 PERCENT 
    SalesOrderID, OrderDate, CustomerID , AccountNumber, TotalDue
  FROM Sales.SalesOrderHeader
  ORDER BY CustomerID;
GO

SELECT SalesOrderID, OrderDate, CustomerID, AccountNumber, TotalDue
FROM dbo.SillyView;

Results:

SalesOrderID   OrderDate   CustomerID   AccountNumber   TotalDue
------------   ----------  ----------   --------------  ----------
43659          2005-07-01  29825        10-4020-000676  23153.2339
43660          2005-07-01  29672        10-4020-000117  1457.3288
43661          2005-07-01  29734        10-4020-000442  36865.8012
43662          2005-07-01  29994        10-4020-000227  32474.9324
43663          2005-07-01  29565        10-4020-000510  472.3108

And you can see from the execution plan that the TOP and ORDER BY have been absolutely ignored and optimized away by SQL Server:

enter image description here

There is no TOP operator at all, and no sort. SQL Server has optimized them away completely.

Now, if you change the view to say ORDER BY SalesID, you will then just happen to get the ordering that the view states, but only - as mentioned before - by coincidence.

But if you change your outer query to perform the ORDER BY you wanted:

SELECT SalesOrderID, OrderDate, CustomerID, AccountNumber, TotalDue
FROM dbo.SillyView
ORDER BY CustomerID;

You get the results ordered the way you want:

SalesOrderID   OrderDate   CustomerID   AccountNumber   TotalDue
------------   ----------  ----------   --------------  ----------
43793          2005-07-22  11000        10-4030-011000  3756.989
51522          2007-07-22  11000        10-4030-011000  2587.8769
57418          2007-11-04  11000        10-4030-011000  2770.2682
51493          2007-07-20  11001        10-4030-011001  2674.0227
43767          2005-07-18  11001        10-4030-011001  3729.364

And the plan still has optimized away the TOP/ORDER BY in the view, but a sort is added (at no small cost, mind you) to present the results ordered by CustomerID:

enter image description here

So, moral of the story, do not put ORDER BY in views. Put ORDER BY in the queries that reference them. And if the sorting is expensive, you might consider adding/changing an index to support it.

How to move (and overwrite) all files from one directory to another?

It's just mv srcdir/* targetdir/.

If there are too many files in srcdir you might want to try something like the following approach:

cd srcdir
find -exec mv {} targetdir/ +

In contrast to \; the final + collects arguments in an xargs like manner instead of executing mv once for every file.

How to copy files from 'assets' folder to sdcard?

You can do it in few steps using Kotlin, Here I am copying only few files instead of all from asstes to my apps files directory.

private fun copyRelatedAssets() {
    val assets = arrayOf("myhome.html", "support.css", "myscript.js", "style.css")
    assets.forEach {
        val inputStream = requireContext().assets.open(it)
        val nameSplit = it.split(".")
        val name = nameSplit[0]
        val extension = nameSplit[1]
        val path = inputStream.getFilePath(requireContext().filesDir, name, extension)
        Log.v(TAG, path)
    }
}

And here is the extension function,

fun InputStream.getFilePath(dir: File, name: String, extension: String): String {
    val file = File(dir, "$name.$extension")
    val outputStream = FileOutputStream(file)
    this.copyTo(outputStream, 4096)
    return file.absolutePath
}

LOGCAT

/data/user/0/com.***.***/files/myhome.html
/data/user/0/com.***.***/files/support.css
/data/user/0/com.***.***/files/myscript.js
/data/user/0/com.***.***/files/style.css

Is it possible to set UIView border properties from interface builder?

Its absolutely possible only when you set layer.masksToBounds = true and do you rest stuff.

python save image from url

A sample code that works for me on Windows:

import requests

with open('pic1.jpg', 'wb') as handle:
        response = requests.get(pic_url, stream=True)

        if not response.ok:
            print response

        for block in response.iter_content(1024):
            if not block:
                break

            handle.write(block)