Programs & Examples On #Great circle

MySQL Great Circle Distance (Haversine formula)

I can't comment on the above answer, but be careful with @Pavel Chuchuva's answer. That formula will not return a result if both coordinates are the same. In that case, distance is null, and so that row won't be returned with that formula as is.

I'm not a MySQL expert, but this seems to be working for me:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance 
FROM markers HAVING distance < 25 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;

How to disable/enable select field using jQuery?

To be able to disable/enable selects first of all your selects need an ID or class. Then you could do something like this:

Disable:

$('#id').attr('disabled', 'disabled');

Enable:

$('#id').removeAttr('disabled');

Lock, mutex, semaphore... what's the difference?

Take a look at Multithreading Tutorial by John Kopplin.

In the section Synchronization Between Threads, he explain the differences among event, lock, mutex, semaphore, waitable timer

A mutex can be owned by only one thread at a time, enabling threads to coordinate mutually exclusive access to a shared resource

Critical section objects provide synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process

Another difference between a mutex and a critical section is that if the critical section object is currently owned by another thread, EnterCriticalSection() waits indefinitely for ownership whereas WaitForSingleObject(), which is used with a mutex, allows you to specify a timeout

A semaphore maintains a count between zero and some maximum value, limiting the number of threads that are simultaneously accessing a shared resource.

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

Detecting endianness programmatically in a C++ program

Please see this article:

Here is some code to determine what is the type of your machine

int num = 1;
if(*(char *)&num == 1)
{
    printf("\nLittle-Endian\n");
}
else
{
    printf("Big-Endian\n");
}

Send FormData and String Data Together Through JQuery AJAX?

You can try this:

var fd = new FormData();
var data = [];           //<---------------declare array here
var file_data = object.get(0).files[i];
var other_data = $('form').serialize();

data.push(file_data);  //<----------------push the data here
data.push(other_data); //<----------------and this data too

fd.append("file", data);  //<---------then append this data

Hex colors: Numeric representation for "transparent"?

Very simple: no color, no opacity:

rgba(0, 0, 0, 0);

Is it wrong to place the <script> tag after the </body> tag?

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

CSS background-image not working

@TheBigO, that's not correct. Spans can have background/images (tested in IE8 and Chrome as a sanity check).

The issue is that the a.btn-pToolName is marked as display: block. This causes webkit browsers to no longer show the background in the outer span. IE seems to render it how the OP is wanting.

OP chance the .btn-pTool class to be display: inline-block to make it work like a span/div hybrid (take the background, but not cause a break in the layout).

Is JavaScript a pass-by-reference or pass-by-value language?

well, it's about 'performance' and 'speed' and in the simple word 'memory management' in a programming language.

in javascript we can put values in two layer: type1-objects and type2-all other types of value such as string & boolean & etc

if you imagine memory as below squares which in every one of them just one type2-value can be saved:

enter image description here

every type2-value (green) is a single square while a type1-value (blue) is a group of them:

enter image description here

the point is that if you want to indicate a type2-value, the address is plain but if you want to do the same thing for type1-value that's not easy at all! :

enter image description here

and in a more complicated story:

enter image description here

so here references can rescue us: enter image description here

while the green arrow here is a typical variable, the purple one is an object variable, so because the green arrow(typical variable) has just one task (and that is indicating a typical value) we don't need to separate it's value from it so we move the green arrow with the value of that wherever it goes and in all assignments, functions and so on ...

but we cant do the same thing with the purple arrow, we may want to move 'john' cell here or many other things..., so the purple arrow will stick to its place and just typical arrows that were assigned to it will move ...

a very confusing situation is where you can't realize how your referenced variable changes, let's take a look at a very good example:

let arr = [1, 2, 3, 4, 5]; //arr is an object now and a purple arrow is indicating it
let obj2 = arr; // now, obj2 is another purple arrow that is indicating the value of arr obj
let obj3 = ['a', 'b', 'c'];
obj2.push(6); // first pic below - making a new hand for the blue circle to point the 6
//obj2 = [1, 2, 3, 4, 5, 6]
//arr = [1, 2, 3, 4, 5, 6]
//we changed the blue circle object value (type1-value) and due to arr and obj2 are indicating that so both of them changed
obj2 = obj3; //next pic below - changing the direction of obj2 array from blue circle to orange circle so obj2 is no more [1,2,3,4,5,6] and it's no more about changing anything in it but we completely changed its direction and now obj2 is pointing to obj3
//obj2 = ['a', 'b', 'c'];
//obj3 = ['a', 'b', 'c'];

enter image description here enter image description here

Could not resolve placeholder in string value

This Issue occurs if the application is unable to access the some_file_name.properties file.Make sure that the properties file is placed under resources folder in spring.

Trouble shooting Steps

1: Add the properties file under the resource folder.

2: If you don't have a resource folder. Create one by navigating new by Right click on the project new > Source Folder, name it as resource and place your properties file under it.

For annotation based Implementation

Add @PropertySource(ignoreResourceNotFound = true, value = "classpath:some_file_name.properties")//Add it before using the place holder

Example:

Assignment1Controller.Java

@PropertySource(ignoreResourceNotFound = true, value = "classpath:assignment1.properties")
@RestController  
public class Assignment1Controller {

//  @Autowired
//  Assignment1Services assignment1Services;
    @Value("${app.title}")
    private String appTitle;
     @RequestMapping(value = "/hello")  
        public String getValues() {

          return appTitle;

        }  

}

assignment1.properties

app.title=Learning Spring

How to solve npm install throwing fsevents warning on non-MAC OS?

npm i -f

I'd like to repost some comments from this thread, where you can read up on the issue and the issue was solved.

This is exactly Angular's issue. Current package.json requires fsevent as not optionalDependencies but devDependencies. This may be a problem for non-OSX users.

Sometimes

Even if you remove it from package.json npm i still fails because another module has it as a peer dep.

So

if npm-shrinkwrap.json is still there, please remove it or try npm i -f

XmlSerializer: remove unnecessary xsi and xsd namespaces

Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.


After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To whit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the default namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.


This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label> is part of the same namespace as the rest of the document, in this case urn:Abracadabra:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:

// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the 
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
    });
}

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
    get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;

Then, later, in your code that uses the MyTypeWithNamespaces object to serialize it, you would call it as I did above:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

...

// Above, you'd setup your XmlTextWriter.

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

And the XmlSerializer would spit back out the same XML as shown immediately above with no additional namespaces in the output:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Redeploy alternatives to JRebel

You might want to take a look this:

HotSwap support: the object-oriented architecture of the Java HotSpot VM enables advanced features such as on-the-fly class redefinition, or "HotSwap". This feature provides the ability to substitute modified code in a running application through the debugger APIs. HotSwap adds functionality to the Java Platform Debugger Architecture, enabling a class to be updated during execution while under the control of a debugger. It also allows profiling operations to be performed by hotswapping in versions of methods in which profiling code has been inserted.

For the moment, this only allows for newly compiled method body to be redeployed without restarting the application. All you have to do is to run it with a debugger. I tried it in Eclipse and it works splendidly.

Also, as Emmanuel Bourg mentioned in his answer (JEP 159), there is hope to have support for the addition of supertypes and the addition and removal of methods and fields.

Reference: Java Whitepaper 135217: Reliability, Availability and Serviceability

Getting Date or Time only from a DateTime Object

You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.

What function is to replace a substring from a string in C?

char *replace(const char*instring, const char *old_part, const char *new_part)
{

#ifndef EXPECTED_REPLACEMENTS
    #define EXPECTED_REPLACEMENTS 100
#endif

    if(!instring || !old_part || !new_part)
    {
        return (char*)NULL;
    }

    size_t instring_len=strlen(instring);
    size_t new_len=strlen(new_part);
    size_t old_len=strlen(old_part);
    if(instring_len<old_len || old_len==0)
    {
        return (char*)NULL;
    }

    const char *in=instring;
    const char *found=NULL;
    size_t count=0;
    size_t out=0;
    size_t ax=0;
    char *outstring=NULL;

    if(new_len> old_len )
    {
        size_t Diff=EXPECTED_REPLACEMENTS*(new_len-old_len);
        size_t outstring_len=instring_len + Diff;
        outstring =(char*) malloc(outstring_len); 
        if(!outstring){
            return (char*)NULL;
        }
        while((found = strstr(in, old_part))!=NULL)
        {
            if(count==EXPECTED_REPLACEMENTS)
            {
                outstring_len+=Diff;
                if((outstring=realloc(outstring,outstring_len))==NULL)
                {
                     return (char*)NULL;
                }
                count=0;
            }
            ax=found-in;
            strncpy(outstring+out,in,ax);
            out+=ax;
            strncpy(outstring+out,new_part,new_len);
            out+=new_len;
            in=found+old_len;
            count++;
        }
    }
    else
    {
        outstring =(char*) malloc(instring_len);
        if(!outstring){
            return (char*)NULL;
        }
        while((found = strstr(in, old_part))!=NULL)
        {
            ax=found-in;
            strncpy(outstring+out,in,ax);
            out+=ax;
            strncpy(outstring+out,new_part,new_len);
            out+=new_len;
            in=found+old_len;
        }
    }
    ax=(instring+instring_len)-in;
    strncpy(outstring+out,in,ax);
    out+=ax;
    outstring[out]='\0';

    return outstring;
}

How to get distinct results in hibernate with joins and row-based limiting (paging)?

Below is the way we can do Multiple projection to perform Distinct

    package org.hibernate.criterion;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;

/**
* A count for style :  count (distinct (a || b || c))
*/
public class MultipleCountProjection extends AggregateProjection {

   private boolean distinct;

   protected MultipleCountProjection(String prop) {
      super("count", prop);
   }

   public String toString() {
      if(distinct) {
         return "distinct " + super.toString();
      } else {
         return super.toString();
      }
   }

   public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) 
   throws HibernateException {
      return new Type[] { Hibernate.INTEGER };
   }

   public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) 
   throws HibernateException {
      StringBuffer buf = new StringBuffer();
      buf.append("count(");
      if (distinct) buf.append("distinct ");
        String[] properties = propertyName.split(";");
        for (int i = 0; i < properties.length; i++) {
           buf.append( criteriaQuery.getColumn(criteria, properties[i]) );
             if(i != properties.length - 1) 
                buf.append(" || ");
        }
        buf.append(") as y");
        buf.append(position);
        buf.append('_');
        return buf.toString();
   }

   public MultipleCountProjection setDistinct() {
      distinct = true;
      return this;
   }

}

ExtraProjections.java

package org.hibernate.criterion; 

public final class ExtraProjections
{ 
    public static MultipleCountProjection countMultipleDistinct(String propertyNames) {
        return new MultipleCountProjection(propertyNames).setDistinct();
    }
}

Sample Usage:

String propertyNames = "titleName;titleDescr;titleVersion"

criteria countCriteria = ....

countCriteria.setProjection(ExtraProjections.countMultipleDistinct(propertyNames);

Referenced from https://forum.hibernate.org/viewtopic.php?t=964506

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

Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.

PHP 7 RC3: How to install missing MySQL PDO

Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql. See comments under the question for details.

SQLRecoverableException: I/O Exception: Connection reset

The error occurs on some RedHat distributions. The only thing you need to do is to run your application with parameter java.security.egd=file:///dev/urandom:

java -Djava.security.egd=file:///dev/urandom [your command]

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

ArrayList vs List<> in C#

Another difference to add is with respect to Thread Synchronization.

ArrayList provides some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections.

List<T> does not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently.

More info here Thread Synchronization in the .Net Framework

How can I return the difference between two lists?

You can use filter in the Java 8 Stream library

List<String> aList = List.of("l","e","t","'","s");
List<String> bList = List.of("g","o","e","s","t");

List<String> difference = aList.stream()
    .filter(aObject -> {
        return ! bList.contains(aObject);
      })
    .collect(Collectors.toList());

//more reduced: no curly braces, no return
List<String> difference2 = aList.stream()
    .filter(aObject -> ! bList.contains(aObject))
    .collect(Collectors.toList());

Result of System.out.println(difference);:

[e, t, s]

How to find out which package version is loaded in R?

Based on the previous answers, here is a simple alternative way of printing the R-version, followed by the name and version of each package loaded in the namespace. It works in the Jupyter notebook, where I had troubles running sessionInfo() and R --version.

print(paste("R", getRversion()))
print("-------------")
for (package_name in sort(loadedNamespaces())) {
    print(paste(package_name, packageVersion(package_name)))
}

Out:

[1] "R 3.2.2"
[1] "-------------"
[1] "AnnotationDbi 1.32.2"
[1] "Biobase 2.30.0"
[1] "BiocGenerics 0.16.1"
[1] "BiocParallel 1.4.3"
[1] "DBI 0.3.1"
[1] "DESeq2 1.10.0"
[1] "Formula 1.2.1"
[1] "GenomeInfoDb 1.6.1"
[1] "GenomicRanges 1.22.3"
[1] "Hmisc 3.17.0"
[1] "IRanges 2.4.6"
[1] "IRdisplay 0.3"
[1] "IRkernel 0.5"

TSQL Pivot without aggregate function

Try this:

SELECT CUSTOMER_ID, MAX(FIRSTNAME) AS FIRSTNAME, MAX(LASTNAME) AS LASTNAME ...

FROM
(

SELECT CUSTOMER_ID, 
       CASE WHEN DBCOLUMNNAME='FirstName' then DATA ELSE NULL END AS FIRSTNAME,
       CASE WHEN DBCOLUMNNAME='LastName' then DATA ELSE NULL END AS LASTNAME,
        ... and so on ...
GROUP BY CUSTOMER_ID

) TEMP

GROUP BY CUSTOMER_ID

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

Have log4net use application config file for configuration data

Add a line to your app.config in the configSections element

<configSections>
 <section name="log4net" 
   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, 
         Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>

Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...

<log4net configSource="Config\Log4Net.config" />

In your application code, when you create the log, write

private static ILog GetLog(string logName)
{
    ILog log = LogManager.GetLogger(logName);
    return log;
}

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

Skip the headers when editing a csv file using Python

Inspired by Martijn Pieters' response.

In case you only need to delete the header from the csv file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers
   outfile.write(infile.read())

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

How to use find command to find all files with extensions from list?

On Mac OS use

find -E packages  -regex ".*\.(jpg|gif|png|jpeg)"

Disable JavaScript error in WebBrowser control

This disables the script errors and also disables other windows.. such as the NTLM login window or the client certificate accept window. The below will suppress only javascript errors.

// Hides script errors without hiding other dialog boxes.
private void SuppressScriptErrorsOnly(WebBrowser browser)
{
    // Ensure that ScriptErrorsSuppressed is set to false.
    browser.ScriptErrorsSuppressed = false;

    // Handle DocumentCompleted to gain access to the Document object.
    browser.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(
            browser_DocumentCompleted);
}

private void browser_DocumentCompleted(object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    ((WebBrowser)sender).Document.Window.Error += 
        new HtmlElementErrorEventHandler(Window_Error);
}

private void Window_Error(object sender, 
    HtmlElementErrorEventArgs e)
{
    // Ignore the error and suppress the error dialog box. 
    e.Handled = true;
}

how to query LIST using linq

Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples

Also, you should really really really change your List into a strongly typed list (List<T>), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.

Java ArrayList clear() function

Source code of clear shows the reason why the newly added data gets the first position.

 public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
    }

clear() is faster than removeAll() by the way, first one is O(n) while the latter is O(n_2)

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Try indextank.

As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.

Android Google Maps API V2 Zoom to Current Location

youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I was upgrading gradle from 4.1 to 4.10 and my internet connection timed out.

So I fixed this issue by deleting "gradle-4.10-all" folder in .gradle/wrapper/dists

View more than one project/solution in Visual Studio

You can have multiple projects in one instance of Visual Studio. The point of a VS solution is to bring together all the projects you want to work with in one place, so you can't have multiple solutions in one instance. You'd have to open each solution separately.

How to create a database from shell command?

You mean while the mysql environment?

create database testdb;

Or directly from command line:

mysql -u root -e "create database testdb"; 

How to delete Tkinter widgets from a window?

You can use forget method on the widget

from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=b.forget)
b.pack()

b['command'] = b.forget

root.mainloop()

Android: Access child views from a ListView

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

The proper syntax is (in example):

$query = mysql_query('SELECT * FROM beer ORDER BY quality');
while($row = mysql_fetch_assoc($query)) $results[] = $row;

Why I get 411 Length required error?

Google search

2nd result

System.Net.WebException: The remote server returned an error: (411) Length Required.

This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.

This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.

var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";

To fix this error, add an explicit content length to your request before making the API call.

request.ContentLength = 0;

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

White spaces are required between publicId and systemId

The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.

You'll get the error with (for instance):

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

You won't with:

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">

Notice "" at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.

By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.

Failed Apache2 start, no error log

Syntax errors in the config file seem to cause problems. I found what the problem was by going to the directory and excuting this from the command line.

httpd -e info 

This gave me the error

Syntax error on line 156 of D:/.../Apache Software Foundation/Apache2.2/conf/httpd.conf:
Invalid command 'PHPIniDir', perhaps misspelled or defined by a module not included in the server configuration

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

IIS Request Timeout on long ASP.NET operation

Great and exhaustive answerby @Kev!

Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location> tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.

Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut is in minutes, while the request executionTimeout is in seconds!

And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).

<configuration>
    ... 
    <compilation debug="false" ...>
    ... other stuff ..

    <location path="~/Admin/SomePage.aspx">
        <system.web>
            <sessionState timeout="240" />
            <httpRuntime executionTimeout="14400" />
        </system.web>
    </location>
    ...
</configuration>

Please explain the exec() function and its family

Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.

The simple idea behind the UNIX "execution model" is that there are two operations you can do.

The first is to fork(), which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.

The second is to exec(), which replaces the program in the current process with a brand new program.

From those two simple operations, the entire UNIX execution model can be constructed.


To add some more detail to the above:

The use of fork() and exec() exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork() call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork() but two processes return from that call - sounds bizarre but it's really quite elegant

The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).

Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork() provides this information - the child gets 0, the parent gets the PID of the child (if the fork() fails, no child is created and the parent gets an error code).

That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()).

The exec() call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork() and exec() are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to call fork() without a following exec() if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).

This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.

Similarly, programs that know they're finished and just want to run another program don't need to fork(), exec() and then wait()/waitpid() for the child. They can just load the child directly into their current process space with exec().

Some UNIX implementations have an optimized fork() which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork() until the program attempts to change something in that space. This is useful for those programs using only fork() and not exec() in that they don't have to copy an entire process space. Under Linux, fork() only makes a copy of the page tables and a new task structure, exec() will do the grunt work of "separating" the memory of the two processes.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.

Linux also has a vfork(), even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec() or _exit().

The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork() followed immediately by exec().

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

Ansible playbook shell output

I found using the minimal stdout_callback with ansible-playbook gave similar output to using ad-hoc ansible.

In your ansible.cfg (Note that I'm on OS X so modify the callback_plugins path to suit your install)

stdout_callback     = minimal
callback_plugins    = /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ansible/plugins/callback

So that a ansible-playbook task like yours

---
-
  hosts: example
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5

Gives output like this, like an ad-hoc command would

example | SUCCESS | rc=0 >>
%CPU USER     COMMAND
 0.2 root     sshd: root@pts/3
 0.1 root     /usr/sbin/CROND -n
 0.0 root     [xfs-reclaim/vda]
 0.0 root     [xfs_mru_cache]

I'm using ansible-playbook 2.2.1.0

One line if statement not working

In Ruby, the condition and the then part of an if expression must be separated by either an expression separator (i.e. ; or a newline) or the then keyword.

So, all of these would work:

if @item.rigged then 'Yes' else 'No' end

if @item.rigged; 'Yes' else 'No' end

if @item.rigged
  'Yes' else 'No' end

There is also a conditional operator in Ruby, but that is completely unnecessary. The conditional operator is needed in C, because it is an operator: in C, if is a statement and thus cannot return a value, so if you want to return a value, you need to use something which can return a value. And the only things in C that can return a value are functions and operators, and since it is impossible to make if a function in C, you need an operator.

In Ruby, however, if is an expression. In fact, everything is an expression in Ruby, so it already can return a value. There is no need for the conditional operator to even exist, let alone use it.

BTW: it is customary to name methods which are used to ask a question with a question mark at the end, like this:

@item.rigged?

This shows another problem with using the conditional operator in Ruby:

@item.rigged? ? 'Yes' : 'No'

It's simply hard to read with the multiple question marks that close to each other.

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet are 0x20 apart from each other, so this is another way to do it.

int lower(int a) 
{
    if ((a >= 0x41) && (a <= 0x5A))
        a |= 0x20; 
    return a;  
}

How can I nullify css property?

An initial keyword is being added in CSS3 to allow authors to explicitly specify this initial value.

iCheck check if checkbox is checked

Use this method:

$(document).on('ifChanged','SELECTOR', function(event){
  alert(event.type + ' callback');
});

What is *.o file?

Ink-Jet is right. More specifically, an .o (.obj) -- or object file is a single source file compiled in to machine code (I'm not sure if the "machine code" is the same or similar to an executable machine code). Ultimately, it's an intermediate between an executable program and plain-text source file.

The linker uses the o files to assemble the file executable.

Wikipedia may have more detailed information. I'm not sure how much info you'd like or need.

SELECT DISTINCT on one column

I know it was asked over 6 years ago, but knowledge is still knowledge. This is different solution than all above, as I had to run it under SQL Server 2000:

DECLARE @TestData TABLE([ID] int, [SKU] char(6), [Product] varchar(15))
INSERT INTO @TestData values (1 ,'FOO-23', 'Orange')
INSERT INTO @TestData values (2 ,'BAR-23', 'Orange')
INSERT INTO @TestData values (3 ,'FOO-24', 'Apple')
INSERT INTO @TestData values (4 ,'FOO-25', 'Orange')

SELECT DISTINCT  [ID] = ( SELECT TOP 1 [ID]  FROM @TestData Y WHERE Y.[Product] = X.[Product])
                ,[SKU]= ( SELECT TOP 1 [SKU] FROM @TestData Y WHERE Y.[Product] = X.[Product])
                ,[PRODUCT] 
            FROM @TestData X  

Byte[] to InputStream or OutputStream

I do realize that my answer is way late for this question but I think the community would like a newer approach to this issue.

How to remove duplicate values from a multi-dimensional array in PHP

if you need to eliminate duplicates on specific keys, such as a mysqli id, here's a simple funciton

function search_array_compact($data,$key){
    $compact = [];
    foreach($data as $row){
        if(!in_array($row[$key],$compact)){
            $compact[] = $row;
        }
    }
    return $compact;
}

Bonus Points You can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Personally, to deal with empty responses, I use in my Integration Tests the MockMvcResponse object like this :

MockMvcResponse response = RestAssuredMockMvc.given()
                .webAppContextSetup(webApplicationContext)
                .when()
                .get("/v1/ticket");

    assertThat(response.mockHttpServletResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());

and in my controller I return empty response in a specific case like this :

return ResponseEntity.noContent().build();

How to calculate the difference between two dates using PHP?

Take a look at the following link. This is the best answer I've found so far.. :)

function dateDiff ($d1, $d2) {

    // Return the number of days between the two dates:    
    return round(abs(strtotime($d1) - strtotime($d2))/86400);

} // end function dateDiff

It doesn't matter which date is earlier or later when you pass in the date parameters. The function uses the PHP ABS() absolute value to always return a postive number as the number of days between the two dates.

Keep in mind that the number of days between the two dates is NOT inclusive of both dates. So if you are looking for the number of days represented by all the dates between and including the dates entered, you will need to add one (1) to the result of this function.

For example, the difference (as returned by the above function) between 2013-02-09 and 2013-02-14 is 5. But the number of days or dates represented by the date range 2013-02-09 - 2013-02-14 is 6.

http://www.bizinfosys.com/php/date-difference.html

Map and Reduce in .NET

Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.

  • Map is Select:

    Enumerable.Range(1, 10).Select(x => x + 2);
    
  • Reduce is Aggregate:

    Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
    
  • Filter is Where:

    Enumerable.Range(1, 10).Where(x => x % 2 == 0);
    

https://www.justinshield.com/2011/06/mapreduce-in-c/

SQL Server: how to select records with specific date from datetime column

SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';

This will select all the data between the 2 dates

Find where java class is loaded from

Take a look at this similar question. Tool to discover same class..

I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap )

How to set standard encoding in Visual Studio

The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.

I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:

Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/

The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".

Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.

how does array[100] = {0} set the entire array to 0?

It's not magic.

The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).

The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.

Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:

char array[100] = {};

As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization

How to unblock with mysqladmin flush hosts

You should put it into command line in windows.

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

For network login use the following command:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

.datepicker('setdate') issues, in jQuery

function calenderEdit(dob) {
    var date= $('#'+dob).val();
    $("#dob").datepicker({
        changeMonth: true,
        changeYear: true, yearRange: '1950:+10'
    }).datepicker("setDate", date);
}

Why does Maven have such a bad rep?

Any Java developer can easily become an expert ANT user, but not even an expert Java developer can't become a beginner level MAVEN user.

Maven will make your developers scared s***less for doing anything related to Build and Deployment.

They will start respecting Maven more than the War file or Ear file!! which is bad bad bad!

Then you will be left at the mercy of online forums, where fan-boys will berate you for not doing things the "Maven way".

How to declare empty list and then add string in scala?

Scala lists are immutable by default. You cannot "add" an element, but you can form a new list by appending the new element in front. Since it is a new list, you need to reassign the reference (so you can't use a val).

var dm  = List[String]()
var dk = List[Map[String,AnyRef]]()

.....

dm = "text" :: dm
dk = Map(1 -> "ok") :: dk

The operator :: creates the new list. You can also use the shorter syntax:

dm ::= "text" 
dk ::= Map(1 -> "ok")

NB: In scala don't use the type Object but Any, AnyRef or AnyVal.

unexpected T_VARIABLE, expecting T_FUNCTION

You cannot use function calls in a class construction, you should initialize that value in the constructor function.

From the PHP Manual on class properties:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

A working code sample:

<?php
    class UserDatabaseConnection
    {
        public $connection;
        public function __construct()
        {
            $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
        }
        public function lookupUser($username)
        {
            // rest of my code...
            // example usage (procedural way):
            $query = sqlite_exec($this->connection, "SELECT ...", $error);
            // object oriented way:
            $query = $this->connection->queryExec("SELECT ...", $error);
        }
    }

    $udb = new UserDatabaseConnection;
?>

Depending on your needs, protected or private might be a better choice for $connection. That protects you from accidentally closing or messing with the connection.

JavaScript and Threads

Here is just a way to simulate multi-threading in Javascript

Now I am going to create 3 threads which will calculate numbers addition, numbers can be divided with 13 and numbers can be divided with 3 till 10000000000. And these 3 functions are not able to run in same time as what Concurrency means. But I will show you a trick that will make these functions run recursively in the same time : jsFiddle

This code belongs to me.

Body Part

    <div class="div1">
    <input type="button" value="start/stop" onclick="_thread1.control ? _thread1.stop() : _thread1.start();" /><span>Counting summation of numbers till 10000000000</span> = <span id="1">0</span>
</div>
<div class="div2">
    <input type="button" value="start/stop" onclick="_thread2.control ? _thread2.stop() : _thread2.start();" /><span>Counting numbers can be divided with 13 till 10000000000</span> = <span id="2">0</span>
</div>
<div class="div3">
    <input type="button" value="start/stop" onclick="_thread3.control ? _thread3.stop() : _thread3.start();" /><span>Counting numbers can be divided with 3 till 10000000000</span> = <span id="3">0</span>
</div>

Javascript Part

var _thread1 = {//This is my thread as object
    control: false,//this is my control that will be used for start stop
    value: 0, //stores my result
    current: 0, //stores current number
    func: function () {   //this is my func that will run
        if (this.control) {      // checking for control to run
            if (this.current < 10000000000) {
                this.value += this.current;   
                document.getElementById("1").innerHTML = this.value;
                this.current++;
            }
        }
        setTimeout(function () {  // And here is the trick! setTimeout is a king that will help us simulate threading in javascript
            _thread1.func();    //You cannot use this.func() just try to call with your object name
        }, 0);
    },
    start: function () {
        this.control = true;   //start function
    },
    stop: function () {
        this.control = false;    //stop function
    },
    init: function () {
        setTimeout(function () {
            _thread1.func();    // the first call of our thread
        }, 0)
    }
};
var _thread2 = {
    control: false,
    value: 0,
    current: 0,
    func: function () {
        if (this.control) {
            if (this.current % 13 == 0) {
                this.value++;
            }
            this.current++;
            document.getElementById("2").innerHTML = this.value;
        }
        setTimeout(function () {
            _thread2.func();
        }, 0);
    },
    start: function () {
        this.control = true;
    },
    stop: function () {
        this.control = false;
    },
    init: function () {
        setTimeout(function () {
            _thread2.func();
        }, 0)
    }
};
var _thread3 = {
    control: false,
    value: 0,
    current: 0,
    func: function () {
        if (this.control) {
            if (this.current % 3 == 0) {
                this.value++;
            }
            this.current++;
            document.getElementById("3").innerHTML = this.value;
        }
        setTimeout(function () {
            _thread3.func();
        }, 0);
    },
    start: function () {
        this.control = true;
    },
    stop: function () {
        this.control = false;
    },
    init: function () {
        setTimeout(function () {
            _thread3.func();
        }, 0)
    }
};

_thread1.init();
_thread2.init();
_thread3.init();

I hope this way will be helpful.

How to convert seconds to HH:mm:ss in moment.js

How to correctly use moment.js durations? | Use moment.duration() in codes

First, you need to import moment and moment-duration-format.

import moment from 'moment';
import 'moment-duration-format';

Then, use duration function. Let us apply the above example: 28800 = 8 am.

moment.duration(28800, "seconds").format("h:mm a");

Well, you do not have above type error. Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.

The solution is to transform seconds to milliseconds and use UTC time.

moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')

All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp

const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')

jQuery find parent form

As of HTML5 browsers one can use inputElement.form - the value of the attribute must be an id of a <form> element in the same document. More info on MDN.

jQuery Scroll To bottom of the page

var pixelFromTop = 500;     
$('html, body').animate({ scrollTop: pixelFromTop  }, 1);

So when page open it is automatically scroll down after 1 milisecond

Switch statement fall-through...should it be allowed?

Fall-through is really a handy thing, depending on what you're doing. Consider this neat and understandable way to arrange options:

switch ($someoption) {
  case 'a':
  case 'b':
  case 'c':
    // Do something
    break;

  case 'd':
  case 'e':
    // Do something else
    break;
}

Imagine doing this with if/else. It would be a mess.

Can I safely delete contents of Xcode Derived data folder?

Just created a github repo with a small script, that creates a RAM disk. If you point your DerivedData folder to /Volumes/ramdisk, after ejecting disk all files will be gone.

It speeds up compiling, also eliminates this problem

xc-launch repo

Best launched using DTerm

How to show math equations in general github's markdown(not github's blog)

I use the below mentioned process to convert equations to markdown. This works very well for me. Its very simple!!

Let's say, I want to represent matrix multiplication equation

Step 1:

Get the script for your formulae from here - https://csrgxtu.github.io/2015/03/20/Writing-Mathematic-Fomulars-in-Markdown/

My example: I wanted to represent Z(i,j)=X(i,k) * Y(k, j); k=1 to n into a summation formulae.

enter image description here

Referencing the website, the script needed was => Z_i_j=\sum_{k=1}^{10} X_i_k * Y_k_j

Step 2:

Use URL encoder - https://www.urlencoder.org/ to convert the script to a valid url

My example:

enter image description here

Step 3:

Use this website to generate the image by copy-pasting the output from Step 2 in the "eq" request parameter - http://www.sciweavers.org/tex2img.php?eq=<b><i>paste-output-here</i></b>&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

- My example:
http://www.sciweavers.org/tex2img.php?eq=Z_i_j=\sum_{k=1}^{10}%20X_i_k%20*%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

enter image description here

Step 4:

Reference image using markdown syntax - ![alt text](enter url here)

- Copy this in your markdown and you are good to go:

![Z(i,j)=X(i,k) * Y(k, j); k=1 to n](http://www.sciweavers.org/tex2img.php?eq=Z_i_j%3D%5Csum_%7Bi%3D1%7D%5E%7B10%7D%20X_i_k%20%2A%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)

Image below is the output of markdown. Hurray!!


enter image description here

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

How to find all the subclasses of a class given its name?

A much shorter version for getting a list of all subclasses:

from itertools import chain

def subclasses(cls):
    return list(
        chain.from_iterable(
            [list(chain.from_iterable([[x], subclasses(x)])) for x in cls.__subclasses__()]
        )
    )

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

Delete directory with files in it?

What about this:

function recursiveDelete($dirPath, $deleteParent = true){
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
        $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
    }
    if($deleteParent) rmdir($dirPath);
}

Check if cookies are enabled

A transparent, clean and simple approach, checking cookies availability with PHP and taking advantage of AJAX transparent redirection, hence not triggering a page reload. It doesn't require sessions either.

Client-side code (JavaScript)

function showCookiesMessage(cookiesEnabled) {
    if (cookiesEnabled == 'true')
        alert('Cookies enabled');
    else
        alert('Cookies disabled');
}

$(document).ready(function() {
    var jqxhr = $.get('/cookiesEnabled.php');
    jqxhr.done(showCookiesMessage);
});

(JQuery AJAX call can be replaced with pure JavaScript AJAX call)

Server-side code (PHP)

if (isset($_COOKIE['cookieCheck'])) {
    echo 'true';
} else {
    if (isset($_GET['reload'])) {
        echo 'false';
    } else {
        setcookie('cookieCheck', '1', time() + 60);
        header('Location: ' . $_SERVER['PHP_SELF'] . '?reload');
        exit();
    }
}

First time the script is called, the cookie is set and the script tells the browser to redirect to itself. The browser does it transparently. No page reload takes place because it's done within an AJAX call scope.

The second time, when called by redirection, if the cookie is received, the script responds an HTTP 200 (with string "true"), hence the showCookiesMessage function is called.

If the script is called for the second time (identified by the "reload" parameter) and the cookie is not received, it responds an HTTP 200 with string "false" -and the showCookiesMessage function gets called.

Catching errors in Angular HttpClient

With the arrival of the HTTPClient API, not only was the Http API replaced, but a new one was added, the HttpInterceptor API.

AFAIK one of its goals is to add default behavior to all the HTTP outgoing requests and incoming responses.

So assumming that you want to add a default error handling behavior, adding .catch() to all of your possible http.get/post/etc methods is ridiculously hard to maintain.

This could be done in the following way as example using a HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

/**
 * Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
 * and extract the relevant information of it.
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    /**
     * Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
     * @see HttpInterceptor
     * @param req the outgoing HTTP request
     * @param next a HTTP request handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .catch(errorResponse => {
                let errMsg: string;
                if (errorResponse instanceof HttpErrorResponse) {
                    const err = errorResponse.message || JSON.stringify(errorResponse.error);
                    errMsg = `${errorResponse.status} - ${errorResponse.statusText || ''} Details: ${err}`;
                } else {
                    errMsg = errorResponse.message ? errorResponse.message : errorResponse.toString();
                }
                return _throw(errMsg);
            });
    }
}

/**
 * Provider POJO for the interceptor
 */
export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
};

// app.module.ts

import { ErrorInterceptorProvider } from 'somewhere/in/your/src/folder';

@NgModule({
   ...
   providers: [
    ...
    ErrorInterceptorProvider,
    ....
   ],
   ...
})
export class AppModule {}

Some extra info for OP: Calling http.get/post/etc without a strong type isn't an optimal use of the API. Your service should look like this:

// These interfaces could be somewhere else in your src folder, not necessarily in your service file
export interface FooPost {
 // Define the form of the object in JSON format that your 
 // expect from the backend on post
}

export interface FooPatch {
 // Define the form of the object in JSON format that your 
 // expect from the backend on patch
}

export interface FooGet {
 // Define the form of the object in JSON format that your 
 // expect from the backend on get
}

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
    constructor(
        private http: HttpClient) {
    }

    get(url, params): Observable<FooGet> {

        return this.http.get<FooGet>(this.baseUrl + url, params);
    }

    post(url, body): Observable<FooPost> {
        return this.http.post<FooPost>(this.baseUrl + url, body);
    }

    patch(url, body): Observable<FooPatch> {
        return this.http.patch<FooPatch>(this.baseUrl + url, body);
    }
}

Returning Promises from your service methods instead of Observables is another bad decision.

And an extra piece of advice: if you are using TYPEscript, then start using the type part of it. You lose one of the biggest advantages of the language: to know the type of the value that you are dealing with.

If you want a, in my opinion, good example of an angular service, take a look at the following gist.

Calling filter returns <filter object at ... >

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

How can I develop for iPhone using a Windows development machine?

As many people already answered, iPhone SDK is available only for OS X, and I believe Apple will never release it for Windows. But there are several alternative environments/frameworks that allow you to develop iOS applications, even package and submit to AppStore using windows machine as well as MAC. Here are most popular and relatively better options.

PhoneGap, allow to create web-based apps, using HTML/CSS/JavaScript

Xamarin, cross-platform apps in C#

Adobe AIR, air applications with Flash / ActionScript

Unity3D, cross-platform game engine

Note: Unity requires Xcode, and therefore OS X to build iOS projects.

Is it safe to delete a NULL pointer?

From the C++0x draft Standard.

$5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"

Of course, no one would ever do 'delete' of a pointer with NULL value, but it is safe to do. Ideally one should not have code that does deletion of a NULL pointer. But it is sometimes useful when deletion of pointers (e.g. in a container) happens in a loop. Since delete of a NULL pointer value is safe, one can really write the deletion logic without explicit checks for NULL operand to delete.

As an aside, C Standard $7.20.3.2 also says that 'free' on a NULL pointer does no action.

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

Convert list of dictionaries to a pandas DataFrame

For converting a list of dictionaries to a pandas DataFrame, you can use "append":

We have a dictionary called dic and dic has 30 list items (list1, list2,…, list30)

  1. step1: define a variable for keeping your result (ex: total_df)
  2. step2: initialize total_df with list1
  3. step3: use "for loop" for append all lists to total_df
total_df=list1
nums=Series(np.arange(start=2, stop=31))
for num in nums:
    total_df=total_df.append(dic['list'+str(num)])

Set mouse focus and move cursor to end of input using jQuery

    function focusCampo(id){
        var inputField = document.getElementById(id);
        if (inputField != null && inputField.value.length != 0){
            if (inputField.createTextRange){
                var FieldRange = inputField.createTextRange();
                FieldRange.moveStart('character',inputField.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                var elemLen = inputField.value.length;
                inputField.selectionStart = elemLen;
                inputField.selectionEnd = elemLen;
                inputField.focus();
            }
        }else{
            inputField.focus();
        }
    }

$('#urlCompany').focus(focusCampo('urlCompany'));

works for all ie browsers..

How do I disable text selection with CSS or JavaScript?

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).


All of the correct CSS variations are:

_x000D_
_x000D_
.noselect {_x000D_
  -webkit-touch-callout: none; /* iOS Safari */_x000D_
    -webkit-user-select: none; /* Safari */_x000D_
     -khtml-user-select: none; /* Konqueror HTML */_x000D_
       -moz-user-select: none; /* Firefox */_x000D_
        -ms-user-select: none; /* Internet Explorer/Edge */_x000D_
            user-select: none; /* Non-prefixed version, currently_x000D_
                                  supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
  Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
  Unselectable text._x000D_
</p>
_x000D_
_x000D_
_x000D_


Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.


More information can be found in Mozilla Developer Network documentation.

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

Check if a value is within a range of numbers

I like Pointy's between function so I wrote a similar one that worked well for my scenario.

/**
 * Checks if an integer is within Β±x another integer.
 * @param {int} op - The integer in question
 * @param {int} target - The integer to compare to
 * @param {int} range - the range Β±
 */
function nearInt(op, target, range) {
    return op < target + range && op > target - range;
}

so if you wanted to see if x was within Β±10 of y:

var x = 100;
var y = 115;
nearInt(x,y,10) = false

I'm using it for detecting a long-press on mobile:

//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);

Choosing a jQuery datagrid plugin?

You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations

Update

The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:

How can I show three columns per row?

Try this one using Grid Layout:

_x000D_
_x000D_
.grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: auto auto auto;_x000D_
  padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
  background-color: rgba(255, 255, 255, 0.8);_x000D_
  border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
  padding: 20px;_x000D_
  font-size: 30px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
  <div class="grid-item">1</div>_x000D_
  <div class="grid-item">2</div>_x000D_
  <div class="grid-item">3</div>  _x000D_
  <div class="grid-item">4</div>_x000D_
  <div class="grid-item">5</div>_x000D_
  <div class="grid-item">6</div>  _x000D_
  <div class="grid-item">7</div>_x000D_
  <div class="grid-item">8</div>_x000D_
  <div class="grid-item">9</div>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to replace comma (,) with a dot (.) using java

Just use str.replace(',', '.') - it is both fast and efficient when a single character is to be replaced. And if the comma doesn't exist, it does nothing.

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

Android translate animation - permanently move View to new position using AnimationListener

You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.

myView.animate().x(50f).y(100f);

myView.animate().translateX(pixelInScreen) 

Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

What ports does RabbitMQ use?

Port Access

Firewalls and other security tools may prevent RabbitMQ from binding to a port. When that happens, RabbitMQ will fail to start. Make sure the following ports can be opened:

4369: epmd, a peer discovery service used by RabbitMQ nodes and CLI tools

5672, 5671: used by AMQP 0-9-1 and 1.0 clients without and with TLS

25672: used by Erlang distribution for inter-node and CLI tools communication and is allocated from a dynamic range (limited to a single port by default, computed as AMQP port + 20000). See networking guide for details.

15672: HTTP API clients and rabbitmqadmin (only if the management plugin is enabled)

61613, 61614: STOMP clients without and with TLS (only if the STOMP plugin is enabled)

1883, 8883: (MQTT clients without and with TLS, if the MQTT plugin is enabled

15674: STOMP-over-WebSockets clients (only if the Web STOMP plugin is enabled)

15675: MQTT-over-WebSockets clients (only if the Web MQTT plugin is enabled)

Reference doc: https://www.rabbitmq.com/install-windows-manual.html

Excel 2010 VBA Referencing Specific Cells in other worksheets

Private Sub Click_Click()

 Dim vaFiles As Variant
 Dim i As Long

For j = 1 To 2
vaFiles = Application.GetOpenFilename _
     (FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
     Title:="Open File(s)", MultiSelect:=True)

If Not IsArray(vaFiles) Then Exit Sub

 With Application
  .ScreenUpdating = False
  For i = 1 To UBound(vaFiles)
     Workbooks.Open vaFiles(i)
     wrkbk_name = vaFiles(i)
    Next i
  .ScreenUpdating = True
End With

If j = 1 Then
work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
End If



Next j

'Filling the values of the group name

'check = Application.WorksheetFunction.Search(Name, work1)
check = InStr(UCase("Qoute Request"), work1)

If check = 1 Then
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
End If

ActiveWorkbook.Sheets("GI Quote Request").Select
ActiveSheet.Range("B4:C12").Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Range("K3").Select
ActiveSheet.Paste


Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select

Range("D3").Value = Range("L3").Value
Range("D7").Value = Range("L9").Value
Range("D11").Value = Range("L7").Value

For i = 4 To 5

If i = 5 Then
GoTo NextIteration
End If

If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
    ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
 End If

NextIteration:
Next i

'eligibles part
Count = Range("D11").Value
For i = 27 To Count + 24
Range("C" & i).EntireRow.Offset(1, 0).Insert
Next i

check = Left(work1, InStrRev(work1, ".") - 1)

'check = InStr("Census", work1)
If check = "Census" Then
workbk = work1
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
workbk = work2
End If

'DOB
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("D2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
ActiveSheet.Range("C27").Select
ActiveSheet.Paste

'Gender
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("C2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False

ActiveSheet.Range("k27").Select
ActiveSheet.Paste

For i = 27 To Count + 27
ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
Next i

'Salary
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("N2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False

ActiveSheet.Range("F27").Select
ActiveSheet.Paste


ActiveSheet.Range("K3:L" & Count).Select
selction.ClearContents
End Sub

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

How to declare a local variable in Razor?

If you're looking for a int variable, one that increments as the code loops, you can use something like this:

@{
  int counter = 1;

  foreach (var item in Model.Stuff) {
    ... some code ...
    counter = counter + 1;
  }
} 

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

Why does Eclipse complain about @Override on interface methods?

Project specific settings may be enabled. Select your project Project > Properties > Java Compiler, uncheck the Enable project specific settings or change Jdk 1.6 and above not forgetting the corresponding JRE.
Incase it does not work, remove your project from eclipse, delete .settings folders, .project, .classpath files. clean and build the project, import it back into eclipse and then reset your Java compiler. Clean and build your projectand eclipse. It worked for me

phpMyAdmin - Error > Incorrect format parameter?

I had this problem but with a docker container (phpmyadmin users),

Solution:

  • Enter in the phpmyadmin container docker exec -it idcontainer /bin/bash
  • Move cd /usr/local/etc/php/
  • Create php.ini file
  • Modify it upload_max_filesize=128M post_max_size=128M max_execution_time=1000
  • Save and restart container.

This problem was in a Windows pc, at Linux i didnt need to do this.

No Access-Control-Allow-Origin header is present on the requested resource

Solution:
Instead of using setHeader method I have used addHeader.

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains, For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

For issues related to IE<=9, Please see here.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

How to make sure that string is valid JSON using JSON.NET

I found that JToken.Parse incorrectly parses invalid JSON such as the following:

{
"Id" : , 
"Status" : 2
}

Paste the JSON string into http://jsonlint.com/ - it is invalid.

So I use:

public static bool IsValidJson(this string input)
{
    input = input.Trim();
    if ((input.StartsWith("{") && input.EndsWith("}")) || //For object
        (input.StartsWith("[") && input.EndsWith("]"))) //For array
    {
        try
        {
            //parse the input into a JObject
            var jObject = JObject.Parse(input);

            foreach(var jo in jObject)
            {
                string name = jo.Key;
                JToken value = jo.Value;

                //if the element has a missing value, it will be Undefined - this is invalid
                if (value.Type == JTokenType.Undefined)
                {
                    return false;
                }
            }
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            Console.WriteLine(jex.Message);
            return false;
        }
        catch (Exception ex) //some other exception
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
    }
    else
    {
        return false;
    }

    return true;
}

How can I check if the array of objects have duplicate property values?

ECMA Script 6 Version

If you are in an environment which supports ECMA Script 6's Set, then you can use Array.prototype.some and a Set object, like this

let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
    return seen.size === seen.add(currentObject.name).size;
});

Here, we insert each and every object's name into the Set and we check if the size before and after adding are the same. This works because Set.size returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.


ECMA Script 5 Version

If you don't have Set support, then you can use a normal JavaScript object itself, like this

var seen = {};
var hasDuplicates = values.some(function(currentObject) {

    if (seen.hasOwnProperty(currentObject.name)) {
        // Current name is already seen
        return true;
    }

    // Current name is being seen for the first time
    return (seen[currentObject.name] = false);
});

The same can be written succinctly, like this

var seen = {};
var hasDuplicates = values.some(function (currentObject) {
    return seen.hasOwnProperty(currentObject.name)
        || (seen[currentObject.name] = false);
});

Note: In both the cases, we use Array.prototype.some because it will short-circuit. The moment it gets a truthy value from the function, it will return true immediately, it will not process rest of the elements.

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

PIG how to count a number of rows in alias

Basic counting is done as was stated in other answers, and in the pig documentation:

logs = LOAD 'log';
all_logs_in_a_bag = GROUP logs ALL;
log_count = FOREACH all_logs_in_a_bag GENERATE COUNT(logs);
dump log_count

You are right that counting is inefficient, even when using pig's builtin COUNT because this will use one reducer. However, I had a revelation today that one of the ways to speed it up would be to reduce the RAM utilization of the relation we're counting.

In other words, when counting a relation, we don't actually care about the data itself so let's use as little RAM as possible. You were on the right track with your first iteration of the count script.

logs = LOAD 'log'
ones = FOREACH logs GENERATE 1 AS one:int;
counter_group = GROUP ones ALL;
log_count = FOREACH counter_group GENERATE COUNT(ones);
dump log_count

This will work on much larger relations than the previous script and should be much faster. The main difference between this and your original script is that we don't need to sum anything.

This also doesn't have the same problem as other solutions where null values would impact the count. This will count all the rows, regardless of if the first column is null or not.

What is the size of column of int(11) in mysql in bytes?

An INT will always be 4 bytes no matter what length is specified.

  • TINYINT = 1 byte (8 bit)
  • SMALLINT = 2 bytes (16 bit)
  • MEDIUMINT = 3 bytes (24 bit)
  • INT = 4 bytes (32 bit)
  • BIGINT = 8 bytes (64 bit).

The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 stored as int(3) will still show as 12345, but if it was stored as int(10) it would still display as 12345, but you would have the option to pad the first five digits. For example, if you added ZEROFILL it would display as 0000012345.

... and the maximum value will be 2147483647 (Signed) or 4294967295 (Unsigned)

MySQL - select data from database between two dates

You can use MySQL DATE function like below

For instance, if you want results between 2017-09-05 till 2017-09-09

SELECT DATE(timestamp_field) as date FROM stocks_annc WHERE DATE(timestamp_field) >= '2017-09-05' AND DATE(timestamp_field) <= '2017-09-09'

Make sure to wrap the dates within single quotation ''

Hope this helps.

Java 8 stream map to list of keys sorted by values

Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");

List<String> list = map.values()
                       .stream()
                       .sorted()
                       .collect(Collectors.toList());

Output: [A, B, C, D]

Node Sass couldn't find a binding for your current environment

None of the install/rebuild solutions resolved the issue for me (using gulp).

Here is how I resolved it:

1) Download the missing binding file from the repository.

2) Rename the file binding.node.

3) Create node_modules/node-sass/vendor/darwin-x64-11 (path from error message) directory if it doesn't exist.

4) Add the binding file to node_modules/node-sass/vendor/darwin-x64-11

Angular 2 two way binding using ngModel is not working

As per Angular2 final, you do not even have to import FORM_DIRECTIVES as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.

Just replace ng-model with ngModel and wrap it in a box of bananas. But you have spilt the code into two files now:

app.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'ng-app',
  template: `
    <input id="name" type="text" [(ngModel)]="name"  />
    {{ name }}
  `
})
export class DataBindingComponent {
  name: string;

  constructor() {
    this.name = 'Jose';
  }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above

@NgModule({
  declarations: [DataBindingComponent],
  imports:      [BrowserModule, FormsModule],
  bootstrap:    [DataBindingComponent]
})
export default class MyAppModule {}

platformBrowserDynamic().bootstrapModule(MyAppModule);

How can I filter a date of a DateTimeField in Django?

Now Django has __date queryset filter to query datetime objects against dates in development version. Thus, it will be available in 1.9 soon.

Submit form using a button outside the <form> tag

I had an issue where I was trying to hide the form from a table cell element, but still show the forms submit-button. The problem was that the form element was still taking up an extra blank space, making the format of my table cell look weird. The display:none and visibility:hidden attributes didn't work because it would hide the submit button as well, since it was contained within the form I was trying to hide. The simple answer was to set the forms height to barely nothing using CSS

So,

CSS -

    #formID {height:4px;}

worked for me.

Visual Studio Code open tab in new window

You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.

I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.

Compile/run assembler in Linux?

For Ubuntu 18.04 installnasm . Open the terminal and type:

sudo apt install as31 nasm

nasm docs

For compiling and running:

nasm -f elf64 example.asm # assemble the program  
ld -s -o example example.o # link the object file nasm produced into an executable file  
./example # example is an executable file

Index of element in NumPy array

Use np.where to get the indices where a given condition is True.

Examples:

For a 2D np.ndarray called a:

i, j = np.where(a == value) # when comparing arrays of integers

i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays

For a 1D array:

i, = np.where(a == value) # integers

i, = np.where(np.isclose(a, value)) # floating-point

Note that this also works for conditions like >=, <=, != and so forth...

You can also create a subclass of np.ndarray with an index() method:

class myarray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        return np.array(*args, **kwargs).view(myarray)
    def index(self, value):
        return np.where(self == value)

Testing:

a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3,  4,  5,  8,  9, 10]),)

How do I format a number to a dollar amount in PHP

In PHP and C++ you can use the printf() function

printf("$%01.2f", $money);

Convert List<T> to ObservableCollection<T> in WP7

ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);

Java - Search for files in a directory

Using Java 8+ features we can write the code in few lines:

protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(f -> f.getFileName().toString().equals(fileName))
                .collect(Collectors.toList());

    }
}

Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.

Note that the documentation of Files.walk requires

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

I'm using the try-resource-statement.


For advanced searches an alternative is to use a PathMatcher:

protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(matcher::matches)
                .collect(Collectors.toList());

    }
}

An example how to use it to find a certain file:

public static void main(String[] args) throws IOException {
    String searchDirectory = args[0];
    String fileName = args[1];
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
    Collection<Path> find = find(searchDirectory, matcher);
    System.out.println(find);
}

More about it: Oracle Finding Files tutorial

Is there a way to force npm to generate package-lock.json?

package-lock.json is re-generated whenever you run npm i.

PHP How to find the time elapsed since a date time?

Use This one and you can get the

    $previousDate = '2013-7-26 17:01:10';
    $startdate = new DateTime($previousDate);
    $endDate   = new DateTime('now');
    $interval  = $endDate->diff($startdate);
    echo$interval->format('%y years, %m months, %d days');

Refer this http://ca2.php.net/manual/en/dateinterval.format.php

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

Linux c++ error: undefined reference to 'dlopen'

I was using CMake to compile my project and I've found the same problem.

The solution described here works like a charm, simply add ${CMAKE_DL_LIBS} to the target_link_libraries() call

java : non-static variable cannot be referenced from a static context Error

The simplest change would be something like this:

public static void main (String[] args) throws Exception {
  testconnect obj = new testconnect();
  obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
  obj.con2.close();
}

Changing datagridview cell color dynamically

This works for me

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

Creating a URL in the controller .NET MVC

I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.

My solution looks like this:

string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });

This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.

EDIT: I found this useful as well.

Convert .pfx to .cer

If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:

Get-PfxCertificate -FilePath InputBundle.pfx | 
Export-Certificate -FilePath OutputCert.der -Type CERT

Newline added for clarity, but you can of course have this all on a single line.

If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem

If you need to export to a different format than DER encoded, you can change the -Type parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed:

-Type <CertType>
    Specifies the type of output file for the certificate export as follows. 
     -- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates. 
     -- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate. 
     -- P7B: A PKCS#7 file format which can contain one or more certificates.

how to call a variable in code behind to aspx page

The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:


private string clients;
public string Clients { get { return clients; } }

UPDATE: It can also be declared as protected, as stated in the comments below.

Then, to call it on the ASPX side:

<%=Clients%>

Note that this won't work if you place it on a server tag attribute. For example:

<asp:Label runat="server" Text="<%=Clients%>" />

This isn't valid. This is:

<div><%=Clients%></div>

How to loop through an associative array and get the key?

Use $key => $val to get the keys:

<?php

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10",
);

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>

Reading a binary input stream into a single byte array in Java

Please keep in mind that the answers here assume that the length of the file is less than or equal to Integer.MAX_VALUE(2147483647).

If you are reading in from a file, you can do something like this:

    File file = new File("myFile");
    byte[] fileData = new byte[(int) file.length()];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(fileData);
    dis.close();

UPDATE (May 31, 2014):

Java 7 adds some new features in the java.nio.file package that can be used to make this example a few lines shorter. See the readAllBytes() method in the java.nio.file.Files class. Here is a short example:

import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

// ...
        Path p = FileSystems.getDefault().getPath("", "myFile");
        byte [] fileData = Files.readAllBytes(p);

Android has support for this starting in Api level 26 (8.0.0, Oreo).

How to export collection to CSV in MongoDB?

I could not get mongoexport to do this for me. I found that,to get an exhaustive list of all the fields, you need to loop through the entire collection once. Use this to generate the headers. Then loop through the collection again to populate these headers for each document.

I've written a script to do just this. Converting MongoDB docs to csv irrespective of schema differences between individual documents.

https://github.com/surya-shodan/mongoexportcsv

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface

But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

What is the difference between varchar and varchar2 in Oracle?

After some experimentation (see below), I can confirm that as of September 2017, nothing has changed with regards to the functionality described in the accepted answer:-

  1. Rextester demo for Oracle 11g: Empty strings are inserted as NULLs for both VARCHAR and VARCHAR2.
  2. LiveSQL demo for Oracle 12c: Same results.

The historical reason for these two keywords is explained well in an answer to a different question.

Git error when trying to push -- pre-receive hook declined

in sometimes, because the branch you are pushing has been protected, so you can ask the repository's maintainers to change the protecting status. in git-lab , you can find it in

Settings > Repository > Protected Branches .

:)

How to break nested loops in JavaScript?

function myFunction(){
  for(var i = 0;i < n;i++){
    for(var m = 0;m < n;m++){
      if(/*break condition*/){
        goto out;
      }
    }
  }
out:
 //your out of the loop;
}

importing go files in same folder

Any number of files in a directory are a single package; symbols declared in one file are available to the others without any imports or qualifiers. All of the files do need the same package foo declaration at the top (or you'll get an error from go build).

You do need GOPATH set to the directory where your pkg, src, and bin directories reside. This is just a matter of preference, but it's common to have a single workspace for all your apps (sometimes $HOME), not one per app.

Normally a Github path would be github.com/username/reponame (not just github.com/xxxx). So if you want to have main and another package, you may end up doing something under workspace/src like

github.com/
  username/
    reponame/
      main.go   // package main, importing "github.com/username/reponame/b"
      b/
        b.go    // package b

Note you always import with the full github.com/... path: relative imports aren't allowed in a workspace. If you get tired of typing paths, use goimports. If you were getting by with go run, it's time to switch to go build: run deals poorly with multiple-file mains and I didn't bother to test but heard (from Dave Cheney here) go run doesn't rebuild dirty dependencies.

Sounds like you've at least tried to set GOPATH to the right thing, so if you're still stuck, maybe include exactly how you set the environment variable (the command, etc.) and what command you ran and what error happened. Here are instructions on how to set it (and make the setting persistent) under Linux/UNIX and here is the Go team's advice on workspace setup. Maybe neither helps, but take a look and at least point to which part confuses you if you're confused.

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

convert string to date in sql server

This will do the trick:

SELECT CONVERT(char(10), GetDate(),126)

How to scroll to bottom in react?

In order to scroll down to the bottom of the page first we have to select an id which resides at the bottom of the page. Then we can use the document.getElementById to select the id and scroll down using scrollIntoView(). Please refer the below code.

   scrollToBottom= async ()=>{
      document.getElementById('bottomID').scrollIntoView();
    }

LINQ to SQL Left Outer Join

I found 1 solution. if want to translate this kind of SQL (left join) into Linq Entity...

SQL:

SELECT * FROM [JOBBOOKING] AS [t0]
LEFT OUTER JOIN [REFTABLE] AS [t1] ON ([t0].[trxtype] = [t1].[code])
                                  AND ([t1]. [reftype] = "TRX")

LINQ:

from job in JOBBOOKINGs
join r in (from r1 in REFTABLEs where r1.Reftype=="TRX" select r1) 
          on job.Trxtype equals r.Code into join1
from j in join1.DefaultIfEmpty()
select new
{
   //cols...
}

SQL, How to convert VARCHAR to bigint?

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.

select CONVERT(bigint,'60') as seconds 

and it returns

60

How can I run NUnit tests in Visual Studio 2017?

This one helped me:

Getting started with .NET unit testing using NUnit

Basically:

  • Add the NUnit 3 library in NuGet.
  • Create the class you want to test.
  • Create a separate testing class. This should have [TestFixture] above it.
  • Create a function in the testing class. This should have [Test] above it.
  • Then go into TEST/WINDOW/TEST EXPLORER (across the top).
  • Click run to the left-hand side. It will tell you what has passed and what has failed.

My example code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace NUnitTesting
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    public class Maths
    {
        public int Add(int a, int b)
        {
            int x = a + b;
            return x;
        }
    }

    [TestFixture]
    public class TestLogging
    {
        [Test]
        public void Add()
        {
            Maths add = new Maths();
            int expectedResult = add.Add(1, 2);
            Assert.That(expectedResult, Is.EqualTo(3));
        }
    }
}

This will return true, and if you change the parameter in Is.EqualTo it will fail, etc.

How to use 'cp' command to exclude a specific directory?

ls -I "filename1" -I "filename2" | xargs cp -rf -t destdir 

The first part ls all the files but hidden specific files with flag -I. The output of ls is used as standard input for the second part. xargs build and execute command cp -rf -t destdir from standard input. the flag -r means copy directories recursively, -f means copy files forcibly which will overwrite the files in the destdir, -t specify the destination directory copy to.

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

There is a simple technique to handle this.

Code:

number=[1,2,3,4,5,6] #Original list
another=[] #another empty list
for a in number: #here I am declaring variable (a) as an item in the list (number)
    another.append(a) #here we are adding the items of list (number) to list (another)
print(another)

Output:

>>> [1,2,3,4,5,6]

I hope this was useful for your query.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

How can I make a JPA OneToOne relation lazy

Here's something that has been working for me (without instrumentation):

Instead of using @OneToOne on both sides, I use @OneToMany in the inverse part of the relationship (the one with mappedBy). That makes the property a collection (List in the example below), but I translate it into an item in the getter, making it transparent to the clients.

This setup works lazily, that is, the selects are only made when getPrevious() or getNext() are called - and only one select for each call.

The table structure:

CREATE TABLE `TB_ISSUE` (
    `ID`            INT(9) NOT NULL AUTO_INCREMENT,
    `NAME`          VARCHAR(255) NULL,
    `PREVIOUS`      DECIMAL(9,2) NULL
    CONSTRAINT `PK_ISSUE` PRIMARY KEY (`ID`)
);
ALTER TABLE `TB_ISSUE` ADD CONSTRAINT `FK_ISSUE_ISSUE_PREVIOUS`
                 FOREIGN KEY (`PREVIOUS`) REFERENCES `TB_ISSUE` (`ID`);

The class:

@Entity
@Table(name = "TB_ISSUE") 
public class Issue {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;

    @Column
    private String name;

    @OneToOne(fetch=FetchType.LAZY)  // one to one, as expected
    @JoinColumn(name="previous")
    private Issue previous;

    // use @OneToMany instead of @OneToOne to "fake" the lazy loading
    @OneToMany(mappedBy="previous", fetch=FetchType.LAZY)
    // notice the type isnt Issue, but a collection (that will have 0 or 1 items)
    private List<Issue> next;

    public Integer getId() { return id; }
    public String getName() { return name; }

    public Issue getPrevious() { return previous; }
    // in the getter, transform the collection into an Issue for the clients
    public Issue getNext() { return next.isEmpty() ? null : next.get(0); }

}

Angular 2 'component' is not a known element

I know this is a long resolved problem, but in my case I had a different solution. It was actually a mistake I made that maybe you made as well and didn't fully notice. My mistake was that I accidentally placed a Module e.g., MatChipsModule, MatAutoCompleteModule, on the declarations section; the section that is composed only by components e.g., MainComponent, AboutComponent. This made all my other import unrecognizable.

Add data dynamically to an Array

You should use method array_push to add value or array to array exists

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

/** GENERATED OUTPUT
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
*/

Strip HTML from strings in Python

Simple code!. This will remove all kind of tags and content inside of it.

def rm(s):
    start=False
    end=False
    s=' '+s
    for i in range(len(s)-1):
        if i<len(s):
            if start!=False:
                if s[i]=='>':
                    end=i
                    s=s[:start]+s[end+1:]
                    start=end=False
            else:
                if s[i]=='<':
                    start=i
    if s.count('<')>0:
        self.rm(s)
    else:
        s=s.replace('&nbsp;', ' ')
        return s

But it won't give full result if text contains <> symbols inside it.

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

Read/Write String from/to a File in Android

I'm a bit of a beginner and struggled getting this to work today.

Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!

public class HighScore {
    File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
    File file = new File(data, "highscore.txt");
    private int highScore = 0;

    public int readHighScore() {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            try {
                highScore = Integer.parseInt(br.readLine());
                br.close();
            } catch (NumberFormatException | IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            try {
                file.createNewFile();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            e.printStackTrace();
        }
        return highScore;
    }

    public void writeHighScore(int highestScore) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(String.valueOf(highestScore));
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

http post - how to send Authorization header?

Here is the detailed answer to the question:

Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).

There is more than one way we can pass data into the headers. The syntax is different but all means the same.

// Option 1 
 const httpOptions = {
   headers: new HttpHeaders({
     'Authorization': 'my-auth-token',
     'ID': emp.UserID,
   })
 };


// Option 2

let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');    

let options = {headers:httpHeaders};


// Option 1
   return this.http.post(this.url + 'testMethod', body,httpOptions)

// Option 2
   return this.http.post(this.url + 'testMethod', body,options)

In the call you can find the field passed as a header as shown in the image below : enter image description here

Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)

  • Response to preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access

  • Response for preflight does not have HTTP ok status.

Find my detailed answer at https://stackoverflow.com/a/52620468/3454221

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

The accepted answer to set git config core.filemode false, works, but with consequences. Setting core.filemode to false tells git to ignore any executable bit changes on the filesystem so it won't view this as a change. If you do need to stage an executable bit change for this repository anytime in the future, you would have to do it manually, or set core.filemode back to true.

A less consequential alternative, if all the modified files should have mode 100755, is to do something like

chmod 100755 $(git ls-files --modified)

which just does exactly the change in mode, no more, no less, without additional implications.

(in my case, it was due to a OneDrive sync with my filesystem on MacOS; by not changing core.filemode, I'm leaving the possibility open that the mode change might happen again in the future; in my case, I'd like to know if it happens again, and changing core.filemode will hide it from me, which I don't want)

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Selecting last element in JavaScript array

Use JavaScript objects if this is critical to your application. You shouldn't be using raw primitives to manage critical parts of your application. As this seems to be the core of your application, you should use objects instead. I've written some code below to help get you started. The method lastLocation would return the last location.


function User(id) {
    this.id = id;

    this.locations = [];

    this.getId = function() {
        return this.id;
    };

    this.addLocation = function(latitude, longitude) {
        this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
    };

    this.lastLocation = function() {
        return this.locations[this.locations.length - 1];
    };

    this.removeLastLocation = function() {
        return this.locations.pop();
    };

}

function Users() {
    this.users = {};

    this.generateId = function() {
        return Math.random();
    };

    this.createUser = function() {
        var id = this.generateId();
        this.users[id] = new User(id);
        return this.users[id];
    };

    this.getUser = function(id) {
        return this.users[id];
    };

    this.removeUser = function(id) {
        var user = this.getUser(id);
        delete this.users[id];

        return user;
    };

}


var users = new Users();

var user = users.createUser();

user.addLocation(0, 0);
user.addLocation(0, 1);

Can't use method return value in write context

The issue is this, you want to know if the error is not empty.

public function getError() {
    return $this->error;
}

Adding a method isErrorSet() will solve the problem.

public function isErrorSet() {
    if (isset($this->error) && !empty($this->error)) {
        return true;
    } else {
        return false;
    }
}

Now this will work fine with this code with no notice.

if (!($x->isErrorSet())) {
    echo $x->getError();
}

passing 2 $index values within nested ng-repeat

When you are dealing with objects, you want to ignore simple id's as much as convenient.

If you change the click line to this, I think you will be well on your way:

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">

Also, I think you may need to change

class="tutorial_title {{tutorial.active}}"

to something like

ng-class="tutorial_title {{tutorial.active}}"

See http://docs.angularjs.org/misc/faq and look for ng-class.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Callback to a Fragment from a DialogFragment

Updated:

I made a library based on my gist code that generates those casting for you by using @CallbackFragment and @Callback.

https://github.com/zeroarst/callbackfragment.

And the example give you the example that send a callback from a fragment to another fragment.

Old answer:

I made a BaseCallbackFragment and annotation @FragmentCallback. It currently extends Fragment, you can change it to DialogFragment and will work. It checks the implementations with the following order: getTargetFragment() > getParentFragment() > context (activity).

Then you just need to extend it and declare your interfaces in your fragment and give it the annotation, and the base fragment will do the rest. The annotation also has a parameter mandatory for you to determine whether you want to force the fragment to implement the callback.

public class EchoFragment extends BaseCallbackFragment {

    private FragmentInteractionListener mListener;

    @FragmentCallback
    public interface FragmentInteractionListener {
        void onEcho(EchoFragment fragment, String echo);
    }
}

https://gist.github.com/zeroarst/3b3f32092d58698a4568cdb0919c9a93

What is the difference between `let` and `var` in swift?

var value can be change, after initialize. But let value is not be change, when it is intilize once.

In case of var

  function variable() {
     var number = 5, number = 6;
     console.log(number); // return console value is 6
   }
   variable();

In case of let

   function abc() {
      let number = 5, number = 6;
      console.log(number); // TypeError: redeclaration of let number
   }
   abc();

How to easily duplicate a Windows Form in Visual Studio?

I have been using another way of copying forms since vb6.

  1. File Menu / SE - Save CurrentForm.cs as - NewForm.cs
  2. Change its Name to NewForm in Properties window.
  3. In Solution Explorer - Add Existing Item - CurrentForm.cs
  4. Usually in MDI form (where CurrentForm is referred) - CurrentFormToolStripMenuItem_Click event - change reference back to CurrentForm (which is automatically changed to NewForm in step 1).

comments welcome.

Launching a website via windows commandline

start chrome https://www.google.com/ or start firefox https://www.google.com/

Oracle SQL Developer spool output?

For Spooling in Oracle SQL Developer, here is the solution.

set heading on

set linesize 1500

set colsep '|'

set numformat 99999999999999999999

set pagesize 25000

spool E:\abc.txt

@E:\abc.sql;

spool off

The hint is :

  1. when we spool from sql plus , then the whole query is required.

  2. when we spool from Oracle Sql Developer , then the reference path of the query required as given in the specified example.

Go build: "Cannot find package" (even though GOPATH is set)

Although the accepted answer is still correct about needing to match directories with package names, you really need to migrate to using Go modules instead of using GOPATH. New users who encounter this problem may be confused about the mentions of using GOPATH (as was I), which are now outdated. So, I will try to clear up this issue and provide guidance associated with preventing this issue when using Go modules.

If you're already familiar with Go modules and are experiencing this issue, skip down to my more specific sections below that cover some of the Go conventions that are easy to overlook or forget.

This guide teaches about Go modules: https://golang.org/doc/code.html

Project organization with Go modules

Once you migrate to Go modules, as mentioned in that article, organize the project code as described:

A repository contains one or more modules. A module is a collection of related Go packages that are released together. A Go repository typically contains only one module, located at the root of the repository. A file named go.mod there declares the module path: the import path prefix for all packages within the module. The module contains the packages in the directory containing its go.mod file as well as subdirectories of that directory, up to the next subdirectory containing another go.mod file (if any).

Each module's path not only serves as an import path prefix for its packages, but also indicates where the go command should look to download it. For example, in order to download the module golang.org/x/tools, the go command would consult the repository indicated by https://golang.org/x/tools (described more here).

An import path is a string used to import a package. A package's import path is its module path joined with its subdirectory within the module. For example, the module github.com/google/go-cmp contains a package in the directory cmp/. That package's import path is github.com/google/go-cmp/cmp. Packages in the standard library do not have a module path prefix.

You can initialize your module like this:

$ go mod init github.com/mitchell/foo-app

Your code doesn't need to be located on github.com for it to build. However, it's a best practice to structure your modules as if they will eventually be published.

Understanding what happens when trying to get a package

There's a great article here that talks about what happens when you try to get a package or module: https://medium.com/rungo/anatomy-of-modules-in-go-c8274d215c16 It discusses where the package is stored and will help you understand why you might be getting this error if you're already using Go modules.

Ensure the imported function has been exported

Note that if you're having trouble accessing a function from another file, you need to ensure that you've exported your function. As described in the first link I provided, a function must begin with an upper-case letter to be exported and made available for importing into other packages.

Names of directories

Another critical detail (as was mentioned in the accepted answer) is that names of directories are what define the names of your packages. (Your package names need to match their directory names.) You can see examples of this here: https://medium.com/rungo/everything-you-need-to-know-about-packages-in-go-b8bac62b74cc With that said, the file containing your main method (i.e., the entry point of your application) is sort of exempt from this requirement.

As an example, I had problems with my imports when using a structure like this:

/my-app
+-- go.mod
+-- /src
   +-- main.go
   +-- /utils
      +-- utils.go

I was unable to import the code in utils into my main package.

However, once I put main.go into its own subdirectory, as shown below, my imports worked just fine:

/my-app
+-- go.mod
+-- /src
   +-- /app
   |  +-- main.go
   +-- /utils
      +-- utils.go

In that example, my go.mod file looks like this:

module git.mydomain.com/path/to/repo/my-app

go 1.14

When I saved main.go after adding a reference to utils.MyFunction(), my IDE automatically pulled in the reference to my package like this:

import "git.mydomain.com/path/to/repo/my-app/src/my-app"

(I'm using VS Code with the Golang extension.)

Notice that the import path included the subdirectory to the package.

Dealing with a private repo

If the code is part of a private repo, you need to run a git command to enable access. Otherwise, you can encounter other errors This article mentions how to do that for private Github, BitBucket, and GitLab repos: https://medium.com/cloud-native-the-gathering/go-modules-with-private-git-repositories-dfe795068db4 This issue is also discussed here: What's the proper way to "go get" a private repository?

How to easily import multiple sql files into a MySQL database?

Just type below command on your command prompt & it will bind all sql file into single sql file,

c:/xampp/mysql/bin/sql/ type *.sql > OneFile.sql;

clearing select using jquery

Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.

<select multiple='multiple' id='selectListName'> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
    <option>4</option>
</select>

In some function called based on some event, the following code would clear all selected options.

$("#selectListName").prop('selectedIndex', -1);

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

Handling optional parameters in javascript

You can know how many arguments were passed to your function and you can check if your second argument is a function or not:

function getData (id, parameters, callback) {
  if (arguments.length == 2) { // if only two arguments were supplied
    if (Object.prototype.toString.call(parameters) == "[object Function]") {
      callback = parameters; 
    }
  }
  //...
}

You can also use the arguments object in this way:

function getData (/*id, parameters, callback*/) {
  var id = arguments[0], parameters, callback;

  if (arguments.length == 2) { // only two arguments supplied
    if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
      callback = arguments[1]; // if is a function, set as 'callback'
    } else {
      parameters = arguments[1]; // if not a function, set as 'parameters'
    }
  } else if (arguments.length == 3) { // three arguments supplied
      parameters = arguments[1];
      callback = arguments[2];
  }
  //...
}

If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.

How to draw a custom UIView that is just a circle - iPhone app

My contribution with a Swift extension:

extension UIView {
    func asCircle() {
        self.layer.cornerRadius = self.frame.width / 2;
        self.layer.masksToBounds = true
    }
}

Just call myView.asCircle()

How to change the color of a button?

You can change the colour two ways; through XML or through coding. I would recommend XML since it's easier to follow for beginners.

XML:

<Button
    android:background="@android:color/white"
    android:textColor="@android:color/black"
/>

You can also use hex values ex.

android:background="@android:color/white"

Coding:

//btn represents your button object

btn.setBackgroundColor(Color.WHITE);
btn.setTextColor(Color.BLACK);

mysqli_real_connect(): (HY000/2002): No such file or directory

You just need to rename ib_logfile0 and ib_logfile1 as ib_logfile_0 and ib_logfile_1. Then your problem would be solved.

Multiline string literal in C#

It's called a verbatim string literal in C#, and it's just a matter of putting @ before the literal. Not only does this allow multiple lines, but it also turns off escaping. So for example you can do:

string query = @"SELECT foo, bar
FROM table
WHERE name = 'a\b'";

This includes the line breaks (using whatever line break your source has them as) into the string, however. For SQL, that's not only harmless but probably improves the readability anywhere you see the string - but in other places it may not be required, in which case you'd either need to not use a multi-line verbatim string literal to start with, or remove them from the resulting string.

The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol:

string quote = @"Jon said, ""This will work,"" - and it did!";

Get Maven artifact version at runtime

I am using maven-assembly-plugin for my maven packaging. The usage of Apache Maven Archiver in Joachim Sauer's answer could also work:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
    <executions>
        <execution .../>
    </executions>
</plugin>

Because archiever is one of maven shared components, it could be used by multiple maven building plugins, which could also have conflict if two or more plugins introduced, including archive configuration inside.

Bootstrap 3: Keep selected tab on page refresh

Using html5 I cooked up this one:

Some where on the page:

<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>

The viewbag should just contain the id for the page/element eg.: "testing"

I created a site.js and added the scrip on the page:

/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
  function() {
    var setactive = $("#heading").data("activetab");
    var a = $('#' + setactive).addClass("active");
  }
)

Now all you have to do is to add your id's to your navbar. Eg.:

<ul class="nav navbar-nav">
  <li **id="testing" **>
    @Html.ActionLink("Lalala", "MyAction", "MyController")
  </li>
</ul>

All hail the data attribute :)

How to make type="number" to positive numbers only

add this code in your input type;

onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57"

for example:

<input type="text" name="age" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />

Early exit from function?

exit(); can be use to go for the next validation.

How can I express that two values are not equal to eachother?

if (!secondaryPassword.equals(initialPassword)) 

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

How can I get the current user directory?

May be this will be a good solution: taking in account whether this is Vista/Win7 or XP and without using environment variables:

string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
if ( Environment.OSVersion.Version.Major >= 6 ) {
    path = Directory.GetParent(path).ToString();
}

Though using the environment variable is much more clear.

Using Tkinter in python to edit the title bar

widget.winfo_toplevel().title("My_Title")

changes the title of either Tk or Toplevel instance that the widget is a child of.

How do I update a Mongo document after inserting it?

This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.

The methods save and update are deprecated.

save(to_save, manipulate=True, check_keys=True, **kwargs)ΒΆ Save a document in this collection.

DEPRECATED - Use insert_one() or replace_one() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

update(spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs) Update a document(s) in this collection.

DEPRECATED - Use replace_one(), update_one(), or update_many() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

in the OPs particular case, it's better to use replace_one.

How to store the hostname in a variable in a .bat file?

hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.

Filtering a list based on a list of booleans

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

Timing comparisons(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

Don't use filter as a variable name, it is a built-in function.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

To move a file or set of files using Tortoise SVN, right-click-and-drag the target files to their destination and release the right mouse button. The popup menu will have a SVN move versioned files here option.

Note that the destination folder must have already been added to the repository for the SVN move versioned files here option to appear.

How to get share counts using graph API

Check out this gist. It has snippets for how to get the sharing count for the following services:

  • Facebook
  • Twitter
  • Google plus
  • Pinterest
  • LinkedIn
  • StumbledUpon

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

The above could also be written with less code as:

new List<SomeType>(items).ForEach(
    i => Console.WriteLine(i)
);

This creates a generic list and populates it with the IEnumerable and then calls the list objects ForEach.

Groovy String to Date

Googling around for Groovy ways to "cast" a String to a Date, I came across this article: http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/

The author uses Groovy metaMethods to allow dynamically extending the behavior of any class' asType method. Here is the code from the website.

class Convert {
    private from
    private to

    private Convert(clazz) { from = clazz }
    static def from(clazz) {
        new Convert(clazz)
    }

    def to(clazz) {
        to = clazz
        return this
    }

    def using(closure) {
        def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
        from.metaClass.asType = { Class clazz ->
            if( clazz == to ) {
                closure.setProperty('value', delegate)
                closure(delegate)
            } else {
                originalAsType.doMethodInvoke(delegate, clazz)
            }
        }
    }
}

They provide a Convert class that wraps the Groovy complexity, making it trivial to add custom as-based type conversion from any type to any other:

Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }

def christmas = '12-25-2010' as Date

It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.

Change variable name in for loop using R

d <- 5
for(i in 1:10) { 
 nam <- paste("A", i, sep = "")
 assign(nam, rnorm(3)+d)
}

More info here or even here!

Can I add color to bootstrap icons only using CSS?

Another possible way to have bootstrap icons in a different color is to create a new .png in the desired color, (eg. magenta) and save it as /path-to-bootstrap-css/img/glyphicons-halflings-magenta.png

In your variables.less find

// Sprite icons path
// -------------------------
@iconSpritePath:          "../img/glyphicons-halflings.png";
@iconWhiteSpritePath:     "../img/glyphicons-halflings-white.png";

and add this line

@iconMagentaSpritePath:     "../img/glyphicons-halflings-magenta.png";

In your sprites.less add

/* Magenta icons with optional class, or on hover/active states of certain elements */
.icon-magenta,
.nav-pills > .active > a > [class^="icon-"],
.nav-pills > .active > a > [class*=" icon-"],
.nav-list > .active > a > [class^="icon-"],
.nav-list > .active > a > [class*=" icon-"],
.navbar-inverse .nav > .active > a > [class^="icon-"],
.navbar-inverse .nav > .active > a > [class*=" icon-"],
.dropdown-menu > li > a:hover > [class^="icon-"],
.dropdown-menu > li > a:hover > [class*=" icon-"],
.dropdown-menu > .active > a > [class^="icon-"],
.dropdown-menu > .active > a > [class*=" icon-"],
.dropdown-submenu:hover > a > [class^="icon-"],
.dropdown-submenu:hover > a > [class*=" icon-"] {
  background-image: url("@{iconMagentaSpritePath}");
}

And use it like this:

<i class='icon-chevron-down icon-magenta'></i>

Hope it helps someone.

ASP.NET Web API application gives 404 when deployed at IIS 7

For me, this issue was slightly different than other answers, as I was only receiving 404s on OPTIONS, yet I already had OPTIONS specifically stated in my Integrated Extensionless URL Handler options. Very confusing.

  1. As others have stated, runAllManagedModulesForAllRequests="true" in the modules node is an easy way to blanket-fix most Web API 404 issues - although I prefer @DavidAndroidDev 's answer which is much less intrusive. But there was something additional in my case.
  2. Unfortunately, I had this set in IIS under Request Filtering in the site:

OPTIONS Issue with Request Filtering

By adding the following security node to the web.config was necessary to knock that out - full system.webserver included for context:

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <remove name="WebDAV" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <security>
      <requestFiltering>
        <verbs>
          <remove verb="OPTIONS" />
        </verbs>
      </requestFiltering>
    </security>
  </system.webServer>

Although it's not the perfect answer for this question, it is the first result for "IIS OPTIONS 404" on Google, so I hope this helps someone out; cost me an hour today.

Best Practices for securing a REST API / web service

One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.

Convert an int to ASCII character

          A PROGRAM TO CONVERT INT INTO ASCII.




          #include<stdio.h>
          #include<string.h>
          #include<conio.h>

           char data[1000]= {' '};           /*thing in the bracket is optional*/
           char data1[1000]={' '};
           int val, a;
           char varray [9];

           void binary (int digit)
          {
              if(digit==0)
               val=48;
              if(digit==1)
               val=49;
              if(digit==2)
               val=50;
              if(digit==3)
               val=51;
              if(digit==4)
               val=52;
              if(digit==5)
               val=53;
              if(digit==6)
               val=54;
              if(digit==7)
               val=55;
              if(digit==8)
               val=56;
              if(digit==9)
                val=57;
                a=0;

           while(val!=0)
           {
              if(val%2==0)
               {
                varray[a]= '0';
               }

               else
               varray[a]='1';
               val=val/2;
               a++;
           }


           while(a!=7)
          {
            varray[a]='0';
            a++;
           }


          varray [8] = NULL;
          strrev (varray);
          strcpy (data1,varray);
          strcat (data1,data);
          strcpy (data,data1);

         }


          void main()
         {
           int num;
           clrscr();
           printf("enter number\n");
           scanf("%d",&num);
           if(num==0)
           binary(0);
           else
           while(num>0)
           {
           binary(num%10);
           num=num/10;
           }
           puts(data);
           getch();

           }

I check my coding and its working good.let me know if its helpful.thanks.