Programs & Examples On #Bcompiler

bcompiler enables you to encode your scripts in phpbytecode, enabling you to protect the source code. bcompiler could be used in the following situations

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

How to send an email with Python?

While indenting your code in the function (which is ok), you did also indent the lines of the raw message string. But leading white space implies folding (concatenation) of the header lines, as described in sections 2.2.3 and 3.2.3 of RFC 2822 - Internet Message Format:

Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding".

In the function form of your sendmail call, all lines are starting with white space and so are "unfolded" (concatenated) and you are trying to send

From: [email protected]    To: [email protected]    Subject: Hello!    This message was sent with Python's smtplib.

Other than our mind suggests, smtplib will not understand the To: and Subject: headers any longer, because these names are only recognized at the beginning of a line. Instead smtplib will assume a very long sender email address:

[email protected]    To: [email protected]    Subject: Hello!    This message was sent with Python's smtplib.

This won't work and so comes your Exception.

The solution is simple: Just preserve the message string as it was before. This can be done by a function (as Zeeshan suggested) or right away in the source code:

import smtplib

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    """this is some test documentation in the function"""
    message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

Now the unfolding does not occur and you send

From: [email protected]
To: [email protected]
Subject: Hello!

This message was sent with Python's smtplib.

which is what works and what was done by your old code.

Note that I was also preserving the empty line between headers and body to accommodate section 3.5 of the RFC (which is required) and put the include outside the function according to the Python style guide PEP-0008 (which is optional).

Converting a PDF to PNG

One can also use the command line utilities included in poppler-utils package:

sudo apt-get install poppler-utils
pdftoppm --help
pdftocairo --help

Example:

pdftocairo -png mypage.pdf mypage.png

Global variables in header file

Don't initialize variables in headers. Put declaration in header and initialization in one of the c files.

In the header:

extern int i;

In file2.c:

int i=1;

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Thread.sleep(1000);

is the worse: being a static wait, it will make test script slower.

driver.manage().timeouts.implicitlyWait(10,TimeUnit.SECONDS);

this is a dynamic wait

  • it is valid till webdriver existence or has a scope till driver lifetime
  • we can implicit wait also.

Finally, what I suggest is

WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.<different canned or predefined conditions are there>);

with some predefined conditions:

isAlertPresent();
elementToBeSelected();
visibilityOfElementLocated();
visibilityOfAllElementLocatedBy();
frameToBeAvailableAndSwitchToIt();
  • It is also dynamic wait
  • in this the wait will only be in seconds
  • we have to use explicit wait for a particular web element on which we want to use.

What does <> mean?

"Does not equal"

const char* concatenation

It seems like you're using C++ with a C library and therefore you need to work with const char *.

I suggest wrapping those const char * into std::string:

const char *a = "hello "; 
const char *b = "world"; 
std::string c = a; 
std::string d = b; 
cout << c + d;

How to get current class name including package name in Java?

use this.getClass().getName() to get packageName.className and use this.getClass().getSimpleName() to get only class name

connect to host localhost port 22: Connection refused

For my case(ubuntu 14.04, fresh installed), I just run the following command and it works!

sudo apt-get install ssh

How to enable curl in xampp?

You can add any extension (in Wamp and Xampp servers) by removing the semi-colon (;)

How to create a .gitignore file

On mac:

  • open terminal and run defaults write com.apple.finder AppleShowAllFiles YES anywhere.

  • restart finder so you can see hidden files: command + option + escape ---> Relaunch

Then create a text file and you will be able to change the file extension to .gitignore

Gradle: How to Display Test Results in the Console in Real Time?

For those using Kotlin DSL, you can do:

tasks {
  named<Test>("test") {
    testLogging.showStandardStreams = true
  }
}

Printing a java map Map<String, Object> - How?

I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet gives you a combined Object with the key and the value. So something like:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}

will do what you're after.


If you're using java 8, there's also the new streaming approach.

map.forEach((key, value) -> System.out.println(key + ":" + value));

Clicking HTML 5 Video element to play, pause video, breaks play button

How about this one

<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
   <source src="" type="video/mp4">
</video>

I want to get the type of a variable at runtime

So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:

val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x

But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:

val x: Any = 5
def f[T](v: T) = v match {
  case _: Int    => "Int"
  case _: String => "String"
  case _         => "Unknown"
}
f(x)

Here it doesn't matter what is the type of the variable, Any. What matters, what is checked is the type of 5, the value. In fact, T is useless -- you might as well have written it def f(v: Any) instead. Also, this uses either ClassTag or a value's Class, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_] (List of something), but not whether it is, for example, a List[Int] or List[String].

Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag or a TypeTag. For example:

val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"

A ClassTag will also let you use type parameters you received on match. This won't work:

def f[A, B](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}

But this will:

val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)

Here I'm using the context bounds syntax, B : ClassTag, which works just like the implicit parameter in the previous ClassTag example, but uses an anonymous variable.

One can also get a ClassTag from a value's Class, like this:

val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
  val B = ClassTag(b.getClass)
  ClassTag(a.getClass) match {
    case B => "a is the same class as b"
    case _ => "a is not the same class as b"
  }
}
f(x, y) == f(y, x) // true, a is the same class as b

A ClassTag is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag for List[Int] and List[String] is the same, List. If you need type parameters, then you must use a TypeTag instead. A TypeTag however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.

Examples with TypeTag can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:

import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int

Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag, so I'll stop here.

Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:

val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it

It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

Creating Roles in Asp.net Identity MVC 5

Here is the complete article describing how to create role, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains User interface, controller methods etc.

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Hope this helpls

Thanks

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

In my case, the error occured in phpmyadmin version 4.5.1 when i set lower_case_table_names = 2 and had a table name with uppercase characters, The table had a primary key set to auto increment but still showed the error. The issue stopped when i changed the table name to all lowercase.

What is the equivalent of Java's System.out.println() in Javascript?

I'm also about to ask the same question. But from what I've learned from codeacademy.com below code is enough to display the output or text?

print("hello world")  

Best way to encode text data for XML in Java?

Try this:

String xmlEscapeText(String t) {
   StringBuilder sb = new StringBuilder();
   for(int i = 0; i < t.length(); i++){
      char c = t.charAt(i);
      switch(c){
      case '<': sb.append("&lt;"); break;
      case '>': sb.append("&gt;"); break;
      case '\"': sb.append("&quot;"); break;
      case '&': sb.append("&amp;"); break;
      case '\'': sb.append("&apos;"); break;
      default:
         if(c>0x7e) {
            sb.append("&#"+((int)c)+";");
         }else
            sb.append(c);
      }
   }
   return sb.toString();
}

How can I change default dialog button text color in android 5

The color of the buttons and other text can also be changed via theme:

values-21/styles.xml

<style name="AppTheme" parent="...">
  ...
  <item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>

<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
  <item name="android:colorPrimary">#00397F</item>
  <item name="android:colorAccent">#0AAEEF</item>
</style>

The result:

Dialog Date picker

How to make a smooth image rotation in Android?

If you are using a set Animation like me you should add the interpolation inside the set tag:

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">

 <rotate
    android:duration="5000"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:startOffset="0"
    android:toDegrees="360" />

 <alpha
    android:duration="200"
    android:fromAlpha="0.7"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:toAlpha="1.0" />

</set>

That Worked for me.

How to parse XML using vba

Update

The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.

Public Sub LoadDocument()
    Dim xDoc As MSXML.DOMDocument
    Set xDoc = New MSXML.DOMDocument
    xDoc.validateOnParse = False
    If xDoc.Load("C:\My Documents\sample.xml") Then
        ' The document loaded successfully.
        ' Now do something intersting.
        DisplayNode xDoc.childNodes, 0
    Else
        ' The document failed to load.
        ' See the previous listing for error information.
    End If
End Sub

Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
   ByVal Indent As Integer)

   Dim xNode As MSXML.IXMLDOMNode
   Indent = Indent + 2

   For Each xNode In Nodes
      If xNode.nodeType = NODE_TEXT Then
         Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _
            ":" & xNode.nodeValue
      End If

      If xNode.hasChildNodes Then
         DisplayNode xNode.childNodes, Indent
      End If
   Next xNode
End Sub

Nota Bene - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.

Original Response

I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.

This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.

sample function


openTag = ""
closeTag = "" 

' Locate the position of the enclosing tags startPos = InStr(1, temp, openTag) endPos = InStr(1, temp, closeTag) startTagPos = InStr(startPos, temp, ">") + 1 ' Parse xml for returned value Data = Mid(temp, startTagPos, endPos - startTagPos)

Element-wise addition of 2 lists?

[a + b for a, b in zip(list1, list2)]

What is the difference between C and embedded C?

c cant access physical address, embedded c can access physical address embedded c variable address is stored in stack, in embedded c variable should be declaired at the begining of the block embedded c input output port are used but in c printf and scanf used

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

How to debug apk signed for release?

I tried with the following and it's worked:

release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

Adding values to Arraylist

First simple rule: never use the String(String) constructor, it is absolutely useless (*).

So arr.add("ss") is just fine.

With 3 it's slightly different: 3 is an int literal, which is not an object. Only objects can be put into a List. So the int will need to be converted into an Integer object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3) which can (and will) avoid creating a new Integer instance in some cases.

So actually writing arr.add(3) is usually a better idea than using arr.add(new Integer(3)), because it can avoid creating a new Integer object and instead reuse and existing one.

Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.

(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

Are complex expressions possible in ng-hide / ng-show?

This will work if you do not have too many expressions.

Example: ng-show="form.type === 'Limited Company' || form.type === 'Limited Partnership'"

For any more expressions than this use a controller.

Why is Android Studio reporting "URI is not registered"?

For me Plugin Android Support get Disabled somehow. Enabling Plugins again worked for me.

Settings > Plugins > Android Support

How do I add my new User Control to the Toolbox or a new Winform?

Assuming I understand what you mean:

  1. If your UserControl is in a library you can add this to you Toolbox using

    Toolbox -> right click -> Choose Items -> Browse

    Select your assembly with the UserControl.

  2. If the UserControl is part of your project you only need to build the entire solution. After that, your UserControl should appear in the toolbox.

In general, it is not possible to add a Control from Solution Explorer, only from the Toolbox.

Enter image description here

Run php script as daemon process

As others have already mentioned, running PHP as a daemon is quite easy, and can be done using a single line of command. But the actual problem is keeping it running and managing it. I've had the same problem quite some time ago and although there are plenty of solutions already available, most of them have lots of dependencies or are difficult to use and not suitable for basic usages. I wrote a shell script that can manage a any process/application including PHP cli scripts. It can be set as a cronjob to start the application and will contain the application and manage it. If it's executed again, for example via the same cronjob, it check if the app is running or not, if it does then simply exits and let its previous instance continue managing the application.

I uploaded it to github, feel free to use it : https://github.com/sinasalek/EasyDeamonizer

EasyDeamonizer

Simply watches over your application (start, restart, log, monitor, etc). a generic script to make sure that your appliation remains running properly. Intentionally it uses process name instread of pid/lock file to prevent all its side effects and keep the script as simple and as stirghforward as possible, so it always works even when EasyDaemonizer itself is restarted. Features

  • Starts the application and optionally a customized delay for each start
  • Makes sure that only one instance is running
  • Monitors CPU usage and restarts the app automatically when it reaches the defined threshold
  • Setting EasyDeamonizer to run via cron to run it again if it's halted for any reason
  • Logs its activity

How to put scroll bar only for modal-body?

#scroll-wrap {
    max-height: 50vh;
    overflow-y: auto;
}

Using max-height with vh as the unit on the modal-body or a wrapper div inside of the modal-body. This will resize the height of modal-body or the wrapping div(in this example) automatically when a user resize the window.

vh is length unit representing 1% of the viewport size for viewport height.

Browser compatibility chart for vh unit.

Example: https://jsfiddle.net/q3xwr53f/

How do I include a file over 2 directories back?

You can do ../../directory/file.txt - This goes two directories back.

../../../ - this goes three. etc

Download data url file

There are several solutions but they depend on HTML5 and haven't been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).

  1. Canvas example with save to file support. Just set your document.location.href to the data URI.
  2. Anchor download example. It uses <a href="your-data-uri" download="filename.txt"> to specify file name.

How do I import a .bak file into Microsoft SQL Server 2012?

You can use the following script if you don't wish to use Wizard;

RESTORE DATABASE myDB
FROM  DISK = N'C:\BackupDB.bak' 
WITH  REPLACE,RECOVERY,  
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',  
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'

Is it better to use "is" or "==" for number comparison in Python?

>>> 2 == 2.0
True
>>> 2 is 2.0
False

Use ==

How do I call a dynamically-named method in Javascript?

I would recommend NOT to use global / window / eval for this purpose.
Instead, do it this way:

define all methods as properties of Handler:

var Handler={};

Handler.application_run = function (name) {
console.log(name)
}

Now call it like this

var somefunc = "application_run";
Handler[somefunc]('jerry');

Output: jerry


Case when importing functions from different files

import { func1, func2 } from "../utility";

const Handler= {
  func1,
  func2
};

Handler["func1"]("sic mundus");
Handler["func2"]("creatus est");

Why does "pip install" inside Python raise a SyntaxError?

pip is run from the command line, not the Python interpreter. It is a program that installs modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do import selenium.

The Python shell is not a command line, it is an interactive interpreter. You type Python code into it, not commands.

Filter values only if not null using lambda in Java8

You can do this in single filter step:

requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));

If you don't want to call getName() several times (for example, it's expensive call), you can do this:

requiredCars = cars.stream().filter(c -> {
    String name = c.getName();
    return name != null && name.startsWith("M");
});

Or in more sophisticated way:

requiredCars = cars.stream().filter(c -> 
    Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());

How can I get a web site's favicon?

http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.

How to normalize a signal to zero mean and unit variance?

To avoid division by zero!

function x = normalize(x, eps)
    % Normalize vector `x` (zero mean, unit variance)

    % default values
    if (~exist('eps', 'var'))
        eps = 1e-6;
    end

    mu = mean(x(:));

    sigma = std(x(:));
    if sigma < eps
        sigma = 1;
    end

    x = (x - mu) / sigma;
end

GetFiles with multiple extensions

You can get every file, then filter the array:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dirInfo, params string[] extensions)
{
    var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);

    return dirInfo.EnumerateFiles()
                  .Where(f => allowedExtensions.Contains(f.Extension));
}

This will be (marginally) faster than every other answer here.
In .Net 3.5, replace EnumerateFiles with GetFiles (which is slower).

And use it like this:

var files = new DirectoryInfo(...).GetFilesByExtensions(".jpg", ".mov", ".gif", ".mp4");

How to insert current_timestamp into Postgres via python

Sure, just pass a string value for that timestamp column in the format: '2011-05-16 15:36:38' (you can also append a timezone there, like 'PST'). PostgreSQL will automatically convert the string to a timestamp. See http://www.postgresql.org/docs/9.0/static/datatype-datetime.html#DATATYPE-DATETIME-INPUT

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

How to auto generate migrations with Sequelize CLI from Sequelize models?

If you want to create model along with migration use this command:-

sequelize model:create --name regions --attributes name:string,status:boolean --underscored

--underscored it is used to create column having underscore like:- created_at,updated_at or any other column having underscore and support user defined columns having underscore.

How to update a single pod without touching other dependencies

Just a small notice.

pod update POD_NAME

will work only if this pod was already installed. Otherwise you will have to update all of them with

pod update

command

Android emulator: could not get wglGetExtensionsStringARB error

I faced the similar problem. In my case I had created the new virtual device and had enabled the snapshot. I just unchecked the checkbox Go to AVD Manager -> Select the device -> click Edit and uncheck the Enabled checkbox. I hope this works.

How to resize datagridview control when form resizes

In your form constructor you could create an event handler like this:

this.SizeChanged(frm_sizeChanged);

Then create an event handler that resizes the grid appropriately, example:

private void frm_sizeChanged(object sender, EventArgs e)
{
     dataGrid.Size = new Size(100, 200);
}

Replacing those numbers with whatever you'd like.

What is the Maximum Size that an Array can hold?

System.Int32.MaxValue

Assuming you mean System.Array, ie. any normally defined array (int[], etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.

This limit is enforced because System.Array uses an Int32 as it's indexer, hence only valid values for an Int32 can be used. On top of this, only positive values (ie, >= 0) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32, which is available in Int32.MaxValue and is equivalent to 2^31, or roughly 2 billion.

On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T> instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T> or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.

The other collection of note is Dictionary<int, T> which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);

Using Dictionary also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>, which will provide more potential elements than you could possible think about.

Python strftime - date without leading 0?

import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")

How to get year/month/day from a date object?

EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.

function getFormattedDate(today) 
{
    var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    var day  = week[today.getDay()];
    var dd   = today.getDate();
    var mm   = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    var hour = today.getHours();
    var minu = today.getMinutes();

    if(dd<10)  { dd='0'+dd } 
    if(mm<10)  { mm='0'+mm } 
    if(minu<10){ minu='0'+minu } 

    return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}

var date = new Date();
var text = getFormattedDate(date);


*For Spanish format, just translate the WEEK variable.

var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');


Output: Monday - 16/11/2015 14:24

How to detect the physical connected state of a network cable/connector?

cat /sys/class/net/ethX is by far the easiest method.

The interface has to be up though, else you will get an invalid argument error.

So first:

ifconfig ethX up

Then:

cat /sys/class/net/ethX

How can I exclude multiple folders using Get-ChildItem -exclude?

You could also do this in a single statement:

$j = "Somepath"
$files = Get-ChildItem -Path $j -Include '*.xlsx','*.zip' -Recurse -ErrorAction SilentlyContinue –File | ? {$_.Directory -notlike "$j\donotwantfoldername"}

Set NA to 0 in R

Why not try this

  na.zero <- function (x) {
        x[is.na(x)] <- 0
        return(x)
    }
    na.zero(df)

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

How to get distinct values for non-key column fields in Laravel?

Grouping by will not work if the database rules don't allow any of the select fields to be outside of an aggregate function. Instead use the laravel collections.

$users = DB::table('users')
        ->select('id','name', 'email')
        ->get();

foreach($users->unique('name') as $user){
  //....
}

Someone pointed out that this may not be great on performance for large collections. I would recommend adding a key to the collection. The method to use is called keyBy. This is the simple method.

     $users = DB::table('users')
        ->select('id','name', 'email')
        ->get()
        ->keyBy('name');

The keyBy also allows you to add a call back function for more complex things...

     $users = DB::table('users')
        ->select('id','name', 'email')
        ->get()
        ->keyBy(function($user){
              return $user->name . '-' . $user->id;
         });

If you have to iterate over large collections, adding a key to it solve the performance issue.

How to get date representing the first day of a month?

... in Powershell you can do something like this:

Get-Date (get-Date ((Get-Date) ) -format MM.yyyy)

... for the last month do this:

Get-Date (get-Date ((Get-Date).AddMonths(-1) ) -format MM.yyyy)

... or for custom Date do this:

Get-Date (get-Date ((Get-Date 12.01.2013) ) -format MM.yyyy)

Im sure theres something like this possible ...

Gruß

How to start up spring-boot application via command line?

1.Run Spring Boot app with java -jar command

To run your Spring Boot app from a command line in a Terminal window you can use java -jar command. This is provided your Spring Boot app was packaged as an executable jar file.

java -jar target/app-0.0.1-SNAPSHOT.jar

2.Run Spring Boot app using Maven

You can also use Maven plugin to run your Spring Boot app. Use the below command to run your Spring Boot app with Maven plugin:

mvn spring-boot:run

3.Run Spring Boot App with Gradle

And if you use Gradle you can run the Spring Boot app with the following command:

gradle bootRun

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

Python send UDP packet

Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more

full code:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

Creating a dictionary from a CSV file

This isn't elegant but a one line solution using pandas.

import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()

If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):

import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()

Tracking the script execution time in PHP

You may only want to know the execution time of parts of your script. The most flexible way to time parts or an entire script is to create 3 simple functions (procedural code given here but you could turn it into a class by putting class timer{} around it and making a couple of tweaks). This code works, just copy and paste and run:

$tstart = 0;
$tend = 0;

function timer_starts()
{
global $tstart;

$tstart=microtime(true); ;

}

function timer_ends()
{
global $tend;

$tend=microtime(true); ;

}

function timer_calc()
{
global $tstart,$tend;

return (round($tend - $tstart,2));
}

timer_starts();
file_get_contents('http://google.com');
timer_ends();
print('It took '.timer_calc().' seconds to retrieve the google page');

Is the size of C "int" 2 bytes or 4 bytes?

This is one of the points in C that can be confusing at first, but the C standard only specifies a minimum range for integer types that is guaranteed to be supported. int is guaranteed to be able to hold -32767 to 32767, which requires 16 bits. In that case, int, is 2 bytes. However, implementations are free to go beyond that minimum, as you will see that many modern compilers make int 32-bit (which also means 4 bytes pretty ubiquitously).

The reason your book says 2 bytes is most probably because it's old. At one time, this was the norm. In general, you should always use the sizeof operator if you need to find out how many bytes it is on the platform you're using.

To address this, C99 added new types where you can explicitly ask for a certain sized integer, for example int16_t or int32_t. Prior to that, there was no universal way to get an integer of a specific width (although most platforms provided similar types on a per-platform basis).

Get the current URL with JavaScript?

Adding result for quick reference

window.location;

 Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
 ancestorOrigins: DOMStringList,
 origin: "https://stackoverflow.com",
 replace: ƒ, assign: ƒ, …}

document.location

  Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript", 
ancestorOrigins: DOMStringList,
 origin: "https://stackoverflow.com",
 replace: ƒ, assign: ƒ
, …}

window.location.pathname

"/questions/1034621/get-the-current-url-with-javascript"

window.location.href

"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"

location.hostname

"stackoverflow.com"

How to apply two CSS classes to a single element

This is very clear that to add two classes in single div, first you have to generate the classes and then combine them. This process is used to make changes and reduce the no. of classes. Those who make the website from scratch mostly used this type of methods. they make two classes first class is for color and second class is for setting width, height, font-style, etc. When we combine both the classes then the first class and second class both are in effect.

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

Unable to connect PostgreSQL to remote database using pgAdmin

Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

  1. Open PuTTY. If you already have a session set up to connect to the EC2 instance, load that, but don't connect to it just yet. If you don't have such a session, see this post.
  2. Go to Connection > SSH > Tunnels
  3. Enter 5433 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the "Add" button.
  6. Go back to Session, and save your session, then click "Open" to connect.
  7. This opens a terminal window. Once you're connected, you can leave that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 5433 in the Port field. Specify a Name for the connection, and the username and password. Click OK when you're done.

How to add column to numpy array

The easiest solution is to use numpy.insert().

The Advantage of np.insert() over np.append is that you can insert the new columns into custom indices.

import numpy as np

X = np.arange(20).reshape(10,2)

X = np.insert(X, [0,2], np.random.rand(X.shape[0]*2).reshape(-1,2)*10, axis=1)
'''

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

append to url and refresh page

Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:

location.href = location.href + "&parameter=" + value;

This will work quite well for the majority of the cases.

However

That's not the correct way to append a parameter to a URL in my opinion.

Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:

https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1

at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?

This is my suggested approach:

function URL_add_parameter(url, param, value){
    var hash       = {};
    var parser     = document.createElement('a');

    parser.href    = url;

    var parameters = parser.search.split(/\?|&/);

    for(var i=0; i < parameters.length; i++) {
        if(!parameters[i])
            continue;

        var ary      = parameters[i].split('=');
        hash[ary[0]] = ary[1];
    }

    hash[param] = value;

    var list = [];  
    Object.keys(hash).forEach(function (key) {
        list.push(key + '=' + hash[key]);
    });

    parser.search = '?' + list.join('&');
    return parser.href;
}

With this function one just will have to do the following:

location.href = URL_add_parameter(location.href, 'param', 'value');

Best way to randomize an array with .NET

This is a complete working Console solution based on the example provided in here:

class Program
{
    static string[] words1 = new string[] { "brown", "jumped", "the", "fox", "quick" };

    static void Main()
    {
        var result = Shuffle(words1);
        foreach (var i in result)
        {
            Console.Write(i + " ");
        }
        Console.ReadKey();
    }

   static string[] Shuffle(string[] wordArray) {
        Random random = new Random();
        for (int i = wordArray.Length - 1; i > 0; i--)
        {
            int swapIndex = random.Next(i + 1);
            string temp = wordArray[i];
            wordArray[i] = wordArray[swapIndex];
            wordArray[swapIndex] = temp;
        }
        return wordArray;
    }         
}

Confused by python file mode "w+"

Here is a list of the different modes of opening a file:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • ab

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

How can I use Bash syntax in Makefile targets?

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I can't see that you're adding these controls to the control hierarchy. Try:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

Events won't be invoked unless the control is part of the control hierarchy.

How to list all users in a Linux group?

Here's another Python one-liner that takes into account the user's default group membership (from /etc/passwd)as well as from the group database (/etc/group)

python -c "import grp,pwd; print set(grp.getgrnam('mysupercoolgroup')[3]).union([u[0] for u in pwd.getpwall() if u.pw_gid == grp.getgrnam('mysupercoolgroup')[2]])"

How to easily get network path to the file you are working on?

Here's how to get the filepath of the file in Excel 2010.

1) Right click on the Ribbon.
2) Click on "Customize the Ribbon"
3) On the right hand side, click "New Group." This will add a new tab to the Ribbon. If you want to, click on the "Rename" button the right side and name your tab. For example, I named the tab "Doc Path." This step is optional
4) Under "Choose Commands From" on the left hand side, choose "Commands Not in the Ribbon."
5) Select "Document Location" and "Add" it to your newly created group.
6) The filepath should now appear under the newly created tab on the ribbon.

How can I adjust DIV width to contents

One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

Which to use <div class="name"> or <div id="name">?

ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...

Running a script inside a docker container using shell script

In case you don't want (or have) a running container, you can call your script directly with the run command.

Remove the iterative tty -i -t arguments and use this:

    $ docker run ubuntu:bionic /bin/bash /path/to/script.sh

This will (didn't test) also work for other scripts:

    $ docker run ubuntu:bionic /usr/bin/python /path/to/script.py

use video as background for div

Why not fix a <video> and use z-index:-1 to put it behind all other elements?

html, body { width:100%; height:100%; margin:0; padding:0; }

<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
    <video id="video" style="width:100%; height:100%">
        ....
    </video>
</div>
<div class='content'>
    ....

Demo

If you want it within a container you have to add a container element and a little more CSS

/* HTML */
<div class='vidContain'>
    <div class='vid'>
        <video> ... </video>
    </div>
    <div class='content'> ... The rest of your content ... </div>
</div>

/* CSS */
.vidContain {
    width:300px; height:200px;
    position:relative;
    display:inline-block;
    margin:10px;
}
.vid {
    position: absolute; 
    top: 0; left:0;
    width: 100%; height: 100%; 
    z-index: -1;
}    
.content {
    position:absolute;
    top:0; left:0;
    background: black;
    color:white;
}

Demo

Get login username in java

in Unix:

new com.sun.security.auth.module.UnixSystem().getUsername()

in Windows:

new com.sun.security.auth.module.NTSystem().getName()

in Solaris:

new com.sun.security.auth.module.SolarisSystem().getUsername()

Windows-1252 to UTF-8 encoding

There's no general way to tell if a file is encoded with a specific encoding. Remember that an encoding is nothing more but an "agreement" how the bits in a file should be mapped to characters.

If you don't know which of your files are actually already encoded in UTF-8 and which ones are encoded in windows-1252, you will have to inspect all files and find out yourself. In the worst case that could mean that you have to open every single one of them with either of the two encodings and see whether they "look" correct -- i.e., all characters are displayed correctly. Of course, you may use tool support in order to do that, for instance, if you know for sure that certain characters are contained in the files that have a different mapping in windows-1252 vs. UTF-8, you could grep for them after running the files through 'iconv' as mentioned by Seva Akekseyev.

Another lucky case for you would be, if you know that the files actually contain only characters that are encoded identically in both UTF-8 and windows-1252. In that case, of course, you're done already.

How can I export tables to Excel from a webpage

This code is IE only so it is only useful in situations where you know all of your users will be using IE (like, for example, in some corporate environments.)

<script Language="javascript">
function ExportHTMLTableToExcel()
{
   var thisTable = document.getElementById("tbl").innerHTML;
   window.clipboardData.setData("Text", thisTable);
   var objExcel = new ActiveXObject ("Excel.Application");
   objExcel.visible = true;

   var objWorkbook = objExcel.Workbooks.Add;
   var objWorksheet = objWorkbook.Worksheets(1);
   objWorksheet.Paste;
}
</script>

asp.net: How can I remove an item from a dropdownlist?

Code:

ListItem removeItem= myDropDown.Items.FindByValue("TextToFind");
drpCategory.Items.Remove(removeItem);

Replace "TextToFind" with the item you want to remove.

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

Nothing wrong with the other answers, but I use the following technique when passing functions in a directive attribute.

Leave off the parenthesis when including the directive in your html:

<my-directive callback="someFunction" />

Then "unwrap" the function in your directive's link or controller. here is an example:

app.directive("myDirective", function() {

    return {
        restrict: "E",
        scope: {
            callback: "&"                              
        },
        template: "<div ng-click='callback(data)'></div>", // call function this way...
        link: function(scope, element, attrs) {
            // unwrap the function
            scope.callback = scope.callback(); 

            scope.data = "data from somewhere";

            element.bind("click",function() {
                scope.$apply(function() {
                    callback(data);                        // ...or this way
                });
            });
        }
    }
}]);    

The "unwrapping" step allows the function to be called using a more natural syntax. It also ensures that the directive works properly even when nested within other directives that may pass the function. If you did not do the unwrapping, then if you have a scenario like this:

<outer-directive callback="someFunction" >
    <middle-directive callback="callback" >
        <inner-directive callback="callback" />
    </middle-directive>
</outer-directive>

Then you would end up with something like this in your inner-directive:

callback()()()(data); 

Which would fail in other nesting scenarios.

I adapted this technique from an excellent article by Dan Wahlin at http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters

I added the unwrapping step to make calling the function more natural and to solve for the nesting issue which I had encountered in a project.

How do I link a JavaScript file to a HTML file?

You can add script tags in your HTML document, ideally inside the which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="relative/path/to/your/javascript.js"></script>

Then in your javascript file you can refer to jQuery either using $ sign or jQuery. Example:

jQuery.each(arr, function(i) { console.log(i); }); 

Why are unnamed namespaces used and what are their benefits?

In addition to the other answers to this question, using an anonymous namespace can also improve performance. As symbols within the namespace do not need any external linkage, the compiler is freer to perform aggressive optimization of the code within the namespace. For example, a function which is called multiple times once in a loop can be inlined without any impact on the code size.

For example, on my system the following code takes around 70% of the run time if the anonymous namespace is used (x86-64 gcc-4.6.3 and -O2; note that the extra code in add_val makes the compiler not want to include it twice).

#include <iostream>

namespace {
  double a;
  void b(double x)
  {
    a -= x;
  }
  void add_val(double x)
  {
    a += x;
    if(x==0.01) b(0);
    if(x==0.02) b(0.6);
    if(x==0.03) b(-0.1);
    if(x==0.04) b(0.4);
  }
}

int main()
{
  a = 0;
  for(int i=0; i<1000000000; ++i)
    {
      add_val(i*1e-10);
    }
  std::cout << a << '\n';
  return 0;
}

Pointers in C: when to use the ampersand and the asterisk?

You have pointers and values:

int* p; // variable p is pointer to integer type
int i; // integer value

You turn a pointer into a value with *:

int i2 = *p; // integer i2 is assigned with integer value that pointer p is pointing to

You turn a value into a pointer with &:

int* p2 = &i; // pointer p2 will point to the address of integer i

Edit: In the case of arrays, they are treated very much like pointers. If you think of them as pointers, you'll be using * to get at the values inside of them as explained above, but there is also another, more common way using the [] operator:

int a[2];  // array of integers
int i = *a; // the value of the first element of a
int i2 = a[0]; // another way to get the first element

To get the second element:

int a[2]; // array
int i = *(a + 1); // the value of the second element
int i2 = a[1]; // the value of the second element

So the [] indexing operator is a special form of the * operator, and it works like this:

a[i] == *(a + i);  // these two statements are the same thing

How to create a MySQL hierarchical recursive query?

The best approach I've come up with is

  1. Use lineage to store\sort\trace trees. That's more than enough, and works thousands times faster for reading than any other approach. It also allows to stay on that pattern even if DB will change(as ANY db will allow that pattern to be used)
  2. Use function that determines lineage for specific ID.
  3. Use it as you wish (in selects, or on CUD operations, or even by jobs).

Lineage approach descr. can be found wherever, for example Here or here. As of function - that is what enspired me.

In the end - got more-or-less simple, relatively fast, and SIMPLE solution.

Function's body

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `get_lineage`(the_id INT) RETURNS text CHARSET utf8
    READS SQL DATA
BEGIN

 DECLARE v_rec INT DEFAULT 0;

 DECLARE done INT DEFAULT FALSE;
 DECLARE v_res text DEFAULT '';
 DECLARE v_papa int;
 DECLARE v_papa_papa int DEFAULT -1;
 DECLARE csr CURSOR FOR 
  select _id,parent_id -- @n:=@n+1 as rownum,T1.* 
  from 
    (SELECT @r AS _id,
        (SELECT @r := table_parent_id FROM table WHERE table_id = _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := the_id, @l := 0,@n:=0) vars,
        table m
    WHERE @r <> 0
    ) T1
    where T1.parent_id is not null
 ORDER BY T1.lvl DESC;
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    open csr;
    read_loop: LOOP
    fetch csr into v_papa,v_papa_papa;
        SET v_rec = v_rec+1;
        IF done THEN
            LEAVE read_loop;
        END IF;
        -- add first
        IF v_rec = 1 THEN
            SET v_res = v_papa_papa;
        END IF;
        SET v_res = CONCAT(v_res,'-',v_papa);
    END LOOP;
    close csr;
    return v_res;
END

And then you just

select get_lineage(the_id)

Hope it helps somebody :)

How to change the height of a div dynamically based on another div using css?

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Here is the Pakka codes for making the height of a division equal to another dynamically - M C Jain, Chartered Accountant -->

<script language="javascript">
function make_equal_heights()
{


if ((document.getElementById('div_A').offsetHeight) > (document.getElementById('div_B').offsetHeight) ) 
{ 
document.getElementById('div_B').style.height = (document.getElementById('div_A').offsetHeight) + "px";
} 
else 
{ 
document.getElementById('div_A').style.height = (document.getElementById('div_B').offsetHeight) + "px"
}


}
</script>

</head>

<body style="margin:50px;"  onload="make_equal_heights()"> 

<div  id="div_A"  style="height:200px; width:150px; margin-top:22px;
                        background-color:lightblue;float:left;">DIVISION A</div><br>

<div  id="div_B"  style="height:150px; width:150px; margin-left:12px;
                        background-color: blue; float:left; ">DIVISION B</div>

</body>
</html>

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

In my case I was trying to run on an watchOS 7 simulator in Relese mode but the iOS 14 simulator was in Debug mode.

So simply putting both sims in Debug/Release mode solved the problem for me!

swift How to remove optional String Character

You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:

if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
    println(color) // "Red"

    let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
    println(imageURLString) // http://hahaha.com/ha.php?color=Red
}

How to check if object has any properties in JavaScript?

If you are willing to use lodash, you can use the some method.

_.some(obj) // returns true or false

See this small jsbin example

GCD to perform task in main thread

As the other answers mentioned, dispatch_async from the main thread is fine.

However, depending on your use case, there is a side effect that you may consider a disadvantage: since the block is scheduled on a queue, it won't execute until control goes back to the run loop, which will have the effect of delaying your block's execution.

For example,

NSLog(@"before dispatch async");
dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"inside dispatch async block main thread from main thread");
});
NSLog(@"after dispatch async");

Will print out:

before dispatch async
after dispatch async
inside dispatch async block main thread from main thread

For this reason, if you were expecting the block to execute in-between the outer NSLog's, dispatch_async would not help you.

Checking if a key exists in a JS object

Above answers are good. But this is good too and useful.

!obj['your_key']  // if 'your_key' not in obj the result --> true

It's good for short style of code special in if statements:

if (!obj['your_key']){
    // if 'your_key' not exist in obj
    console.log('key not in obj');
} else {
    // if 'your_key' exist in obj
    console.log('key exist in obj');
}

Note: If your key be equal to null or "" your "if" statement will be wrong.

obj = {'a': '', 'b': null, 'd': 'value'}
!obj['a']    // result ---> true
!obj['b']    // result ---> true
!obj['c']    // result ---> true
!obj['d']    // result ---> false

So, best way for checking if a key exists in a obj is:'a' in obj

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

Just today I had the (questionable) pleasure to get VB6 code running on Windows / 64 Bit. I did come across this thread, but none of the proposed solutions worked for me. Neither worked adding references using the "Project -> References..." menu.

To get it running, I had to manually modify the VB6 project file (*.vbp). For all the libraries I had load issue with I had to use the following notation to define as reference: Object={Registry Key}#Version#0; LIBRARY.OCX Example: Object={FAEEE763-117E-101B-8933-08002B2F4F5A}#1.1#0; DBLIST32.OCX

I had not to register any of the libraries (using regsvr32), these were all already correctly registered. I guess why my solution works is that if the "object={[...]" notation is used (instead of the "Reference=*\G{[...]" notation) VB Studio is using the Registry Key only and gets rooted to C:\Windows\SysWOW64 while as the other way ends up looking in C:\Windows\System32

By the way, IE11 is installed. Whether or not this matters, only Bill G might know. My guess is that my solution works regardless which IE is installed. You just might have to unregister and register the missing libraries as mentioned in this thread.

Hope that helps anyone who faces similar issues.

How do I redirect to another webpage?

Should just be able to set using window.location.

Example:

window.location = "https://stackoverflow.com/";

Here is a past post on the subject: How do I redirect to another webpage?

Angular 5 Scroll to top on every Route click

Now there's a built in solution available in Angular 6.1 with scrollPositionRestoration option.

See my answer on Angular 2 Scroll to top on Route Change.

DIV table colspan: how?

<div style="clear:both;"></div> - may do the trick in some cases; not a "colspan" but may help achieve what you are looking for...

<div id="table">
    <div class="table_row">
        <div class="table_cell1"></div>
        <div class="table_cell2"></div>
        <div class="table_cell3"></div>
    </div>
    <div class="table_row">
        <div class="table_cell1"></div>
        <div class="table_cell2"></div>
        <div class="table_cell3"></div>
    </div>

<!-- clear:both will clear any float direction to default, and
prevent the previously defined floats from affecting other elements -->
    <div style="clear:both;"></div>

    <div class="table_row">
<!-- the float is cleared, you could have 4 divs (columns) or
just one with 100% width -->
        <div class="table_cell123"></div>
    </div>
</div>

Reading a date using DataReader

I know that this is an old question, but I'm surprised that no answer mentions GetDateTime:

Gets the value of the specified column as a DateTime object.

Which you can use like:

while (MyReader.Read())
{
    TextBox1.Text = MyReader.GetDateTime(columnPosition).ToString("dd/MM/yyyy");
}

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Why is there no xrange function in Python3?

xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.

how to set the default value to the drop down list control?

lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);

And in your cancel method:

lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");

And in your update method:

lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;

What is <scope> under <dependency> in pom.xml for?

.pom dependency scope can contain:

  • compile - available at Compile-time and Run-time
  • provided - available at Compile-time. (this dependency should be provided by outer container like OS...)
  • runtime - available at Run-time
  • test - test compilation and run time
  • system - is similar to provided but exposes <systemPath>path/some.jar</systemPath> to point on .jar
  • import - is available from Maven v2.0.9 for <type>pom</type> and it should be replaced by effective dependency from this file <dependencyManagement/>

What is the difference between procedural programming and functional programming?

I've never seen this definition given elsewhere, but I think this sums up the differences given here fairly well:

Functional programming focuses on expressions

Procedural programming focuses on statements

Expressions have values. A functional program is an expression who's value is a sequence of instructions for the computer to carry out.

Statements don't have values and instead modify the state of some conceptual machine.

In a purely functional language there would be no statements, in the sense that there's no way to manipulate state (they might still have a syntactic construct named "statement", but unless it manipulates state I wouldn't call it a statement in this sense). In a purely procedural language there would be no expressions, everything would be an instruction which manipulates the state of the machine.

Haskell would be an example of a purely functional language because there is no way to manipulate state. Machine code would be an example of a purely procedural language because everything in a program is a statement which manipulates the state of the registers and memory of the machine.

The confusing part is that the vast majority of programming languages contain both expressions and statements, allowing you to mix paradigms. Languages can be classified as more functional or more procedural based on how much they encourage the use of statements vs expressions.

For example, C would be more functional than COBOL because a function call is an expression, whereas calling a sub program in COBOL is a statement (that manipulates the state of shared variables and doesn't return a value). Python would be more functional than C because it allows you to express conditional logic as an expression using short circuit evaluation (test && path1 || path2 as opposed to if statements). Scheme would be more functional than Python because everything in scheme is an expression.

You can still write in a functional style in a language which encourages the procedural paradigm and vice versa. It's just harder and/or more awkward to write in a paradigm which isn't encouraged by the language.

how to delete installed library form react native project

I followed the following steps:--

  1. react-native unlink <lib name> -- this command has done the unlinking of the library from both platforms.

  2. react-native uninstall <lib name> -- this has uninstalled the library from the node modules and its dependencies

  3. Manually removed the library name from package.json -- somehow the --save command was not working for me to remove the library declaration from package.json.

After this I have manually deleted the empty react-native library from the node_modules folder

Why use 'virtual' for class properties in Entity Framework model definitions?

It’s quite common to define navigational properties in a model to be virtual. When a navigation property is defined as virtual, it can take advantage of certain Entity Framework functionality. The most common one is lazy loading.

Lazy loading is a nice feature of many ORMs because it allows you to dynamically access related data from a model. It will not unnecessarily fetch the related data until it is actually accessed, thus reducing the up-front querying of data from the database.

From book "ASP.NET MVC 5 with Bootstrap and Knockout.js"

Calculate days between two Dates in Java 8

Get number of days before Christmas from current day , try this

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));

Passing multiple variables to another page in url

Use & for this. Using & you can put as many variables as you want!

$url = "http://localhost/main.php?event_id=".$event_id."&email=".$email;

How do I compile with -Xlint:unchecked?

For IntelliJ 13.1, go to File -> Settings -> Project Settings -> Compiler -> Java Compiler, and on the right-hand side, for Additional command line parameters enter "-Xlint:unchecked".

How to install Visual C++ Build tools?

I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.

I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.

It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"

scale Image in an UIButton to AspectFit?

Background image can actually be set to scale aspect fill pretty easily. Just need to do something like this in a subclass of UIButton:

- (CGRect)backgroundRectForBounds:(CGRect)bounds
{
    // you'll need the original size of the image, you 
    // can save it from setBackgroundImage:forControlState
    return CGRectFitToFillRect(__original_image_frame_size__, bounds);
}

// Utility function, can be saved elsewhere
CGRect CGRectFitToFillRect( CGRect inRect, CGRect maxRect )
{
    CGFloat origRes = inRect.size.width / inRect.size.height;
    CGFloat newRes = maxRect.size.width / maxRect.size.height;

    CGRect retRect = maxRect;

    if (newRes < origRes)
    {
        retRect.size.width = inRect.size.width * maxRect.size.height / inRect.size.height;
        retRect.origin.x = roundf((maxRect.size.width - retRect.size.width) / 2);
    }
    else
    {
        retRect.size.height = inRect.size.height * maxRect.size.width / inRect.size.width;
        retRect.origin.y = roundf((maxRect.size.height - retRect.size.height) / 2);
    }

    return retRect;
}

JUnit Eclipse Plugin?

You might want to try out Quick JUnit: https://marketplace.eclipse.org/content/quick-junit

The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:

Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)

Why would an Enum implement an Interface?

Enums are like Java Classes, they can have Constructors, Methods, etc. The only thing that you can't do with them is new EnumName(). The instances are predefined in your enum declaration.

How to determine a user's IP address in node

You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.

Disclosure: I created this module

Install:

npm install request-ip

In your app:

var requestIp = require('request-ip');

// inside middleware handler
var ipMiddleware = function(req, res, next) {
    var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
    next();
};

Hope this helps

How can I set a UITableView to grouped style

Swift 4+:

let myTableViewController = UITableViewController(style: .grouped)

AngularJS event on window innerWidth size change

We could do it with jQuery:

$(window).resize(function(){
    alert(window.innerWidth);

    $scope.$apply(function(){
       //do something to update current scope based on the new innerWidth and let angular update the view.
    });
});

Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when the scope is destroyed. If you don't do this, everytime when the scope is recreated (the controller is rerun), there will be 1 more handler added causing unexpected behavior and leaking.

In this case, you may need to identify your attached handler:

  $(window).on("resize.doResize", function (){
      alert(window.innerWidth);

      $scope.$apply(function(){
          //do something to update current scope based on the new innerWidth and let angular update the view.
      });
  });

  $scope.$on("$destroy",function (){
      $(window).off("resize.doResize"); //remove the handler added earlier
  });

In this example, I'm using event namespace from jQuery. You could do it differently according to your requirements.

Improvement: If your event handler takes a bit long time to process, to avoid the problem that the user may keep resizing the window, causing the event handlers to be run many times, we could consider throttling the function. If you use underscore, you can try:

$(window).on("resize.doResize", _.throttle(function (){
    alert(window.innerWidth);

    $scope.$apply(function(){
        //do something to update current scope based on the new innerWidth and let angular update the view.
    });
},100));

or debouncing the function:

$(window).on("resize.doResize", _.debounce(function (){
     alert(window.innerWidth);

     $scope.$apply(function(){
         //do something to update current scope based on the new innerWidth and let angular update the view.
     });
},100));

Difference Between throttling and debouncing a function

Could not connect to React Native development server on Android

In my case, running on a Macbook, i had to turn off my firewall, thus allowing incoming connections from my android. RN v0.61.5

presentViewController and displaying navigation bar

I use this code. It's working fine in iOS 8.

MyProfileEditViewController *myprofileEdit=[self.storyboard instantiateViewControllerWithIdentifier:@"myprofileeditSid"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:myprofileEdit];
[self presentViewController:navigationController animated:YES completion:^{}];

C/C++ line number

C++20 offers a new way to achieve this by using std::source_location. This is currently accessible in gcc an clang as std::experimental::source_location with #include <experimental/source_location>.

The problem with macros like __LINE__ is that if you want to create for example a logging function that outputs the current line number along with a message, you always have to pass __LINE__ as a function argument, because it is expanded at the call site. Something like this:

void log(const std::string msg) {
    std::cout << __LINE__ << " " << msg << std::endl;
}

Will always output the line of the function declaration and not the line where log was actually called from. On the other hand, with std::source_location you can write something like this:

#include <experimental/source_location>
using std::experimental::source_location;

void log(const std::string msg, const source_location loc = source_location::current())
{
    std::cout << loc.line() << " " << msg << std::endl;
}

Here, loc is initialized with the line number pointing to the location where log was called. You can try it online here.

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

My guess is that you are trying to restore in lower versions which wont work

How do I overload the square-bracket operator in C#?

Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded, 
                                    but only as pairs.

&&, ||                  They can't be overloaded

() (Conversion operator)        They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be 
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!

Source of the information

For bracket:

public Object this[int index]
{

}

BUT

The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).

From MSDN

How to remove decimal values from a value of type 'double' in Java

You could use

String newValue = Integer.toString((int)percentageValue);

Or

String newValue = Double.toString(Math.floor(percentageValue));

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Cassandra cqlsh - connection refused

try changing the native_transport_protocol to port 9160 (if it is set to anything other than 9160; it might be pointing to 9042). Check your logs and see on which port cassandra is listening for CQL clients?

Difference between null and empty ("") Java String

When you write

String a = "";

It means there is a variable 'a' of type string which points to a object reference in string pool which has a value "". As variable a is holding a valid string object reference, all the methods of string can be applied here.

Whereas when you write

String b = null;

It means that there is a variable b of type string which points to an unknown reference. And any operation on unknown reference will result in an NullPointerException.

Now, let us evaluate the below expressions.

System.out.println(a == b); // false. because a and b both points to different object reference

System.out.println(a.equals(b)); // false, because the values at object reference pointed by a and b do not match.

System.out.println(b.equals(a)); // NullPointerException, because b is pointing to unknown reference and no operation is allowed

How can I access my localhost from my Android device?

Having a netconfig xml and assign it in the manifest.xml is the best work around. This will bypass the androids default https only contraint.

move_uploaded_file gives "failed to open stream: Permission denied" error

This is because images and tmp_file_upload are only writable by root user. For upload to work we need to make the owner of those folders same as httpd process owner OR make them globally writable (bad practice).

  1. Check apache process owner: $ps aux | grep httpd. The first column will be the owner typically it will be nobody
  2. Change the owner of images and tmp_file_upload to be become nobody or whatever the owner you found in step 1.

    $sudo chown nobody /var/www/html/mysite/images/
    
    $sudo chown nobody /var/www/html/mysite/tmp_file_upload/
    
  3. Chmod images and tmp_file_upload now to be writable by the owner, if needed [Seems you already have this in place]. Mentioned in @Dmitry Teplyakov answer.

    $ sudo chmod -R 0755 /var/www/html/mysite/images/
    
    $ sudo chmod -R 0755 /var/www/html/mysite/tmp_file_upload/
    
  4. For more details why this behavior happend, check the manual http://php.net/manual/en/ini.core.php#ini.upload-tmp-dir , note that it also talking about open_basedir directive.

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

Using migrate ruby on rails

class CreateNeighborhoods < ActiveRecord::Migration[5.0]
  def change
    create_table :neighborhoods do |t|
      t.string :name
      t.decimal :latitude, precision: 15, scale: 13
      t.decimal :longitude, precision: 15, scale: 13
      t.references :country, foreign_key: true
      t.references :state, foreign_key: true
      t.references :city, foreign_key: true

      t.timestamps
    end
  end
end

Whitespaces in java

From sun docs:

\s A whitespace character: [ \t\n\x0B\f\r]

The simplest way is to use it with regex.

Arrays vs Vectors: Introductory Similarities and Differences

Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:

int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;

for vectors, you just declare it and add elements

vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...

at times you wont know the number of elements needed so a vector would be ideal for such a situation.

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

How to convert Blob to String and String to Blob in java

And here is my solution, that always works for me

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }

Hiding axis text in matplotlib plots

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

Can't use System.Windows.Forms

A console application does not automatically add a reference to System.Windows.Forms.dll.

Right-click your project in Solution Explorer and select Add reference... and then find System.Windows.Forms and add it.

How to sort Map values by key in Java?

Short answer

Use a TreeMap. This is precisely what it's for.

If this map is passed to you and you cannot determine the type, then you can do the following:

SortedSet<String> keys = new TreeSet<>(map.keySet());
for (String key : keys) { 
   String value = map.get(key);
   // do something
}

This will iterate across the map in natural order of the keys.


Longer answer

Technically, you can use anything that implements SortedMap, but except for rare cases this amounts to TreeMap, just as using a Map implementation typically amounts to HashMap.

For cases where your keys are a complex type that doesn't implement Comparable or you don't want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator:

// placed inline for the demonstration, but doesn't have to be a lambda expression
Comparator<Foo> comparator = (Foo o1, Foo o2) -> {
        ...
    }

SortedSet<Foo> keys = new TreeSet<>(comparator);
keys.addAll(map.keySet());

Remember when using a TreeMap or TreeSet that it will have different performance characteristics than HashMap or HashSet. Roughly speaking operations that find or insert an element will go from O(1) to O(Log(N)).

In a HashMap, moving from 1000 items to 10,000 doesn't really affect your time to lookup an element, but for a TreeMap the lookup time will be about 3 times slower (assuming Log2). Moving from 1000 to 100,000 will be about 6 times slower for every element lookup.

How to read single Excel cell value

The issue with reading single Excel Cell in .Net comes from the fact, that the empty cell is evaluated to a Null. Thus, one cannot use its .Value or .Value2 properties, because an error shows up.

To return an empty string, when the cell is Null the Convert.ToString(Cell) can be used in the following way:

Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);

for (int i = 1; i < 5; i++)
{
    string a = Convert.ToString(wk.Cells[i, 1].Value2);
    Console.WriteLine(a);
}

Where is jarsigner?

If you are on Mac or Linux, just go to the terminal and type in:

whereis jarsigner

It will give you the location of the jarsigner

Send FormData with other field in AngularJS

This never gonna work, you can't stringify your FormData object.

You should do this:

this.uploadFileToUrl = function(file, title, text, uploadUrl){
   var fd = new FormData();
   fd.append('title', title);
   fd.append('text', text);
   fd.append('file', file);

     $http.post(uploadUrl, obj, {
       transformRequest: angular.identity,
       headers: {'Content-Type': undefined}
     })
  .success(function(){
    blockUI.stop();
  })
  .error(function(error){
    toaster.pop('error', 'Errore', error);
  });
}

Difference between Fact table and Dimension table?

This appears to be a very simple answer on how to differentiate between fact and dimension tables!

It may help to think of dimensions as things or objects. A thing such as a product can exist without ever being involved in a business event. A dimension is your noun. It is something that can exist independent of a business event, such as a sale. Products, employees, equipment, are all things that exist. A dimension either does something, or has something done to it.

Employees sell, customers buy. Employees and customers are examples of dimensions, they do.

Products are sold, they are also dimensions as they have something done to them.

Facts, are the verb. An entry in a fact table marks a discrete event that happens to something from the dimension table. A product sale would be recorded in a fact table. The event of the sale would be noted by what product was sold, which employee sold it, and which customer bought it. Product, Employee, and Customer are all dimensions that describe the event, the sale.

In addition fact tables also typically have some kind of quantitative data. The quantity sold, the price per item, total price, and so on.

Source: http://arcanecode.com/2007/07/23/dimensions-versus-facts-in-data-warehousing/

Split and join C# string

Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):

string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];

This is very similar to the Substring method, just by a different means.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.

In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).

If you suspect a memory leak, use a profiler to find which object occupies all the available memory.

Problem with converting int to string in Linq to entities

One more solution:

c.ContactId + ""

Just add empty string and it will be converted to string.

C# Creating and using Functions

You should either make your Add function static like so:

static public int Add(int x, int y)
{ 
    int result = x + y;
    return result;
 } //END   Add

static means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program class.

or you should create in instance of your Program class, and then call Add on this instance. Like so:

Program prog = new Program();
prog.Add(5,10);

ASP.net page without a code behind

By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>

adb remount permission denied, but able to access super user in shell -- android

Try

adb root
adb remount

to start the adb demon as root and ensure partitions are mounted in read-write mode (the essential part is adb root). After pushing, revoke root permissions again using:

adb unroot

Mysql: Select rows from a table that are not in another

SELECT *
FROM Table1 AS a
WHERE NOT EXISTS (
  SELECT *
  FROM Table2 AS b 
  WHERE a.FirstName=b.FirstName AND a.LastName=b.Last_Name
)

EXISTS will help you...

Adding quotes to a string in VBScript

I don't think I can improve on these answers as I've used them all, but my preference is declaring a constant and using that as it can be a real pain if you have a long string and try to accommodate with the correct number of quotes and make a mistake. ;)

What is SuppressWarnings ("unchecked") in Java?

A warning by which the compiler indicates that it cannot ensure type safety. The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked".

The most common source of "unchecked" warnings is the use of raw types. "unchecked" warnings are issued when an object is accessed through a raw type variable, because the raw type does not provide enough type information to perform all necessary type checks.

Example (of unchecked warning in conjunction with raw types):

TreeSet set = new TreeSet(); 
set.add("abc");        // unchecked warning 
set.remove("abc");
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.TreeSet 
               set.add("abc");  
                      ^

When the add method is invoked the compiler does not know whether it is safe to add a String object to the collection. If the TreeSet is a collection that contains String s (or a supertype thereof), then it would be safe. But from the type information provided by the raw type TreeSet the compiler cannot tell. Hence the call is potentially unsafe and an "unchecked" warning is issued.

"unchecked" warnings are also reported when the compiler finds a cast whose target type is either a parameterized type or a type parameter.

Example (of an unchecked warning in conjunction with a cast to a parameterized type or type variable):

  class Wrapper<T> { 
  private T wrapped ; 
  public Wrapper (T arg) {wrapped = arg;} 
  ... 
  public Wrapper <T> clone() { 
    Wrapper<T> clon = null; 
     try {  
       clon = (Wrapper<T>) super.clone(); // unchecked warning 
     } catch (CloneNotSupportedException e) {  
       throw new InternalError();  
     } 
     try {  
       Class<?> clzz = this.wrapped.getClass(); 
       Method   meth = clzz.getMethod("clone", new Class[0]); 
       Object   dupl = meth.invoke(this.wrapped, new Object[0]); 
       clon.wrapped = (T) dupl; // unchecked warning 
     } catch (Exception e) {} 
     return clon; 
  } 
} 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: Wrapper <T> 
                  clon = ( Wrapper <T>)super.clone();  
                                                ^ 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: T 
                  clon. wrapped = (T)dupl;

A cast whose target type is either a (concrete or bounded wildcard) parameterized type or a type parameter is unsafe, if a dynamic type check at runtime is involved. At runtime, only the type erasure is available, not the exact static type that is visible in the source code. As a result, the runtime part of the cast is performed based on the type erasure, not on the exact static type.

In the example, the cast to Wrapper would check whether the object returned from super.clone is a Wrapper , not whether it is a wrapper with a particular type of members. Similarly, the casts to the type parameter T are cast to type Object at runtime, and probably optimized away altogether. Due to type erasure, the runtime system is unable to perform more useful type checks at runtime.

In a way, the source code is misleading, because it suggests that a cast to the respective target type is performed, while in fact the dynamic part of the cast only checks against the type erasure of the target type. The "unchecked" warning is issued to draw the programmer's attention to this mismatch between the static and dynamic aspect of the cast.

Please refer: What is an "unchecked" warning?

How do I add a submodule to a sub-directory?

You go into ~/.janus and run:

git submodule add <git@github ...> snipmate-snippets/snippets/

If you need more information about submodules (or git in general) ProGit is pretty useful.

How to let an ASMX file output JSON

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

Node Version Manager install - nvm command not found

After trying multiple steps, not sure what was the problem in my case but running this helped:

touch ~/.bash_profile
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash

Verified by nvm --version

nvm -v output

How to remove a build from itunes connect?

I had this problem. I'll share my ride on the learning curve.

First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.

If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.

You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).

Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!

Converting string to number in javascript/jQuery

It sounds like this in your code is not referring to your .btn element. Try referencing it explicitly with a selector:

var votevalue = parseInt($(".btn").data('votevalue'), 10);

Also, don't forget the radix.

Why should we typedef a struct so often in C?

From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):


The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s
    {
    ...
    };

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
    {
    ...
    };
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

This is good.

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    {
    ...
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

extract digits in a simple way from a python string

This regular expression handles floats as well

import re
re_float = re.compile(r'\d*\.?\d+')

You could also add a group to the expression that catches your weight units.

re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')

You can access the named groups like this re_banana.match("200 kgm").group('number').

I think this should help you getting started.

Allow 2 decimal places in <input type="number">

If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places

^\d*(\.\d{0,2})?$

For an example, I have found solution below to be fairly reliable

HTML:

<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />

JS / JQuery:

$(document).on('keydown', 'input[pattern]', function(e){
  var input = $(this);
  var oldVal = input.val();
  var regex = new RegExp(input.attr('pattern'), 'g');

  setTimeout(function(){
    var newVal = input.val();
    if(!regex.test(newVal)){
      input.val(oldVal); 
    }
  }, 0);
});

Update

setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised.

Changing the browser zoom level

Not possible in IE, as the UI Zoom button in the status bar is not scriptable. YMMV for other browsers.

Using python's mock patch.object to change the return value of a method called within another method

There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

Environ Function code samples for VBA

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()
        Dim strVar As String
        Dim i As Long
        For i = 1 To 255
            strVar = Environ$(i)
            If LenB(strVar) = 0& Then Exit For
            Debug.Print strVar
        Next
    End Sub

MVVM Passing EventArgs As Command Parameter

Prism's InvokeCommandAction will pass the event args by default if CommandParameter is not set.

https://docs.microsoft.com/en-us/previous-versions/msp-n-p/gg405494(v=pandp.40)#passing-eventargs-parameters-to-the-command

Here is an example. Note the use of prism:InvokeCommandAction instead of i:InvokeCommandAction.

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Sorting">
        <prism:InvokeCommandAction Command="{Binding SortingCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

The ViewModel

    private DelegateCommand<EventArgs> _sortingCommand;

    public DelegateCommand<EventArgs> SortingCommand => _sortingCommand ?? (_sortingCommand = new DelegateCommand<EventArgs>(OnSortingCommand));

    private void OnSortingCommand(EventArgs obj)
    {
        //do stuff
    }

There is a new version of the Prismlibrary documentation.

Disable Scrolling on Body

HTML css works fine if body tag does nothing you can write as well

<body scroll="no" style="overflow: hidden">

In this case overriding should be on the body tag, it is easier to control but sometimes gives headaches.

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

In your pom.xml you should add distributionManagement configuration to where to deploy.

In the following example I have used file system as the locations.

<distributionManagement>
       <repository>
         <id>internal.repo</id>
         <name>Internal repo</name>
         <url>file:///home/thara/testesb/in</url>
       </repository>
   </distributionManagement>

you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :

mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

Executing a command stored in a variable from PowerShell

Try invoking your command with Invoke-Expression:

Invoke-Expression $cmd1

Here is a working example on my machine:

$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd

iex is an alias for Invoke-Expression so you could do:

iex $cmd1

For a full list : Visit https://ss64.com/ps/ for more Powershell stuff.

Good Luck...

Measure the time it takes to execute a t-sql query

even better, this will measure the average of n iterations of your query! Great for a more accurate reading.

declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100

while @i < @itrs
begin
declare @t0 datetime = GETDATE()

--your query here

declare @t1 datetime = GETDATE()

set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)

set @i = @i + 1
end

select @tTotal/@itrs

Can you do greater than comparison on a date in a Rails 3 search?

You can try to use:

where(date: p[:date]..Float::INFINITY)

equivalent in sql

WHERE (`date` >= p[:date])

The result is:

Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)

And I have changed too

order('date ASC, created_at ASC')

For

order(:fecha, :created_at)

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

Laravel - Session store not set on request

Laravel [5.4]

My solution was to use global session helper: session()

Its functionality is a little bit harder than $request->session().

writing:

session(['key'=>'value']);

pushing:

session()->push('key', $notification);

retrieving:

session('key');

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

iframe to Only Show a Certain Part of the Page

An <iframe> gives you a complete window to work with. The most direct way to do what you want is to have your server give you a complete page that only contains the fragment you want to show.

As an alternative, you could just use a simple <div> and use the jQuery "load" function to load the whole page and pluck out just the section you want:

$('#target-div').load('http://www.mywebsite.com/portfolio.php #portfolio-sports');

There may be other things you need to do, and a significant difference is that the content will become part of the main page instead of being segregated into a separate window.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();

Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?

How to set TextView textStyle such as bold, italic

The easiest way you can do based on the style selection criteria is:

String pre = "", post = "";

if(isBold){
    pre += "<b>"; post += "</b>";
}
if(isItalic){
    pre += "<i>"; post += "</i>";
}
if(isUnderline){
    pre += "<u>"; post += "</u>";
}

textView.setText(Html.fromHtml(pre + editText.getText().toString()+ post));
// you can also use it with EidtText
editText.setText(Html.fromHtml(pre + editText.getText().toString()+ post));

Return only string message from Spring MVC 3 Controller

Annotate your method in controller with @ResponseBody:

@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
    return "Response!";
}

From: 15.3.2.6 Mapping the response body with the @ResponseBody annotation:

The @ResponseBody annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

Flatten List in LINQ

Like this?

var iList = Method().SelectMany(n => n);

How to convert array values to lowercase in PHP?

You don't say if your array is multi-dimensional. If it is, array_map will not work alone. You need a callback method. For multi-dimensional arrays, try array_change_key_case.

// You can pass array_change_key_case a multi-dimensional array,
// or call a method that returns one
$my_array = array_change_key_case(aMethodThatReturnsMultiDimArray(), CASE_UPPER);

How does java do modulus calculations with negative numbers?

Since "mathematically" both are correct:

-13 % 64 = -13 (on modulus 64)  
-13 % 64 = 51 (on modulus 64)

One of the options had to be chosen by Java language developers and they chose:

the sign of the result equals the sign of the dividend.

Says it in Java specs:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

Declaring multiple variables in JavaScript

My only, yet essential, use for a comma is in a for loop:

for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}

I went here to look up whether this is OK in JavaScript.

Even seeing it work, a question remained whether n is local to the function.

This verifies n is local:

a = [3, 5, 7, 11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
  "as expected, n was local" : "oops, n was global");

For a moment I wasn't sure, switching between languages.

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

Add a new line to a text file in MS-DOS

Use the following:

echo (text here) >> (name here).txt

Ex. echo my name is jeff >> test.txt

test.txt

my name is jeff

You can use it in a script too.

Javascript: Easier way to format numbers?

Here's the YUI version if anyone's interested:

http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html

var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );

How can I calculate divide and modulo for integers in C#?

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;

Simple excel find and replace for formulas

Use the find and replace command accessible through ctrl+h, make sure you are searching through the functions of the cells. You can then wildcards to accommodate any deviations of the formula. * for # wildcards, ? for charcter wildcards, and ~? or ~* to search for ? or *.

How to add a class to body tag?

This should do it:

var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);

The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);

That pattern should yield the following:

  • ../about_us.html : about
  • ../something.html : something
  • ../has_two_underscores.html : has

How do I skip a header from CSV files in Spark?

In PySpark you can use a dataframe and set header as True:

df = spark.read.csv(dataPath, header=True)

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had a similar problem but all answers here didn't help me.

For me the problem was a failing test. If you are doing test driven development than a failing / not implemented test shouldn't break the build. I still want my project to build.

To solve this I added a configuration to surefire so that it ignores a failing test.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <testFailureIgnore>true</testFailureIgnore>
    </configuration>
</plugin>

Get checkbox value in jQuery

$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();