Programs & Examples On #Data migration

Data Migration is the movement of data from one location to another and can happen in many forms and many systems. One example of data migration is copying data from one database to another.

How to group by week in MySQL?

If you need the "week ending" date this will work as well. This will count the number of records for each week. Example: If three work orders were created between (inclusive) 1/2/2010 and 1/8/2010 and 5 were created between (inclusive) 1/9/2010 and 1/16/2010 this would return:

3 1/8/2010
5 1/16/2010

I had to use the extra DATE() function to truncate my datetime field.

SELECT COUNT(*), DATE_ADD( DATE(wo.date_created), INTERVAL (7 - DAYOFWEEK( wo.date_created )) DAY) week_ending
FROM work_order wo
GROUP BY week_ending;

How do I move a redis database from one server to another?

I also want to do the same thing: migrate a db from a standalone redis instance to a another redis instances(redis sentinel).

Because the data is not critical(session data), i will give https://github.com/yaauie/redis-copy a try.

How to move Jenkins from one PC to another

This worked for me to move from Ubuntu 12.04 (Jenkins ver. 1.628) to Ubuntu 16.04 (Jenkins ver. 1.651.2). I first installed Jenkins from the repositories.

  1. Stop both Jenkins servers
  2. Copy JENKINS_HOME (e.g. /var/lib/jenkins) from the old server to the new one. From a console in the new server:

    rsync -av username@old-server-IP:/var/lib/jenkins/ /var/lib/jenkins/

  3. Start your new Jenkins server

You might not need this, but I had to

  • Manage Jenkins and Reload Configuration from Disk.
  • Disconnect and connect all the slaves again.
  • Check that in the Configure System > Jenkins Location, the Jenkins URL is correctly assigned to the new Jenkins server.

Exporting data In SQL Server as INSERT INTO

For the sake of over-explicit brainlessness, after following marc_s' instructions to here...

In SSMS in the Object Explorer, right click on the database right-click and pick "Tasks" and then "Generate Scripts".

... I then see a wizard screen with "Introduction, Choose Objects, Set Scripting Options, Summary, and Save or Publish Scripts" with prev, next, finish, cancel buttons at the bottom.

On the Set Scripting Options step, you have to click "Advanced" to get the page with the options. Then, as Ghlouw has mentioned, you now select "Types of data to script" and profit.

advanced button HIGHLIGHTED IN RED!1!!

SQL Server String or binary data would be truncated

I came across this problem today, and in my search for an answer to this minimal informative error message i also found this link:

https://connect.microsoft.com/SQLServer/feedback/details/339410/please-fix-the-string-or-binary-data-would-be-truncated-message-to-give-the-column-name

So it seems microsoft has no plans to expand on error message anytime soon.

So i turned to other means.

I copied the errors to excel:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected) Msg 8152, Level 16, State 14, Line 13 String or binary data would be truncated. The statement has been terminated.

(1 row(s) affected)

counted the number of rows in excel, got to close to the records counter that caused the problem... adjusted my export code to print out the SQL close to it... then ran the 5 - 10 sql inserts around the problem sql and managed to pinpoint the problem one, see the string that was too long, increase size of that column and then big import file ran no problem.

Bit of a hack and a workaround, but when you left with very little choice you do what you can.

What is the exact location of MySQL database tables in XAMPP folder?

Rather late I know, but you can use SELECT @@datadir to get the information.

Happy file huntin' SO community :)

Here's how it looks like when ran via phpmyadmin: enter image description here

OrderBy pipe issue

This will work for any field you pass to it. (IMPORTANT: It will only order alphabetically so if you pass a date it will order it as alphabet not as date)

/*
 *      Example use
 *      Basic Array of single type: *ngFor="let todo of todoService.todos | orderBy : '-'"
 *      Multidimensional Array Sort on single column: *ngFor="let todo of todoService.todos | orderBy : ['-status']"
 *      Multidimensional Array Sort on multiple columns: *ngFor="let todo of todoService.todos | orderBy : ['status', '-title']"
 */

import {Pipe, PipeTransform} from "@angular/core";

@Pipe({name: "orderBy", pure: false})
export class OrderByPipe implements PipeTransform {

    value: string[] = [];

    static _orderByComparator(a: any, b: any): number {

        if (a === null || typeof a === "undefined") { a = 0; }
        if (b === null || typeof b === "undefined") { b = 0; }

        if (
            (isNaN(parseFloat(a)) ||
            !isFinite(a)) ||
            (isNaN(parseFloat(b)) || !isFinite(b))
        ) {
            // Isn"t a number so lowercase the string to properly compare
            a = a.toString();
            b = b.toString();
            if (a.toLowerCase() < b.toLowerCase()) { return -1; }
            if (a.toLowerCase() > b.toLowerCase()) { return 1; }
        } else {
            // Parse strings as numbers to compare properly
            if (parseFloat(a) < parseFloat(b)) { return -1; }
            if (parseFloat(a) > parseFloat(b)) { return 1; }
        }

        return 0; // equal each other
    }

    public transform(input: any, config = "+"): any {
        if (!input) { return input; }

        // make a copy of the input"s reference
        this.value = [...input];
        let value = this.value;
        if (!Array.isArray(value)) { return value; }

        if (!Array.isArray(config) || (Array.isArray(config) && config.length === 1)) {
            let propertyToCheck: string = !Array.isArray(config) ? config : config[0];
            let desc = propertyToCheck.substr(0, 1) === "-";

            // Basic array
            if (!propertyToCheck || propertyToCheck === "-" || propertyToCheck === "+") {
                return !desc ? value.sort() : value.sort().reverse();
            } else {
                let property: string = propertyToCheck.substr(0, 1) === "+" || propertyToCheck.substr(0, 1) === "-"
                    ? propertyToCheck.substr(1)
                    : propertyToCheck;

                return value.sort(function(a: any, b: any) {
                    let aValue = a[property];
                    let bValue = b[property];

                    let propertySplit = property.split(".");

                    if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) {
                        aValue = a;
                        bValue = b;
                        for (let j = 0; j < propertySplit.length; j++) {
                            aValue = aValue[propertySplit[j]];
                            bValue = bValue[propertySplit[j]];
                        }
                    }

                    return !desc
                        ? OrderByPipe._orderByComparator(aValue, bValue)
                        : -OrderByPipe._orderByComparator(aValue, bValue);
                });
            }
        } else {
            // Loop over property of the array in order and sort
            return value.sort(function(a: any, b: any) {
                for (let i = 0; i < config.length; i++) {
                    let desc = config[i].substr(0, 1) === "-";
                    let property = config[i].substr(0, 1) === "+" || config[i].substr(0, 1) === "-"
                        ? config[i].substr(1)
                        : config[i];

                    let aValue = a[property];
                    let bValue = b[property];

                    let propertySplit = property.split(".");

                    if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) {
                        aValue = a;
                        bValue = b;
                        for (let j = 0; j < propertySplit.length; j++) {
                            aValue = aValue[propertySplit[j]];
                            bValue = bValue[propertySplit[j]];
                        }
                    }

                    let comparison = !desc
                        ? OrderByPipe._orderByComparator(aValue, bValue)
                        : -OrderByPipe._orderByComparator(aValue, bValue);

                    // Don"t return 0 yet in case of needing to sort by next property
                    if (comparison !== 0) { return comparison; }
                }

                return 0; // equal each other
            });
        }
    }
}

How to concatenate text from multiple rows into a single text string in SQL server?

How about this:

   ISNULL(SUBSTRING(REPLACE((select ',' FName as 'data()' from NameList for xml path('')), ' ,',', '), 2, 300), '') 'MyList'

Where the "300" could be any width taking into account the max number of items you think will show up.

Calculate the execution time of a method

If you are interested in understand performance, the best answer is to use a profiler.

Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.

C++ error 'Undefined reference to Class::Function()'

This part has problems:

Card* cardArray;
void Deck() {
    cardArray = new Card[NUM_TOTAL_CARDS];
    int cardCount = 0;
    for (int i = 0; i > NUM_SUITS; i++) {  //Error
        for (int j = 0; j > NUM_RANKS; j++) { //Error
            cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
            cardCount++;
         }
    }
 }
  1. cardArray is a dynamic array, but not a member of Card class. It is strange if you would like to initialize a dynamic array which is not member of the class
  2. void Deck() is not constructor of class Deck since you missed the scope resolution operator. You may be confused with defining the constructor and the function with name Deck and return type void.
  3. in your loops, you should use < not > otherwise, loop will never be executed.

Edit and replay XHR chrome/firefox etc?

Chrome :

  • In the Network panel of devtools, right-click and select Copy as cURL
  • Paste / Edit the request, and then send it from a terminal, assuming you have the curl command

See capture :

enter image description here

Alternatively, and in case you need to send the request in the context of a webpage, select "Copy as fetch" and edit-send the content from the javascript console panel.


Firefox :

Firefox allows to edit and resend XHR right from the Network panel. Capture below is from Firefox 36:

enter image description here

How to get Selected Text from select2 when using <input>

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via ajax

 $("#vendor-brands").select2({
   ajax: {
   url:site_url('general/get_brand_ajax_json'),
  dataType: 'json',
  delay: 250,
  data: function (params) {
  return {
    q: params.term, // search term
    page: params.page
  };
},
processResults: function (data, params) {
  // parse the results into the format expected by Select2
  // since we are using custom formatting functions we do not need to
  // alter the remote JSON data, except to indicate that infinite
  // scrolling can be used
  params.page = params.page || 1;

  return {
    results: data,
    pagination: {
      more: (params.page * 30) < data.total_count
    }
  };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom    formatter work
minimumInputLength: 1,
}).on("change", function(e) {


  var lastValue = $("#vendor-brands option:last-child").val();
  var lastText = $("#vendor-brands option:last-child").text();

  alert(lastValue+' '+lastText);
 });

Change a Rails application to production

If you're running on Passenger, then the default is to run in production, in your apache conf:

<VirtualHost *:80>
  ServerName application_name.rails.local
  DocumentRoot "/Users/rails/application_name/public"
  RailsEnv production ## This is the default
</VirtualHost>

If you're just running a local server with mongrel or webrick, you can do:

./script/server -e production

or in bash:

RAILS_ENV=production ./script/server

actually overriding the RAILS_ENV constant in the enviornment.rb should probably be your last resort, as it's probably not going to stay set (see another answer I gave on that)

How to get the first day of the current week and month?

public static void main(String[] args) {
    System.out.println(getMonthlyEpochList(1498867199L,12,"Monthly"));

}

public static Map<String,String> getMonthlyEpochList(Long currentEpoch, int noOfTerms, String timeMode) {
    Map<String,String> map = new LinkedHashMap<String,String>();
    int month = 0;
    while(noOfTerms != 0) {
        Calendar calendar = Calendar.getInstance();         
        calendar.add(Calendar.MONTH, month);
        calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date monthFirstDay = calendar.getTime();
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date monthLastDay = calendar.getTime();
        map.put(getMMYY(monthFirstDay.getTime()), monthFirstDay + ":" +monthLastDay);
        month--;
        noOfTerms--;
    }
    return map;     
}

Merging two arrays in .NET

Just to have it noted as an option: if the arrays you are working with are of a primitive type – Boolean (bool), Char, SByte, Byte, Int16 (short), UInt16, Int32 (int), UInt32, Int64 (long), UInt64, IntPtr, UIntPtr, Single, or Double – then you could (or should?) try using Buffer.BlockCopy. According to the MSDN page for the Buffer class:

This class provides better performance for manipulating primitive types than similar methods in the System.Array class.

Using the C# 2.0 example from @OwenP's answer as a starting point, it would work as follows:

int[] front = { 1, 2, 3, 4 };
int[] back = { 5, 6, 7, 8 };

int[] combined = new int[front.Length + back.Length];
Buffer.BlockCopy(front, 0, combined, 0, front.Length);
Buffer.BlockCopy(back, 0, combined, front.Length, back.Length);

There is barely any difference in syntax between Buffer.BlockCopy and the Array.Copy that @OwenP used, but this should be faster (even if only slightly).

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

Getting the difference between two sets

Just to put one example here (system is in existingState, and we want to find elements to remove (elements that are not in newState but are present in existingState) and elements to add (elements that are in newState but are not present in existingState) :

public class AddAndRemove {

  static Set<Integer> existingState = Set.of(1,2,3,4,5);
  static Set<Integer> newState = Set.of(0,5,2,11,3,99);

  public static void main(String[] args) {

    Set<Integer> add = new HashSet<>(newState);
    add.removeAll(existingState);

    System.out.println("Elements to add : " + add);

    Set<Integer> remove = new HashSet<>(existingState);
    remove.removeAll(newState);

    System.out.println("Elements to remove : " + remove);

  }
}

would output this as a result:

Elements to add : [0, 99, 11]
Elements to remove : [1, 4]

Allow multi-line in EditText view in Android?

All of these are nice but will not work in case you have your edittext inside upper level scroll view :) Perhaps most common example is "Settings" view that has so many items that the they go beyond of visible area. In this case you put them all into scroll view to make settings scrollable. In case that you need multiline scrollable edit text in your settings, its scroll will not work.

How to shut down the computer from C#

**Elaborated Answer...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// Remember to add a reference to the System.Management assembly
using System.Management;
using System.Diagnostics;

namespace ShutDown
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnShutDown_Click(object sender, EventArgs e)
        {
            ManagementBaseObject mboShutdown = null;
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system
            mboShutdownParams["Flags"] = "1";
            mboShutdownParams["Reserved"] = "0";

            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
            }
        }
    }
}

How do I fetch only one branch of a remote Git repository?

git version 2.16.1.windows.4

Just doing a git fetch remoteRepositoryName branchName (eg: git fetch origin my_local_branch) is enough. Fetch will be done and a new local branch will be created with the same name and tracking will be set to remote branch.

Then perform git checkout branchName

How to convert an int to a hex string?

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

What is the difference between a web API and a web service?

API and Web service serve as a means of communication.

The only difference is that a Web service facilitates interaction between two machines over a network. An API acts as an interface between two different applications so that they can communicate with each other. An API is a method by which third-party vendors can write programs that interface easily with other programs. A Web service is designed to have an interface that is depicted in a machine-processable format usually specified in Web Service Description Language (WSDL)

All Web services are APIs but not all APIs are Web services.

A Web service is merely an API wrapped in HTTP.


This here article provides good knowledge regarding web service and API.

Add a properties file to IntelliJ's classpath

For those of you who migrate from Eclipse to IntelliJ or the other way around here is a tip when working with property files or other resource files.

Its maddening (cost my a whole evening to find out) but both IDE's work quite different when it comes to looking for resource/propertty files when you want to run locally from your IDE or during debugging. (Packaging to a .jar is also quite different, but thats documented better.)

Suppose you have a relative path referral like this in your code:

new FileInputStream("xxxx.properties");

(which is convenient if you work with env specific .properties files which you don't want to package along with your JAR)

INTELLIJ

(I use 13.1 , but could be valid for more versions)

The file xxxx.properties needs to be at the PARENT dir of the project ROOT in order to be picked up at runtime like this in IntelliJ. (The project ROOT is where the /src folder resides in)

ECLIPSE

Eclipse is just happy when the xxxx.properties file is at the project ROOT itself.

So IntelliJ expects .properties file to be 1 level higher then Eclipse when it is referenced like this !!

This also affects the way you have to execute your code when you have this same line of code ( new FileInputStream("xxxx.properties"); ) in your exported .jar. When you want to be agile and don't want to package the .properties file with your jar you'll have to execute the jar like below in order to reference the .properties file correctly from the command line:

INTELLIJ EXPORTED JAR

java -cp "/path/to_properties_file/:/path/to_jar/some.jar" com.bla.blabla.ClassContainingMainMethod

ECLIPSE EXPORTED JAR

java -jar some.jar

where the Eclipse exported executable jar will just expect the referenced .properties file to be on the same location as where the .jar file is

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

  1. Since you are on Windows, make sure that your certificate in Windows "compatible", most importantly that it doesn't have ^M in the end of each line

    If you open it it will look like this:

    -----BEGIN CERTIFICATE-----^M
    MIIDITCCAoqgAwIBAgIQL9+89q6RUm0PmqPfQDQ+mjANBgkqhkiG9w0BAQUFADBM^M
    

    To solve "this" open it with Write or Notepad++ and have it convert it to Windows "style"

  2. Try to run openssl x509 -text -inform DER -in server_cert.pem and see what the output is, it is unlikely that a private/secret key would be untrusted, trust only is needed if you exported the key from a keystore, did you?

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

Since Docker 17.05 COPY is used with the --from flag in multi-stage builds to copy artifacts from previous build stages to the current build stage.

from the documentation

Optionally COPY accepts a flag --from=<name|index> that can be used to set the source location to a previous build stage (created with FROM .. AS ) that will be used instead of a build context sent by the user.

HTTP Error 404.3-Not Found in IIS 7.5

You should install IIS sub components from

Control Panel -> Programs and Features -> Turn Windows features on or off

Internet Information Services has subsection World Wide Web Services / Application Development Features

There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.

Run from cmd:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.

Also, look at this answer.

Parse v. TryParse

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

How to set Grid row and column positions programmatically

Here is an example which might help someone:

Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());

Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";

Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);

Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);

Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);

Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);

Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);

Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);

Django - how to create a file and save it to a model's FileField?

You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().

Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is:

self.license_file.save(new_name, new_contents)

where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details).

The two choices boil down to:

from django.core.files.base import ContentFile, File

# Using File
with open('/path/to/file') as f:
    self.license_file.save(new_name, File(f))

# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))

How to preSelect an html dropdown list with php?

<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">

This is a very simple and straightforward way, if I understand your question correctly.

How to declare a vector of zeros in R

replicate is another option:

replicate(10, 0)
# [1] 0 0 0 0 0 0 0 0 0 0

replicate(5, 1)
# [1] 1 1 1 1 1

To create a matrix:

replicate( 5, numeric(3) )

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    0    0
#[2,]    0    0    0    0    0
#[3,]    0    0    0    0    0

What is the difference between an int and an Integer in Java and C#?

In platforms like Java, ints are primitives while Integer is an object which holds a integer field. The important distinction is that primitives are always passed around by value and by definition are immutable.

Any operation involving a primitive variable always returns a new value. On the other hand, objects are passed around by reference. One could argue that the point to the object (AKA the reference) is also being passed around by value, but the contents are not.

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

How to find out what this MySQL Error is trying to say:

#1064 - You have an error in your SQL syntax;

This error has no clues in it. You have to double check all of these items to see where your mistake is:

  1. You have omitted, or included an unnecessary symbol: !@#$%^&*()-_=+[]{}\|;:'",<>/?
  2. A misplaced, missing or unnecessary keyword: select, into, or countless others.
  3. You have unicode characters that look like ascii characters in your query but are not recognized.
  4. Misplaced, missing or unnecessary whitespace or newlines between keywords.
  5. Unmatched single quotes, double quotes, parenthesis or braces.

Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.

Find all CSV files in a directory using Python

While solution given by thclpr works it scans only immediate files in the directory and not files in the sub directories if any. Although this is not the requirement but just in case someone wishes to scan sub directories too below is the code that uses os.walk

import os
from glob import glob
PATH = "/home/someuser/projects/someproject"
EXT = "*.csv"
all_csv_files = [file
                 for path, subdir, files in os.walk(PATH)
                 for file in glob(os.path.join(path, EXT))]
print(all_csv_files)

Copied from this blog.

Javascript code for showing yesterday's date and todays date

One liner:

var yesterday = new Date(Date.now() - 864e5); // 864e5 == 86400000 == 24*60*60*1000

How to rotate the background image in the container?

Update 2020, May:

Setting position: absolute and then transform: rotate(45deg) will provide a background:

_x000D_
_x000D_
div {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  outline: 2px dashed slateBlue;_x000D_
  overflow: hidden;_x000D_
}_x000D_
div img {_x000D_
  position: absolute;_x000D_
  transform: rotate(45deg);_x000D_
  z-index: -1;_x000D_
  top: 40px;_x000D_
  left: 40px;_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://placekitten.com/120/120" />_x000D_
  <h1>Hello World!</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Original Answer:

In my case, the image size is not so large that I cannot have a rotated copy of it. So, the image has been rotated with photoshop. An alternative to photoshop for rotating images is online tool too for rotating images. Once rotated, I'm working with the rotated-image in the background property.

div.with-background {
    background-image: url(/img/rotated-image.png);
    background-size:     contain;
    background-repeat:   no-repeat;
    background-position: top center;
}

Good Luck...

What is the difference between And and AndAlso in VB.NET?

To understand with words not cods:

Use Case:
With “And” the compiler will check all conditions so if you are checking that an object could be “Nothing” and then you are checking one of it’s properties you will have a run time error.
But with AndAlso with the first “false” in the conditions it will checking the next one so you will not have an error.

Use of for_each on map elements

How about a plain C++? (example fixed according to the note by @Noah Roberts)

for(std::map<int, MyClass>::iterator itr = Map.begin(), itr_end = Map.end(); itr != itr_end; ++itr) {
  itr->second.Method();
}

How can I iterate over files in a given directory?

Original answer:

import os

for filename in os.listdir(directory):
    if filename.endswith(".asm") or filename.endswith(".py"): 
         # print(os.path.join(directory, filename))
        continue
    else:
        continue

Python 3.6 version of the above answer, using os - assuming that you have the directory path as a str object in a variable called directory_in_str:

import os

directory = os.fsencode(directory_in_str)
    
for file in os.listdir(directory):
     filename = os.fsdecode(file)
     if filename.endswith(".asm") or filename.endswith(".py"): 
         # print(os.path.join(directory, filename))
         continue
     else:
         continue

Or recursively, using pathlib:

from pathlib import Path

pathlist = Path(directory_in_str).glob('**/*.asm')
for path in pathlist:
     # because path is object not string
     path_in_str = str(path)
     # print(path_in_str)
  • Use rglob to replace glob('**/*.asm') with rglob('*.asm')
    • This is like calling Path.glob() with '**/' added in front of the given relative pattern:
from pathlib import Path

pathlist = Path(directory_in_str).rglob('*.asm')
for path in pathlist:
     # because path is object not string
     path_in_str = str(path)
     # print(path_in_str)

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

What is __init__.py for?

In addition to labeling a directory as a Python package and defining __all__, __init__.py allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic "flat is better than nested" philosophy.

An example

Here is an example from one of my projects, in which I frequently import a sessionmaker called Session to interact with my database. I wrote a "database" package with a few modules:

database/
    __init__.py
    schema.py
    insertions.py
    queries.py

My __init__.py contains the following code:

import os

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

engine = create_engine(os.environ['DATABASE_URL'])
Session = sessionmaker(bind=engine)

Since I define Session here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the "database" package directory.

from database import Session
session = Session()

Of course, this is a small convenience -- the alternative would be to define Session in a new file like "create_session.py" in my database package, and start new sessions using:

from database.create_session import Session
session = Session()

Further reading

There is a pretty interesting reddit thread covering appropriate uses of __init__.py here:

http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/

The majority opinion seems to be that __init__.py files should be very thin to avoid violating the "explicit is better than implicit" philosophy.

string.Replace in AngularJs

In Javascript method names are camel case, so it's replace, not Replace:

$scope.newString = oldString.replace("stackover","NO");

Note that contrary to how the .NET Replace method works, the Javascript replace method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:

$scope.newString = oldString.replace(/stackover/g,"NO");

See this example.

center a row using Bootstrap 3

Instead of

<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>

You could just use

<div class="col-md-4 col-md-offset-4"></div>

As long as you don't want anything in columns 1 & 3 this is a more elegant solution. The offset "adds" 4 columns in front, leaving you with 4 "spare" after.

PS I realise that the initial question specifies no offsets but at least one previous answer uses a CSS hack that is unnecessary if you use offsets. So for completeness' sake I think this is valid.

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

How do I initialize Kotlin's MutableList to empty MutableList?

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

How to remove all files from directory without removing directory in Node.js

How about run a command line:

require('child_process').execSync('rm -rf /path/to/directory/*')

div background color, to change onhover

There is no need to put anchor. To change style of div on hover then Change background color of div on hover.

<div class="div_hover"> Change div background color on hover</div>

In .css page

.div_hover { background-color: #FFFFFF; }

.div_hover:hover { background-color: #000000; }

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

React-Router External link

FOR V3, although it may work for V4. Going off of Eric's answer, I needed to do a little more, like handle local development where 'http' is not present on the url. I'm also redirecting to another application on the same server.

Added to router file:

import RedirectOnServer from './components/RedirectOnServer';

       <Route path="/somelocalpath"
          component={RedirectOnServer}
          target="/someexternaltargetstring like cnn.com"
        />

And the Component:

import React, { Component } from "react";

export class RedirectOnServer extends Component {

  constructor(props) {
    super();
    //if the prefix is http or https, we add nothing
    let prefix = window.location.host.startsWith("http") ? "" : "http://";
    //using host here, as I'm redirecting to another location on the same host
    this.target = prefix + window.location.host + props.route.target;
  }
  componentDidMount() {
    window.location.replace(this.target);
  }
  render(){
    return (
      <div>
        <br />
        <span>Redirecting to {this.target}</span>
      </div>
    );
  }
}

export default RedirectOnServer;

JavaScript TypeError: Cannot read property 'style' of null

In your script, this part:

document.getElementById('Noite')

must be returning null and you are also attempting to set the display property to an invalid value. There are a couple of possible reasons for this first part to be null.

  1. You are running the script too early before the document has been loaded and thus the Noite item can't be found.

  2. There is no Noite item in your HTML.

I should point out that your use of document.write() in this case code probably signifies a problem. If the document has already loaded, then a new document.write() will clear the old content and start a new fresh document so no Noite item would be found.

If your document has not yet been loaded and thus you're doing document.write() inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite item.

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write() statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).


In addition, setting the display property to "display" doesn't make sense to me. The valid options for that are "block", "inline", "none", "table", etc... I'm not aware of any option named "display" for that style property. See here for valid options for teh display property.

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.


P.S. I should point out that your lack of braces for your if statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.


I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added var declarations to your variables (a good habit to always use).
  3. The if statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every if statement so it absolutely clear which statements are part of the if/else and which are not.
  5. I've properly closed the </dd> tag you were inserting.
  6. I've changed style.display = ''; to style.display = 'block';.
  7. I've added semicolons at the end of every statement (another good habit to follow).

The code:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você não<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almoçar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

How can I convert an image into Base64 string using JavaScript?

There are multiple approaches you can choose from:

1. Approach: FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:

_x000D_
_x000D_
function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})
_x000D_
_x000D_
_x000D_

This code example could also be implemented using the WHATWG fetch API:

_x000D_
_x000D_
const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))


toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
  })
_x000D_
_x000D_
_x000D_

These approaches:

  • lack in browser support
  • have better compression
  • work for other file types as well

Browser Support:


2. Approach: Canvas

Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.

_x000D_
_x000D_
function toDataURL(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
  if (img.complete || img.complete === undefined) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
  }
}

toDataURL(
  'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
  function(dataUrl) {
    console.log('RESULT:', dataUrl)
  }
)
_x000D_
_x000D_
_x000D_

In detail

Supported input formats:

image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx

Supported output formats:

image/png, image/jpeg, image/webp(chrome)

Browser Support:


3. Approach: Images from the local file system

If you want to convert images from the users file system you need to take a different approach. Use the FileReader API:

_x000D_
_x000D_
function encodeImageFileAsURL(element) {
  var file = element.files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    console.log('RESULT', reader.result)
  }
  reader.readAsDataURL(file);
}
_x000D_
<input type="file" onchange="encodeImageFileAsURL(this)" />
_x000D_
_x000D_
_x000D_

Generics/templates in python?

Actually now you can use generics in Python 3.5+. See PEP-484 and typing module documentation.

According to my practice it is not very seamless and clear especially for those who are familiar with Java Generics, but still usable.

Cannot uninstall angular-cli

You are using the beta version of angular CLI you can do this way.

npm uninstall -g @angular/cli
npm uninstall -g angular/cli

Then type,

npm cache clean

Then go to the AppData folder which is hidden in your users and go to roaming folder which is inside AppData then go to npm folder and delete angular files in there and also go to npm-cache folder and delete angular components in there.After that restart your PC and type

npm install -g @angular/cli@latest

This worked for me ??

Can someone explain Microsoft Unity?

MSDN has a Developer's Guide to Dependency Injection Using Unity that may be useful.

The Developer's Guide starts with the basics of what dependency injection is, and continues with examples of how to use Unity for dependency injection. As of the February 2014 the Developer's Guide covers Unity 3.0, which was released in April 2013.

Limit the size of a file upload (html input element)

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";
    };
};

This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.

Here is the jsfiddle example for more clearence:
https://jsfiddle.net/7bjfr/808/

Why should I use IHttpActionResult instead of HttpResponseMessage?

You can still use HttpResponseMessage. That capability will not go away. I felt the same way as you and argued extensively with the team that there was no need for an additional abstraction. There were a few arguments thrown around to try and justify its existence but nothing that convinced me that it was worthwhile.

That is, until I saw this sample from Brad Wilson. If you construct IHttpActionResult classes in a way that can be chained, you gain the ability to create a "action-level" response pipeline for generating the HttpResponseMessage. Under the covers, this is how ActionFilters are implemented however, the ordering of those ActionFilters is not obvious when reading the action method which is one reason I'm not a fan of action filters.

However, by creating an IHttpActionResult that can be explicitly chained in your action method you can compose all kinds of different behaviour to generate your response.

Should I use PATCH or PUT in my REST API?

One possible option to implement such behavior is

PUT /groups/api/v1/groups/{group id}/status
{
    "Status":"Activated"
}

And obviously, if someone need to deactivate it, PUT will have Deactivated status in JSON.

In case of necessity of mass activation/deactivation, PATCH can step into the game (not for exact group, but for groups resource:

PATCH /groups/api/v1/groups
{
    { “op”: “replace”, “path”: “/group1/status”, “value”: “Activated” },
    { “op”: “replace”, “path”: “/group7/status”, “value”: “Activated” },
    { “op”: “replace”, “path”: “/group9/status”, “value”: “Deactivated” }
}

In general this is idea as @Andrew Dobrowolski suggesting, but with slight changes in exact realization.

Easiest way to flip a boolean value?

I prefer John T's solution, but if you want to go all code-golfy, your statement logically reduces to this:

//if key is down, toggle the boolean, else leave it alone.
flipVal = ((wParam==VK_F11) && !flipVal) || (!(wParam==VK_F11) && flipVal);
if(wParam==VK_F11) Break;

//if key is down, toggle the boolean, else leave it alone.
otherVal = ((wParam==VK_F12) && !otherVal) || (!(wParam==VK_F12) && otherVal);
if(wParam==VK_F12) Break;

How can I load storyboard programmatically from class?

Swift 3

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "viewController")
self.navigationController!.pushViewController(vc, animated: true)

Swift 2

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController")
self.navigationController!.pushViewController(vc, animated: true)

Prerequisite

Assign a Storyboard ID to your view controller.

Storyboard ID

IB > Show the Identity inspector > Identity > Storyboard ID

Swift (legacy)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController") as? UIViewController
self.navigationController!.pushViewController(vc!, animated: true)

Edit: Swift 2 suggested in a comment by Fred A.

if you want to use without any navigationController you have to use like following :

    let Storyboard  = UIStoryboard(name: "Main", bundle: nil)
    let vc = Storyboard.instantiateViewController(withIdentifier: "viewController")
    present(vc , animated: true , completion: nil)

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

Searching in a ArrayList with custom objects for certain strings

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

jQuery add blank option to top of list and make selected to existing dropdown

Solution native Javascript :

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example : http://codepen.io/anon/pen/GprybL

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Add before OpenDatabase this lines:

File outFile = new File(Environment.getDataDirectory(), outFileName);
outFile.setWritable(true);
SQLiteDatabase.openDatabase(outFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);

How do I filter ForeignKey choices in a Django ModelForm?

In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the ModelForm.__init__ function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy.

class ClientForm(forms.ModelForm):
    def __init__(self,company,*args,**kwargs):
        super (ClientForm,self ).__init__(*args,**kwargs) # populates the post
        self.fields['rate'].queryset = Rate.objects.filter(company=company)
        self.fields['client'].queryset = Client.objects.filter(company=company)

    class Meta:
        model = Client

def addclient(request, company_id):
        the_company = get_object_or_404(Company, id=company_id)

        if request.POST:
            form = ClientForm(the_company,request.POST)  #<-- Note the extra arg
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(the_company.get_clients_url())
        else:
            form = ClientForm(the_company)

        return render_to_response('addclient.html', 
                                  {'form': form, 'the_company':the_company})

This can be useful for reuse say if you have common filters needed on many models (normally I declare an abstract Form class). E.g.

class UberClientForm(ClientForm):
    class Meta:
        model = UberClient

def view(request):
    ...
    form = UberClientForm(company)
    ...

#or even extend the existing custom init
class PITAClient(ClientForm):
    def __init__(company, *args, **args):
        super (PITAClient,self ).__init__(company,*args,**kwargs)
        self.fields['support_staff'].queryset = User.objects.exclude(user='michael')

Other than that I'm just restating Django blog material of which there are many good ones out there.

How to extract the hostname portion of a URL in JavaScript

The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.

Take a look at the URL object:

var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol;  // "http:"
url.hostname;  // "aaa.bbb.ccc.com"
url.pathname;  // "/asdf/asdf/sadf.aspx"
url.search;    // "?blah"

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

How can I make a button have a rounded border in Swift?

TRY THIS Button Border With Rounded Corners

anyButton.backgroundColor = .clear

anyButton.layer.cornerRadius = anyButton.frame.height / 2

anyButton.layer.borderWidth = 1

anyButton.layer.borderColor = UIColor.black.cgColor

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

Where can I find WcfTestClient.exe (part of Visual Studio)

C:\Program Files (x86)\Microsoft Visual Studio (Your Version Here)\Common7\IDE

Leading zeros for Int in Swift

Swift 3.0+

Left padding String extension similar to padding(toLength:withPad:startingAt:) in Foundation

extension String {
    func leftPadding(toLength: Int, withPad: String = " ") -> String {

        guard toLength > self.characters.count else { return self }

        let padding = String(repeating: withPad, count: toLength - self.characters.count)
        return padding + self
    }
}

Usage:

let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

Declare and initialize a Dictionary in Typescript

Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.

Record<string, Partial<IPerson>>

interface IPerson {
   firstName: string;
   lastName: string;
}

var persons: Record<string, Partial<IPerson>> = {
   "p1": { firstName: "F1", lastName: "L1" },
   "p2": { firstName: "F2" }
};

Explanation.

  1. Record type creates a dictionary/hashmap.
  2. Partial type says some of the fields may be missing.

Alternate.

If you wish to make last name optional you can append a ? Typescript will know that it's optional.

lastName?: string;

https://www.typescriptlang.org/docs/handbook/utility-types.html

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

The ORA-2270 error is a straightforward logical error: it happens when the columns we list in the foreign key do not match a primary key or unique constraint on the parent table. Common reasons for this are

  • the parent lacks a PRIMARY KEY or UNIQUE constraint altogether
  • the foreign key clause references the wrong column in the parent table
  • the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.

Neither appears to be the case in your posted code. But that's a red herring, because your code does not run as you have posted it. Judging from the previous edits I presume you are not posting your actual code but some simplified example. Unfortunately in the process of simplification you have eradicated whatever is causing the ORA-2270 error.

SQL> CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   NUMBER,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );  2    3    4    5    6  

Table created.

SQL> CREATE TABLE USER
 (
   ID       NUMBER NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );  2    3    4    5  
CREATE TABLE USER
             *
ERROR at line 1:
ORA-00903: invalid table name


SQL> 

That statement failed because USER is a reserved keyword so we cannot name a table USER. Let's fix that:

SQL> 1
  1* CREATE TABLE USER
SQL> a s
  1* CREATE TABLE USERs
SQL> l
  1  CREATE TABLE USERs
  2   (
  3     ID       NUMBER NOT NULL ,
  4     CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
  5*  )
SQL> r
  1  CREATE TABLE USERs
  2   (
  3     ID       NUMBER NOT NULL ,
  4     CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
  5*  )

Table created.

SQL> Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USERS(ID);   

Table altered.

SQL> 

And lo! No ORA-2270 error.

Alas, there's not much we can do here to help you further. You have a bug in your code. You can post your code here and one of us can spot your mistake. Or you can check your own code and discover it for yourself.


Note: an earlier version of the code defined HOB.USERID as VARCHAR2(20). Because USER.ID is defined as a NUMBER the attempt to create a foreign key would have hurl a different error:

ORA-02267: column type incompatible with referenced column type

An easy way to avoid mismatches is to use foreign key syntax to default the datatype of the column:

CREATE TABLE USERs
 (
   ID    number NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );

CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   constraint FK_USERID references users,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );

Attach IntelliJ IDEA debugger to a running Java process

It's possible, but you have to add some JVM flags when you start your application.

You have to add remote debug configuration: Edit configuration -> Remote.

Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y)

Is there any way I can define a variable in LaTeX?

add the following to you preamble:

\newcommand{\newCommandName}{text to insert}

Then you can just use \newCommandName{} in the text

For more info on \newcommand, see e.g. wikibooks

Example:

\documentclass{article}
\newcommand\x{30}
\begin{document}
\x
\end{document}

Output:

30

CSS technique for a horizontal line with words in the middle

Shortest and best method:

_x000D_
_x000D_
span:after,_x000D_
span:before{_x000D_
    content:"\00a0\00a0\00a0\00a0\00a0";_x000D_
    text-decoration:line-through;_x000D_
}
_x000D_
<span> your text </span>
_x000D_
_x000D_
_x000D_

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

How can a add a row to a data frame in R?

To formalize what someone else used setNames for:

add_row <- function(original_data, new_vals_list){ 
  # appends row to dataset while assuming new vals are ordered and classed appropriately. 
  # new_vals must be a list not a single vector. 
  rbind(
    original_data,
    setNames(data.frame(new_vals_list), colnames(original_data))
    )
  }

It preserves class when legal and passes errors elsewhere.

m <- mtcars[ ,1:3]
m$cyl <- as.factor(m$cyl)
str(m)

#'data.frame':  32 obs. of  3 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num  160 160 108 258 360 ...

Factor preserved when adding 4, even though it was passed as a numeric.

str(add_row(m, list(20,4,160)))
#'data.frame':  33 obs. of  3 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ... 
# $ disp: num  160 160 108 258 360 ...

Attempting to pass a non- 4,6,8 would return an error that factor level is invalid.

str(add_row(m, list(20,3,160)))
# 'data.frame': 33 obs. of  3 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num  160 160 108 258 360 ...
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 3) :
  invalid factor level, NA generated

Could you explain STA and MTA?

Each EXE which hosts COM or OLE controls defines it's apartment state. The apartment state is by default STA (and for most programs should be STA).

STA - All OLE controls by necessity must live in a STA. STA means that your COM-object must be always manipulated on the UI thread and cannot be passed to other threads (much like any UI element in MFC). However, your program can still have many threads.

MTA - You can manipulate the COM object on any thread in your program.

Creating a new user and password with Ansible

This is how it worked for me

- hosts: main
  vars:
  # created with:
  #  python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('<password>')"
  # above command requires the PassLib library: sudo pip install passlib
  - password: '$6$rounds=100000$H/83rErWaObIruDw$DEX.DgAuZuuF.wOyCjGHnVqIetVt3qRDnTUvLJHBFKdYr29uVYbfXJeHg.IacaEQ08WaHo9xCsJQgfgZjqGZI0'

tasks:

- user: name=spree password={{password}} groups=sudo,www-data shell=/bin/bash append=yes
  sudo: yes

Adding Lombok plugin to IntelliJ project

To install the plugin manually, try:

  1. Download Lombok zip file (ensure Lombok matches the IDE version).
  2. Select Preferences Plugins Install Plugins from Disk.

IntelliJ Plugin Preferences Dialog

How do you rotate a two dimensional array?

In place clock wise 90 degrees rotation using vector of vectors..

 #include<iostream>
 #include<vector>
 #include<algorithm>
 using namespace std;
 //Rotate a Matrix by 90 degrees
void rotateMatrix(vector<vector<int> > &matrix){
   int n=matrix.size();
   for(int i=0;i<n;i++){
    for(int j=i+1;j<n;j++){
        swap(matrix[i][j],matrix[j][i]);
    }
 }
     for(int i=0;i<n;i++){
        reverse(matrix[i].begin(),matrix[i].end());
       }
   }

    int main(){

   int n;
   cout<<"enter the size of the matrix:"<<endl;
     while (cin >> n) {
    vector< vector<int> > m;
      cout<<"enter the elements"<<endl;
    for (int i = 0; i < n; i++) {
        m.push_back(vector<int>(n));
        for (int j = 0; j < n; j++)
            scanf("%d", &m[i][j]);
    }
      cout<<"the rotated matrix is:"<<endl;
      rotateMatrix(m);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << m[i][j] << ' ';
        cout << endl;
    }
   }
   return 0;
 }

How to run mvim (MacVim) from Terminal?

I don't think I'd to add anything to the path, did

brew install macvim

mvim -v

should then open macvim in the terminal, you can also go ahead and alias that

alias vim='mvim -v'

jwt check if token expired

// Pass in function expiration date to check token 
function checkToken(exp) {
    if (Date.now() <= exp * 1000) {
      console.log(true, 'token is not expired')
    } else { 
      console.log(false, 'token is expired') 
    }
  }

How to assert two list contain the same elements in Python?

Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:

L1 = [1,2,2,3]
L2 = [1,2,3,3]

You are likely better off sorting the two lists and comparing them:

def checkEqual(L1, L2):
    if sorted(L1) == sorted(L2):
        print "the two lists are the same"
        return True
    else:
        print "the two lists are not the same"
        return False

Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists

Fit website background image to screen size

You can do it like what I did with my website:

background-repeat: no-repeat;

background-size: cover;

Get top most UIViewController

Where did you put the code in?

I try your code in my demo, I found out, if you put the code in

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

will fail, because key window have been setting yet.

But I put your code in some view controller's

override func viewDidLoad() {

It just works.

how to make password textbox value visible when hover an icon

1 minute googling gave me this result. See the DEMO!

HTML

<form>
    <label for="username">Username:</label>
    <input id="username" name="username" type="text" placeholder="Username" />
    <label for="password">Password:</label>
    <input id="password" name="password" type="password" placeholder="Password" />
    <input id="submit" name="submit" type="submit" value="Login" />
</form>

jQuery

// ----- Setup: Add dummy text field for password and add toggle link to form; "offPage" class moves element off-screen
$('input[type=password]').each(function () {
    var el = $(this),
        elPH = el.attr("placeholder");
    el.addClass("offPage").after('<input class="passText" placeholder="' + elPH + '" type="text" />');
});
$('form').append('<small><a class="togglePassText" href="#">Toggle Password Visibility</a></small>');

// ----- keep password field and dummy text field in sync
$('input[type=password]').keyup(function () {
    var elText = $(this).val();
    $('.passText').val(elText);
});
$('.passText').keyup(function () {
    var elText = $(this).val();
    $('input[type=password]').val(elText);
});

// ----- Toggle link functionality - turn on/off "offPage" class on fields
$('a.togglePassText').click(function (e) {
    $('input[type=password], .passText').toggleClass("offPage");
    e.preventDefault(); // <-- prevent any default actions
});

CSS

.offPage {
    position: absolute;
    bottom: 100%;
    right: 100%;
}

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

Python regex to match dates

Instead of using regex, it is generally better to parse the string as a datetime.datetime object:

In [140]: datetime.datetime.strptime("11/12/98","%m/%d/%y")
Out[140]: datetime.datetime(1998, 11, 12, 0, 0)

In [141]: datetime.datetime.strptime("11/12/98","%d/%m/%y")
Out[141]: datetime.datetime(1998, 12, 11, 0, 0)

You could then access the day, month, and year (and hour, minutes, and seconds) as attributes of the datetime.datetime object:

In [143]: date.year
Out[143]: 1998

In [144]: date.month
Out[144]: 11

In [145]: date.day
Out[145]: 12

To test if a sequence of digits separated by forward-slashes represents a valid date, you could use a try..except block. Invalid dates will raise a ValueError:

In [159]: try:
   .....:     datetime.datetime.strptime("99/99/99","%m/%d/%y")
   .....: except ValueError as err:
   .....:     print(err)
   .....:     
   .....:     
time data '99/99/99' does not match format '%m/%d/%y'

If you need to search a longer string for a date, you could use regex to search for digits separated by forward-slashes:

In [146]: import re
In [152]: match = re.search(r'(\d+/\d+/\d+)','The date is 11/12/98')

In [153]: match.group(1)
Out[153]: '11/12/98'

Of course, invalid dates will also match:

In [154]: match = re.search(r'(\d+/\d+/\d+)','The date is 99/99/99')

In [155]: match.group(1)
Out[155]: '99/99/99'

To check that match.group(1) returns a valid date string, you could then parsing it using datetime.datetime.strptime as shown above.

React JSX: selecting "selected" on selected <select> option

Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.

class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};
  }

  handleChange = (event) =>
    this.setState({value: event.target.value});

  handleSubmit = (event) => {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite flavor:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
} 

How do I add an existing Solution to GitHub from Visual Studio 2013

This question has already been answered accurately by Richard210363.

However, I would like to point out that there is another way to do this, and to warn that this alternate approach should be avoided, as it causes problems.

As R0MANARMY stated in a comment to the original question, it is possible to create a repo from the existing solution folder using the git command line or even Git Gui. However, when you do this it adds all the files below that folder to the repo, including build output (bin/ obj/ folders) user options files (.suo, .csproj.user) and numerous other files that may be in your solution folder but that you don't want to include in your repo. One unwanted side effect of this is that after building locally, the build output will show up in your "changes" list.

When you add using "Select File | Add to Source Control" in Visual Studio, it intelligently includes the correct project and solution files, and leaves the other ones out. Also it automatically creates a .gitignore file that helps prevent these unwanted files from being added to the repo in the future.

If you have already created a repo that includes these unwanted files and then add the .gitignore file at a later time, the unwanted files will still remain part of the repo and will need to be removed manually... it's probably easier to delete the repo and start over again by creating the repo the correct way.

How can I show an image using the ImageView component in javafx and fxml?

You don't need an initializer, unless you're dynamically loading a different image each time. I think doing as much as possible in fxml is more organized. Here is an fxml file that will do what you need.

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

<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>

<AnchorPane
    xmlns:fx="http://javafx.co/fxml/1"
    xmlns="http://javafx.com/javafx/2.2"
    fx:controller="application.SampleController"
    prefHeight="316.0"
    prefWidth="321.0"
    >
    <children>
        <ImageView
                fx:id="imageView"
                fitHeight="150.0"
                fitWidth="200.0"
                layoutX="61.0"
                layoutY="83.0"
                pickOnBounds="true"
                preserveRatio="true"
            >
            <image>
                <Image
                    url="src/Box13.jpg"
                    backgroundLoading="true"
                    />
            </image>
        </ImageView>
    </children>
</AnchorPane>

Specifying the backgroundLoading property in the Image tag is optional, it defaults to false. It's best to set backgroundLoading true when it takes a moment or longer to load the image, that way a placeholder will be used until the image loads, and the program wont freeze while loading.

what is reverse() in Django

reverse() | Django documentation


Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

This will be rendered as:

<a href="/foo/">link which calls some_view</a>

Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

return HttpResponseRedirect('/foo/')

But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

Instead, you can say:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

jquery dialog save cancel button styling

Here is how to add custom classes in jQuery UI Dialog (Version 1.8+):

$('#foo').dialog({
    'buttons' : {
        'cancel' : {
            priority: 'secondary', class: 'foo bar baz', click: function() {
                ...
            },
        },
    }
}); 

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

In Tkinter is there any way to make a widget not visible?

import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
    lb.config(visible=visible)
visiblelabel(x, False)  # Hide
visiblelabel(x, True)  # Show

P.S. config can change any attribute:

x.config(text='Hello')  # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold'))  # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white')  # Background: red, Foreground: white

It's a bypass of StringVar, IntVar etc.

Permission denied for relation

This frequently happens when you create a table as user postgres and then try to access it as an ordinary user. In this case it is best to log in as the postgres user and change the ownership of the table with the command:

alter table <TABLE> owner to <USER>;

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Change

CREATE DEFINER =  `root`@`localhost` FUNCTION  `fnc_calcWalkedDistance` (

By

FUNCTION  `fnc_calcWalkedDistance` (

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

Was updating an old website using nuget (including .Net update and MVC update).

I deleted the System.Net.HTTP reference in VS2017 (it was to version 2.0.0.0) and re-added the reference, which then showed 4.2.0.0.

I then updated a ton of 'packages' using nuget and got the error message, then noticed something had reset the reference to 2.0.0.0, so I removed and re-added again and it works fine... bizarre.

Get file path of image on Android

Posting to Twitter needs the image's actual path on the device to be sent in the request to post. I was finding it mighty difficult to get the actual path and more often than not I would get the wrong path.

To counter that, once you have a Bitmap, I use that to get the URI from using the getImageUri(). Subsequently, I use the tempUri Uri instance to get the actual path as it is on the device.

This is production code and naturally tested. ;-)

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setImageBitmap(photo);
        knop.setVisibility(Button.VISIBLE);


        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // CALL THIS METHOD TO GET THE ACTUAL PATH
        File finalFile = new File(getRealPathFromURI(tempUri));

        System.out.println(mImageCaptureUri);
    }  
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(idx); 
}

Java: How to read a text file

Java 1.5 introduced the Scanner class for handling input from file and streams.

It is used for getting integers from a file and would look something like this:

List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
   integers.add(fileScanner.nextInt());
}

Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

How to save as a new file and keep working on the original one in Vim?

After save new file press

Ctrl-6

This is shortcut to alternate file

TypeError: $.ajax(...) is not a function?

This is too late for an answer but this response may be helpful for future readers.

I would like to share a scenario where, say there are multiple html files(one base html and multiple sub-HTMLs) and $.ajax is being used in one of the sub-HTMLs.

Suppose in the sub-HTML, js is included via URL "https://code.jquery.com/jquery-3.5.0.js" and in the base/parent HTML, via URL -"https://code.jquery.com/jquery-3.1.1.slim.min.js", then the slim version of JS will be used across all pages which use this sub-HTML as well as the base HTML mentioned above.

This is especially true in case of using bootstrap framework which loads js using "https://code.jquery.com/jquery-3.1.1.slim.min.js".

So to resolve the problem, need to ensure that in all pages, js is included via URL "https://code.jquery.com/jquery-3.5.0.js" or whatever is the latest URL containing all JQuery libraries.

Thanks to Lily H. for pointing me towards this answer.

How to clamp an integer to some range?

Whatever happened to my beloved readable Python language? :-)

Seriously, just make it a function:

def addInRange(val, add, minval, maxval):
    newval = val + add
    if newval < minval: return minval
    if newval > maxval: return maxval
    return newval

then just call it with something like:

val = addInRange(val, 7, 0, 42)

Or a simpler, more flexible, solution where you do the calculation yourself:

def restrict(val, minval, maxval):
    if val < minval: return minval
    if val > maxval: return maxval
    return val

x = restrict(x+10, 0, 42)

If you wanted to, you could even make the min/max a list so it looks more "mathematically pure":

x = restrict(val+7, [0, 42])

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

How to open VMDK File of the Google-Chrome-OS bundle 2012?

VMDK is a virtual disk file, what you need is a VMX file. Cruise on over to EasyVMX and have it create one for you, then just replace the VMDK file it gives you with the Cnrome OS one.

EasyVMX is good since VMWare Player has no VM creation stuff in it (at least in version 2, not sure about 3). You had to use one of VMWare's other products to do that.

JavaScript - Use variable in string match

for me anyways, it helps to see it used. just made this using the "re" example:

var analyte_data = 'sample-'+sample_id;
var storage_keys = $.jStorage.index();
var re = new RegExp( analyte_data,'g');  
for(i=0;i<storage_keys.length;i++) { 
    if(storage_keys[i].match(re)) {
        console.log(storage_keys[i]);
        var partnum = storage_keys[i].split('-')[2];
    }
}

How to check which version of Keras is installed?

Python library authors put the version number in <module>.__version__. You can print it by running this on the command line:

python -c 'import keras; print(keras.__version__)'

If it's Windows terminal, enclose snippet with double-quotes like below

python -c "import keras; print(keras.__version__)"

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

This is how I do it in FreeBSD:

#!/usr/local/bin/bash
for i in $(ipcs -a | grep "^s" | awk '{ print $2 }');
do
        echo "ipcrm -s $i"
        ipcrm -s $i
done

Read lines from a text file but skip the first two lines

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum

''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr

Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)
Loop

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

"Parser Error Message: Could not load type" in Global.asax

I spent multiple days on this issue. I finally got it resolved with the following combination of suggestions from this post.

  1. Change platform target to Any CPU. I did not have this configuration currently, so I had to go to the Configuration Manager and add it. I was specifically compiling for x64. This alone did not resolve the error.
  2. Change the output path to bin\ instead of bin\x64\Debug. I had tried this several times already before I changed the platform target. It never made a difference other than getting an error that it failed to load the assembly because of an invalid format.

To be clear, I had to do both of these before it started working. I had tried them individually multiple times but it never fixed it until I did both.

If I change either one of these settings back to the original, I get the same error again, despite having run Clean Solution, and manually deleting everything in the bin directory.

How to add a second x-axis in matplotlib

If You want your upper axis to be a function of the lower axis tick-values you can do as below. Please note: sometimes get_xticks() will have a ticks outside of the visible range, which you have to allow for when converting.

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

ax1 = fig.add_subplot(111)

ax1.plot(range(5), range(5))

ax1.grid(True)

ax2 = ax1.twiny()
ax2.set_xticks( ax1.get_xticks() )
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels([x * 2 for x in ax1.get_xticks()])

title = ax1.set_title("Upper x-axis ticks are lower x-axis ticks doubled!")
title.set_y(1.1)
fig.subplots_adjust(top=0.85)

fig.savefig("1.png")

Gives:

enter image description here

Can I add color to bootstrap icons only using CSS?

Quick and dirty work around which did it for me, not actually coloring the icon, but surrounding it with a label or badge in the color you want;

<span class="label-important label"><i class="icon-remove icon-white"></i></span>
<span class="label-success label"><i class="icon-ok icon-white"></i></span>

Convert pandas data frame to series

You can also use stack()

df= DataFrame([list(range(5))], columns = [“a{}”.format(I) for I in range(5)])

After u run df, then run:

df.stack()

You obtain your dataframe in series

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to read the post request parameters using JavaScript

<head><script>var xxx = ${params.xxx}</script></head>

Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

How to initialize an array in Kotlin with values?

You can simply use the existing standard library methods as shown here:

val numbers = intArrayOf(10, 20, 30, 40, 50)

It might make sense to use a special constructor though:

val numbers2 = IntArray(5) { (it + 1) * 10 }

You pass a size and a lambda that describes how to init the values. Here's the documentation:

/**
 * Creates a new array of the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> Int)

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I had a similar issue, but I was not using ASP.Net 1.1 nor updating a control via javascript. My problem only happened on Firefox and not on IE (!).

I added options to a DropDownList on the PreRender event like this:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string[] opcoes = HF.value.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

My "HF" (hiddenfield) had the options separated by the newline, like this:

HF.value = "option 1\n\roption 2\n\roption 3";

The problem was that the HTML page was broken (I mean had newlines) on the options of the "select" that represented the DropDown.

So I resolved my my problem adding one line:

DropDownList DD = (DropDownList)F.FindControl("DDlista");
HiddenField HF = (HiddenField)F.FindControl("HFlista");
string dados = HF.Value.Replace("\r", "");
string[] opcoes = dados.Split('\n');
foreach (string opcao in opcoes) DD.Items.Add(opcao);

Hope this help someone.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

run postgres -D /usr/local/var/postgres and you should see something like:

 FATAL:  lock file "postmaster.pid" already exists
 HINT:   Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"?

Then run kill -9 PID in HINT

And you should be good to go.

Understanding generators in Python

A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.

>>> def myGenerator():
...     yield 'These'
...     yield 'words'
...     yield 'come'
...     yield 'one'
...     yield 'at'
...     yield 'a'
...     yield 'time'

>>> myGeneratorInstance = myGenerator()
>>> next(myGeneratorInstance)
These
>>> next(myGeneratorInstance)
words

and so on. The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem. Generators, just like lists, are iterable, so they can be used in the same ways:

>>> for word in myGeneratorInstance:
...     print word
These
words
come
one
at 
a 
time

Note that generators provide another way to deal with infinity, for example

>>> from time import gmtime, strftime
>>> def myGen():
...     while True:
...         yield strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())    
>>> myGeneratorInstance = myGen()
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:17:15 +0000
>>> next(myGeneratorInstance)
Thu, 28 Jun 2001 14:18:02 +0000   

The generator encapsulates an infinite loop, but this isn't a problem because you only get each answer every time you ask for it.

PostgreSQL: Drop PostgreSQL database through command line

This worked for me:

select pg_terminate_backend(pid) from pg_stat_activity where datname='YourDatabase';

for postgresql earlier than 9.2 replace pid with procpid

DROP DATABASE "YourDatabase";

http://blog.gahooa.com/2010/11/03/how-to-force-drop-a-postgresql-database-by-killing-off-connection-processes/

Is there a way to @Autowire a bean that requires constructor arguments?

Well, from time to time I run into the same question. As far as I know, one cannot do that when one wants to add dynamic parameters to the constructor. However, the factory pattern may help.

public interface MyBean {
    // here be my fancy stuff
}

public interface MyBeanFactory {
    public MyBean getMyBean(/* bean parameters */);
}

@Component
public class MyBeanFactoryImpl implements MyBeanFactory {
    @Autowired
    WhateverIWantToInject somethingInjected;

    public MyBean getMyBean(/* params */) {
        return new MyBeanImpl(/* params */);
    }

    private class MyBeanImpl implements MyBean {
        public MyBeanImpl(/* params */) {
            // let's do whatever one has to
        }
    }
}

@Component
public class MyConsumerClass {
    @Autowired
    private MyBeanFactory beanFactory;

    public void myMethod() {
        // here one has to prepare the parameters
        MyBean bean = beanFactory.getMyBean(/* params */);
    }
}

Now, MyBean is not a spring bean per se, but it is close enough. Dependency Injection works, although I inject the factory and not the bean itself - one has to inject a new factory on top of his own new MyBean implementation if one wants to replace it.

Further, MyBean has access to other beans - because it may have access to the factory's autowired stuff.

And one might apparently want to add some logic to the getMyBean function, which is extra effort I allow, but unfortunately I have no better solution. Since the problem usually is that the dynamic parameters come from an external source, like a database, or user interaction, therefore I must instantiate that bean only in mid-run, only when that info is readily available, so the Factory should be quite adequate.

MongoDB not equal to

Use $ne -- $not should be followed by the standard operator:

An examples for $ne, which stands for not equal:

use test
switched to db test
db.test.insert({author : 'me', post: ""})
db.test.insert({author : 'you', post: "how to query"})
db.test.find({'post': {$ne : ""}})
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" }

And now $not, which takes in predicate ($ne) and negates it ($not):

db.test.find({'post': {$not: {$ne : ""}}})
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" }

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

How to define Singleton in TypeScript

This is probably the longest process to make a singleton in typescript, but in larger applications is the one that has worked better for me.

First you need a Singleton class in, let's say, "./utils/Singleton.ts":

module utils {
    export class Singleton {
        private _initialized: boolean;

        private _setSingleton(): void {
            if (this._initialized) throw Error('Singleton is already initialized.');
            this._initialized = true;
        }

        get setSingleton() { return this._setSingleton; }
    }
}

Now imagine you need a Router singleton "./navigation/Router.ts":

/// <reference path="../utils/Singleton.ts" />

module navigation {
    class RouterClass extends utils.Singleton {
        // NOTICE RouterClass extends from utils.Singleton
        // and that it isn't exportable.

        private _init(): void {
            // This method will be your "construtor" now,
            // to avoid double initialization, don't forget
            // the parent class setSingleton method!.
            this.setSingleton();

            // Initialization stuff.
        }

        // Expose _init method.
        get init { return this.init; }
    }

    // THIS IS IT!! Export a new RouterClass, that no
    // one can instantiate ever again!.
    export var Router: RouterClass = new RouterClass();
}

Nice!, now initialize or import wherever you need:

/// <reference path="./navigation/Router.ts" />

import router = navigation.Router;

router.init();
router.init(); // Throws error!.

The nice thing about doing singletons this way is that you still use all the beauty of typescript classes, it gives you nice intellisense, the singleton logic keeps someway separated and it's easy to remove if needed.

How to align a <div> to the middle (horizontally/width) of the page

Use justify-content and align-items to horizontally and vertically align a div

https://developer.mozilla.org/de/docs/Web/CSS/justify-content https://developer.mozilla.org/en/docs/Web/CSS/align-items

_x000D_
_x000D_
html,_x000D_
body,_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
.container {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
.mydiv {_x000D_
  width: 80px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="mydiv">h & v aligned</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

NodeJs : TypeError: require(...) is not a function

For me, this was an issue with cyclic dependencies.

IOW, module A required module B, and module B required module A.

So in module B, require('./A') is an empty object rather than a function.

How to deal with cyclic dependencies in Node.js

Executable directory where application is running from?

You can write the following:

Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")

Best JavaScript compressor

KJScompress

http://opensource.seznam.cz/KJScompress/index.html

Kjscompress/csskompress is set of two applications (kjscompress a csscompress) to remove non-significant whitespaces and comments from files containing JavaScript and CSS. Both are command-line applications for GNU/Linux operating system.

static linking only some libraries

From the manpage of ld (this does not work with gcc), referring to the --static option:

You may use this option multiple times on the command line: it affects library searching for -l options which follow it.

One solution is to put your dynamic dependencies before the --static option on the command line.

Another possibility is to not use --static, but instead provide the full filename/path of the static object file (i.e. not using -l option) for statically linking in of a specific library. Example:

# echo "int main() {}" > test.cpp
# c++ test.cpp /usr/lib/libX11.a
# ldd a.out
linux-vdso.so.1 =>  (0x00007fff385cc000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f9a5b233000)
libm.so.6 => /lib/libm.so.6 (0x00007f9a5afb0000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f9a5ad99000)
libc.so.6 => /lib/libc.so.6 (0x00007f9a5aa46000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9a5b53f000)

As you can see in the example, libX11 is not in the list of dynamically-linked libraries, as it was linked statically.

Beware: An .so file is always linked dynamically, even when specified with a full filename/path.

How to get the excel file name / path in VBA

If you mean VBA, then you can use FullName, for example:

strFileFullName = ThisWorkbook.FullName

(updated as considered by the comments: the former used ActiveWorkbook.FullName could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook could be the correct choice, if it is guaranteed to be active at execution time.)

bootstrap 3 navbar collapse button not working

In case it might help someone, I had a similar issue after adding Bootstrap 3 to my MVC 4 project. It turned out my problem was that I was referring to bootstrap-min.js instead of bootstrap.js in my BundleConfig.cs.

Didn't work:

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                            "~/Scripts/bootstrap-min.js"));

Worked:

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                        "~/Scripts/bootstrap.js"));

Determine if running on a rooted device

Using C++ with the ndk is the best approach to detect root even if the user is using applications that hide his root such as RootCloak. I tested this code with RootCloak and I was able to detect the root even if the user is trying to hide it. So your cpp file would like:

#include <jni.h>
#include <string>


/**
 *
 * function that checks for the su binary files and operates even if 
 * root cloak is installed
 * @return integer 1: device is rooted, 0: device is not 
 *rooted
*/
extern "C"
JNIEXPORT int JNICALL


Java_com_example_user_root_1native_rootFunction(JNIEnv *env,jobject thiz){
const char *paths[] ={"/system/app/Superuser.apk", "/sbin/su", "/system/bin/su",
                      "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
                      "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};

int counter =0;
while (counter<9){
    if(FILE *file = fopen(paths[counter],"r")){
        fclose(file);
        return 1;
    }
    counter++;
}
return 0;
}

And you will call the function from your java code as follows

public class Root_detect {



   /**
    *
    * function that calls a native function to check if the device is 
    *rooted or not
    * @return boolean: true if the device is rooted, false if the 
    *device is not rooted
   */
   public boolean check_rooted(){

        int checker = rootFunction();

        if(checker==1){
           return true;
        }else {
           return false;
        }
   }
   static {
    System.loadLibrary("cpp-root-lib");//name of your cpp file
   }

   public native int rootFunction();
}

List submodules in a Git repository

This worked for me:

git ls-files --stage | grep ^160000

It is based on this great article: Understanding Git Submodules

It must read grep ^160000.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

Detect click outside Angular component

ginalx's answer should be set as the default one imo: this method allows for many optimizations.

The problem

Say that we have a list of items and on every item we want to include a menu that needs to be toggled. We include a toggle on a button that listens for a click event on itself (click)="toggle()", but we also want to toggle the menu whenever the user clicks outside of it. If the list of items grows and we attach a @HostListener('document:click') on every menu, then every menu loaded within the item will start listening for the click on the entire document, even when the menu is toggled off. Besides the obvious performance issues, this is unnecessary.

You can, for example, subscribe whenever the popup gets toggled via a click and start listening for "outside clicks" only then.


isActive: boolean = false;

// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;

private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;


constructor(
 ...
 private _utilitiesService: UtilitiesService,
 private _elementRef: ElementRef,
){
 ...
 this._toggleMenuSubject$ = new BehaviorSubject(false);
 this._toggleMenu$ = this._toggleMenuSubject$.asObservable();

}

ngOnInit() {
 this._toggleMenuSub = this._toggleMenu$.pipe(
      tap(isActive => {
        logger.debug('Label Menu is active', isActive)
        this.isActive = isActive;

        // subscribe to the click event only if the menu is Active
        // otherwise unsubscribe and save memory
        if(isActive === true){
          this._clickSub = this._utilitiesService.documentClickedTarget
           .subscribe(target => this._documentClickListener(target));
        }else if(isActive === false && this._clickSub !== null){
          this._clickSub.unsubscribe();
        }

      }),
      // other observable logic
      ...
      ).subscribe();
}

toggle() {
    this._toggleMenuSubject$.next(!this.isActive);
}

private _documentClickListener(targetElement: HTMLElement): void {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this._toggleMenuSubject$.next(false);
    }    
 }

ngOnDestroy(){
 this._toggleMenuSub.unsubscribe();
}

And, in *.component.html:


<button (click)="toggle()">Toggle the menu</button>

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)

eg -

~/myproject/mygitrepo/app/$ git diff app/TestFile.txt

should have been

~/myproject/mygitrepo/app/$ git diff TestFile.txt

adb connection over tcp not working now

Thanks to sud007 for this answer. In my case, I only need this part of the solution:

In CMD/Terminal:

$ adb kill-server

$ adb tcpip 5555
restarting in TCP mode port: 5555

$ adb connect 192.168.XXX.XXX

This bug brings more errors than unable to connect to 192.168.XXX.XXX:5555: Connection refused. In my case, I could connect to the device, but when you try to run the app. AndroidStudio stay in Installing APK forever. In this case, I needed to restart the phone too.

Resolving a Git conflict with binary files

my case seems like a bug.... using git 2.21.0

I did a pull... it complained about binary files:

warning: Cannot merge binary files: <path>
Auto-merging <path>
CONFLICT (content): Merge conflict in <path>
Automatic merge failed; fix conflicts and then commit the result.

And then nothing in any of the answers here resulted in any output that made any sense.

If I look at which file I have now... it's the one I edited. If I do either:

git checkout --theirs -- <path>
git checkout --ours -- <path>

I get output:

Updated 0 paths from the index

and I still have my version of the file. If I rm and then checkout, It'll say 1 instead, but it still gives me my version of the file.

git mergetool says

No files need merging

and git status says

    All conflicts fixed but you are still merging.
    (use "git commit" to conclude merge)

One option is to undo the commit... but I was unlucky and I had many commits, and this bad one was the first. I don't want to waste time repeating that.

so to solve this madness:

I just ran

git commit

which loses the remote version, and probably wastes some space storing an extra binary file... then

git checkout <commit where the remote version exists> <path>

which gives me back the remote version

then edited the file again...and then commit and push, which again probably means wasting space with another copy of the binary file.

Rollback transaction after @Test

I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:

My test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest 

Context xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driverClassName}" />
   <property name="url" value="${jdbc.url}" />
   <property name="username" value="${jdbc.username}" />
   <property name="password" value="${jdbc.password}" />
</bean>

I still had the problem that, the database was not being cleaned up automatically.

Issue was resolved when I added following property to BasicDataSource

<property name="defaultAutoCommit" value="false" />

Hope it helps.

Convert Json Array to normal Java list

You can use a String[] instead of an ArrayList<String>:

Hope it helps!

   private String[] getStringArray(JSONArray jsonArray) throws JSONException {
            if (jsonArray != null) {
                String[] stringsArray = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    stringsArray[i] = jsonArray.getString(i);
                }
                return stringsArray;
            } else
                return null;
        }

How can I get the MAC and the IP address of a connected client in PHP?

Perhaps getting the Mac address is not the best approach for verifying a client's machine over the internet. Consider using a token instead which is stored in the client's browser by an administrator's login.

Therefore the client can only have this token if the administrator grants it to them through their browser. If the token is not present or valid then the client's machine is invalid.

How to install .MSI using PowerShell

Why get so fancy about it? Just invoke the .msi file:

& <path>\filename.msi

or

Start-Process <path>\filename.msi

Edit: Full list of Start-Process parameters

https://ss64.com/ps/start-process.html

How can I restart a Java application?

If you realy need to restart your app, you could write a separate app the start it...

This page provides many different examples for different scenarios:

http://www.rgagnon.com/javadetails/java-0014.html

How do I expand the output display to see more columns of a pandas DataFrame?

Try this:

pd.set_option('display.expand_frame_repr', False)

From the documentation:

display.expand_frame_repr : boolean

Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if it’s width exceeds display.width. [default: True] [currently: True]

See: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html

How to remove all namespaces from XML with C#?

After much searching for a solution to this very issue, this particular page seemed to have the most beef...however, nothing quite fit exactly, so I took the old-fashioned way and just parsed the stuff out I wanted out. Hope this helps someone. (Note: this also removes the SOAP or similar envelope stuff.)

        public static string RemoveNamespaces(string psXml)
    {
        //
        // parse through the passed XML, and remove any and all namespace references...also
        // removes soap envelope/header(s)/body, or any other references via ":" entities,
        // leaving all data intact
        //
        string xsXml = "", xsCurrQtChr = "";
        int xiPos = 0, xiLastPos = psXml.Length - 1;
        bool xbInNode = false;

        while (xiPos <= xiLastPos)
        {
            string xsCurrChr = psXml.Substring(xiPos, 1);
            xiPos++;
            if (xbInNode)
            {
                if (xsCurrChr == ":")
                {
                    // soap envelope or body (or some such)
                    // we'll strip these node wrappers completely
                    // need to first strip the beginning of it off  (i.e. "<soap" or "<s")
                    int xi = xsXml.Length;
                    string xsChr = "";
                    do
                    {
                        xi--;
                        xsChr = xsXml.Substring(xi, 1);
                        xsXml = xsXml.Substring(0, xi);
                    } while (xsChr != "<");

                    // next, find end of node
                    string xsQt = "";
                    do
                    {
                        xiPos++;
                        if (xiPos <= xiLastPos)
                        {
                            xsChr = psXml.Substring(xiPos, 1);
                            if (xsQt.Length == 0)
                            {
                                if (xsChr == "'" || xsChr == "\"")
                                {
                                    xsQt = xsChr;
                                }
                            }
                            else
                            {
                                if (xsChr == xsQt)
                                {
                                    xsQt = "";  // end of quote
                                }
                                else
                                {
                                    if (xsChr == ">") xsChr = "x";      // stay in loop...this is not end of node
                                }
                            }
                        }
                    } while (xsChr != ">" && xiPos <= xiLastPos);
                    xiPos++;            // skip over closing ">"
                    xbInNode = false;
                }
                else
                {
                    if (xsCurrChr == ">")
                    {
                        xbInNode = false;
                        xsXml += xsCurrChr;
                    }
                    else
                    {
                        if (xsCurrChr == " " || xsCurrChr == "\t")
                        {
                            // potential namespace...let's check...next character must be "/"
                            // or more white space, and if not, skip until we find such
                            string xsChr = "";
                            int xiOrgLen = xsXml.Length;
                            xsXml += xsCurrChr;
                            do
                            {
                                if (xiPos <= xiLastPos)
                                {
                                    xsChr = psXml.Substring(xiPos, 1);
                                    xiPos++;
                                    if (xsChr == " " || xsChr == "\r" || xsChr == "\n" || xsChr == "\t")
                                    {
                                        // carry on..white space
                                        xsXml += xsChr;
                                    }
                                    else
                                    {
                                        if (xsChr == "/" || xsChr == ">")
                                        {
                                            xsXml += xsChr;
                                        }
                                        else
                                        {
                                            // namespace! - get rid of it
                                            xsXml = xsXml.Substring(0, xiOrgLen - 0);       // first, truncate any added whitespace
                                            // next, peek forward until we find "/" or ">"
                                            string xsQt = "";
                                            do
                                            {
                                                if (xiPos <= xiLastPos)
                                                {
                                                    xsChr = psXml.Substring(xiPos, 1);
                                                    xiPos++;
                                                    if (xsQt.Length > 0)
                                                    {
                                                        if (xsChr == xsQt) xsQt = ""; else xsChr = "x";
                                                    }
                                                    else
                                                    {
                                                        if (xsChr == "'" || xsChr == "\"") xsQt = xsChr;
                                                    }
                                                }
                                            } while (xsChr != ">" && xsChr != "/" && xiPos <= xiLastPos);
                                            if (xsChr == ">" || xsChr == "/") xsXml += xsChr;
                                            xbInNode = false;
                                        }
                                    }
                                }
                            } while (xsChr != ">" && xsChr != "/" && xiPos <= xiLastPos);
                        }
                        else
                        {
                            xsXml += xsCurrChr;
                        }
                    }
                }
            }
            else
            {
                //
                // if not currently inside a node, then we are in a value (or about to enter a new node)
                //
                xsXml += xsCurrChr;
                if (xsCurrQtChr.Length == 0)
                {
                    if (xsCurrChr == "<")
                    {
                        xbInNode = true;
                    }
                }
                else
                {
                    //
                    // currently inside a quoted string
                    //
                    if (xsCurrQtChr == xsCurrChr)
                    {
                        // finishing quoted string
                        xsCurrQtChr = "";
                    }
                }
            }
        }

        return (xsXml);
    }

How can I pass an argument to a PowerShell script?

# ENTRY POINT MAIN()
Param(
    [Parameter(Mandatory=$True)]
    [String] $site,
    [Parameter(Mandatory=$True)]
    [String] $application,
    [Parameter(Mandatory=$True)]
    [String] $dir,
    [Parameter(Mandatory=$True)]
    [String] $applicationPool
)

# Create Web IIS Application
function ValidateWebSite ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return 1
    }
}

# Get full path from IIS WebSite
function GetWebSiteDir ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return $iisWebSite.PhysicalPath
    }
}

# Create Directory
function CreateDirectory([string]$fullPath)
{
    $existEvaluation = Test-Path $fullPath -PathType Any
    if($existEvaluation -eq $false)
    {
        new-item $fullPath -itemtype directory
    }
    return 1
}

function CreateApplicationWeb
{
    Param(
        [String] $WebSite,
        [String] $WebSitePath,
        [String] $application,
        [String] $applicationPath,
        [String] $applicationPool
        )
    $fullDir = "$($WebSitePath)\$($applicationPath)"
    CreateDirectory($fullDir)
    New-WebApplication -Site $WebSite -Name $application -PhysicalPath $fullDir -ApplicationPool $applicationPool -Force
}

$fullWebSiteDir = GetWebSiteDir($Site)f($null -ne $fullWebSiteDir)
{
    CreateApplicationWeb -WebSite $Site -WebSitePath $fullWebSiteDir -application $application  -applicationPath $dir -applicationPool $applicationPool
}

Android Room - simple select query - Cannot access database on the main thread

Update: I also got this message when I was trying to build a query using @RawQuery and SupportSQLiteQuery inside the DAO.

@Transaction
public LiveData<List<MyEntity>> getList(MySettings mySettings) {
    //return getMyList(); -->this is ok

    return getMyList(new SimpleSQLiteQuery("select * from mytable")); --> this is an error

Solution: build the query inside the ViewModel and pass it to the DAO.

public MyViewModel(Application application) {
...
        list = Transformations.switchMap(searchParams, params -> {

            StringBuilder sql;
            sql = new StringBuilder("select  ... ");

            return appDatabase.rawDao().getList(new SimpleSQLiteQuery(sql.toString()));

        });
    }

Or...

You should not access the database directly on the main thread, for example:

 public void add(MyEntity item) {
     appDatabase.myDao().add(item); 
 }

You should use AsyncTask for update, add, and delete operations.

Example:

public class MyViewModel extends AndroidViewModel {

    private LiveData<List<MyEntity>> list;

    private AppDatabase appDatabase;

    public MyViewModel(Application application) {
        super(application);

        appDatabase = AppDatabase.getDatabase(this.getApplication());
        list = appDatabase.myDao().getItems();
    }

    public LiveData<List<MyEntity>> getItems() {
        return list;
    }

    public void delete(Obj item) {
        new deleteAsyncTask(appDatabase).execute(item);
    }

    private static class deleteAsyncTask extends AsyncTask<MyEntity, Void, Void> {

        private AppDatabase db;

        deleteAsyncTask(AppDatabase appDatabase) {
            db = appDatabase;
        }

        @Override
        protected Void doInBackground(final MyEntity... params) {
            db.myDao().delete((params[0]));
            return null;
        }
    }

    public void add(final MyEntity item) {
        new addAsyncTask(appDatabase).execute(item);
    }

    private static class addAsyncTask extends AsyncTask<MyEntity, Void, Void> {

        private AppDatabase db;

        addAsyncTask(AppDatabase appDatabase) {
            db = appDatabase;
        }

        @Override
        protected Void doInBackground(final MyEntity... params) {
            db.myDao().add((params[0]));
            return null;
        }

    }
}

If you use LiveData for select operations, you don't need AsyncTask.

Spring Boot Multiple Datasource

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

java.lang.ClassNotFoundException: HttpServletRequest

1 Right click on "your project" in Eclipse EE Project Explorer 2 Click on Properties 3 Click on Targeted Runtimes 4 Checkbox of the version you are currently working with 5 Apply and close

This should do the trick.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

This solved my problem when I had to deal with HTML page with embedded JavaScript

WebElement empSalary =  driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I have the same problem. I ran docker system prune -a --volumes, docker network prune, but neither helped me.

I use a VPN, I turned off the VPN and, after it docker started normal and was able to create a network. After that, you can enable VPN again.

Regular expression for letters, numbers and - _

/^[\w-_.]*$/

What is means By:

  • ^ Start of string

  • [......] Match characters inside

  • \w Any word character so 0-9 a-z A-Z

  • -_. Matched by charecter - and _ and .

  • Zero or more of pattern or unlimited $ End of string If you want to limit the amount of characters:

    /^[\w-_.]{0,5}$/
    

    {0,5} Means 0-5 Numbers & characters

How do I change an HTML selected option using JavaScript?

An array Index will start from 0. If you want value=11 (Person1), you will get it with position getElementsByTagName('option')[10].selected.

Storing a file in a database as opposed to the file system?

In my own experience, it is always better to store files as files. The reason is that the filesystem is optimised for file storeage, whereas a database is not. Of course, there are some exceptions (e.g. the much heralded next-gen MS filesystem is supposed to be built on top of SQL server), but in general that's my rule.

Check if input is integer type in C

I found a way to check whether the input given is an integer or not using atoi() function .

Read the input as a string, and use atoi() function to convert the string in to an integer.

atoi() function returns the integer number if the input string contains integer, else it will return 0. You can check the return value of the atoi() function to know whether the input given is an integer or not.

There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.

Note : It works only for non-zero numbers.

#include<stdio.h>
#include<stdlib.h>

int main() {
    char *string;
    int number;

    printf("Enter a number :");
    string = scanf("%s", string);

    number = atoi(string);

    if(number != 0)
        printf("The number is %d\n", number);
    else
        printf("Not a number !!!\n");
    return 0;
}

Meaning of tilde in Linux bash (not home directory)

Those are the home directories of the users. Try cd ~(your username), for example.

How to prevent http file caching in Apache httpd (MAMP)

Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control: private, x-gzip-ok="" > to prevent caching of ads by proxies and clients.

From http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.

Make function wait until element exists

Just use setTimeOut with recursion:

waitUntilElementIsPresent(callback: () => void): void {
    if (!this.methodToCheckIfElementIsPresent()) {
        setTimeout(() => this.waitUntilElementIsPresent(callback), 500);
        return;
    }
    callback();
}

Usage:

this.waitUntilElementIsPresent(() => console.log('Element is present!'));

You can limit amount of attempts, so an error will be thrown when the element is not present after the limit:

waitUntilElementIsPresent(callback: () => void, attempt: number = 0): void {
    const maxAttempts = 10;
    if (!this.methodToCheckIfElementIsPresent()) {
        attempt++;
        setTimeout(() => this.waitUntilElementIsPresent(callback, attempt), 500);
        return;
    } else if (attempt >= maxAttempts) {
        return;
    }
    callback();
}

Why is a ConcurrentModificationException thrown and how to debug it

Note that the selected answer cannot be applied to your context directly before some modification, if you are trying to remove some entries from the map while iterating the map just like me.

I just give my working example here for newbies to save their time:

HashMap<Character,Integer> map=new HashMap();
//adding some entries to the map
...
int threshold;
//initialize the threshold
...
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
    Map.Entry<Character,Integer> item=(Map.Entry<Character,Integer>)it.next();
    //it.remove() will delete the item from the map
    if((Integer)item.getValue()<threshold){
        it.remove();
    }

TypeScript getting error TS2304: cannot find name ' require'

For TypeScript 2.x, there are now two steps:

  1. Install a package that defines require. For example:

    npm install @types/node --save-dev
    
  2. Tell TypeScript to include it globally in tsconfig.json:

    {
        "compilerOptions": {
            "types": ["node"]
        }
    }
    

The second step is only important if you need access to globally available functions such as require. For most packages, you should just use the import package from 'package' pattern. There's no need to include every package in the tsconfig.json types array above.

round() for float in C++

Based on Kalaxy's response, the following is a templated solution that rounds any floating point number to the nearest integer type based on natural rounding. It also throws an error in debug mode if the value is out of range of the integer type, thereby serving roughly as a viable library function.

    // round a floating point number to the nearest integer
    template <typename Arg>
    int Round(Arg arg)
    {
#ifndef NDEBUG
        // check that the argument can be rounded given the return type:
        if (
            (Arg)std::numeric_limits<int>::max() < arg + (Arg) 0.5) ||
            (Arg)std::numeric_limits<int>::lowest() > arg - (Arg) 0.5)
            )
        {
            throw std::overflow_error("out of bounds");
        }
#endif

        return (arg > (Arg) 0.0) ? (int)(r + (Arg) 0.5) : (int)(r - (Arg) 0.5);
    }

Ping all addresses in network, windows

I know this is a late response, but a neat way of doing this is to ping the broadcast address which populates your local arp cache.

This can then be shown by running arp -a which will list all the addresses in you local arp table.

ping 192.168.1.255
arp -a

Hopefully this is a nice neat option that people can use.

How to build query string with Javascript

Might be a bit redundant but the cleanest way i found which builds on some of the answers here:

const params: {
   key1: 'value1',
   key2: 'value2',
   key3: 'value3',
}

const esc = encodeURIComponent;
const query = Object.keys(params)
  .map(k => esc(k) + '=' + esc(params[k]))
  .join('&');

return fetch('my-url', {
  method: 'POST',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: query,
})

Source

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

LINQ to Entities how to update a record

In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

change the package of classes, your files are probably in the wrong package, happened to me when I copied the code from a friend, it was the default package and mine was another, hence the netbeans could not compile because of it.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

Make element fixed on scroll

You can do that with some easy jQuery:

http://jsfiddle.net/jpXjH/6/

var elementPosition = $('#navigation').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});

Converting String to "Character" array in Java

chaining is always best :D

String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());

sqldeveloper error message: Network adapter could not establish the connection error

This worked for me :

Try deleting old listener using NETCA and then add new listener with same name.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

You won't be able to restore from 2012 to 2008. You will be able to use a tool like red-gate SQL compare to copy the schema etc (provided nothing 2012 specific is used). If you have data to copy across too, you can use their Data Compare tool, and I think you get a 14 day free trial.

PHP ini file_get_contents external url

Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

echo get_content('http://example.com');

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

When you install Entity Framework 6 through Nuget. EntityFramework.SqlServer sometime miss for another executable. Simply add the Nuget package to that project.

Sometimes above does not work for Test Project

To solve this issue in Test Project just place this Method inside Test Project:

public void FixEfProviderServicesProblem()
{
    var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
}

This method is never been called, but as my observations, the compiler will remove all "unnecessary" assemblies and without using the EntityFramework.SqlServer stuff the test fails.

Evenly distributing n points on a sphere

This works and it's deadly simple. As many points as you want:

    private function moveTweets():void {


        var newScale:Number=Scale(meshes.length,50,500,6,2);
        trace("new scale:"+newScale);


        var l:Number=this.meshes.length;
        var tweetMeshInstance:TweetMesh;
        var destx:Number;
        var desty:Number;
        var destz:Number;
        for (var i:Number=0;i<this.meshes.length;i++){

            tweetMeshInstance=meshes[i];

            var phi:Number = Math.acos( -1 + ( 2 * i ) / l );
            var theta:Number = Math.sqrt( l * Math.PI ) * phi;

            tweetMeshInstance.origX = (sphereRadius+5) * Math.cos( theta ) * Math.sin( phi );
            tweetMeshInstance.origY= (sphereRadius+5) * Math.sin( theta ) * Math.sin( phi );
            tweetMeshInstance.origZ = (sphereRadius+5) * Math.cos( phi );

            destx=sphereRadius * Math.cos( theta ) * Math.sin( phi );
            desty=sphereRadius * Math.sin( theta ) * Math.sin( phi );
            destz=sphereRadius * Math.cos( phi );

            tweetMeshInstance.lookAt(new Vector3D());


            TweenMax.to(tweetMeshInstance, 1, {scaleX:newScale,scaleY:newScale,x:destx,y:desty,z:destz,onUpdate:onLookAtTween, onUpdateParams:[tweetMeshInstance]});

        }

    }
    private function onLookAtTween(theMesh:TweetMesh):void {
        theMesh.lookAt(new Vector3D());
    }

Closing Excel Application using VBA

To avoid the Save prompt message, you have to insert those lines

Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True

After saving your work, you need to use this line to quit the Excel application

Application.Quit

Don't just simply put those line in Private Sub Workbook_Open() unless you got do a correct condition checking, else you may spoil your excel file.

For safety purpose, please create a module to run it. The following are the codes that i put:

Sub testSave()
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
End Sub

Hope it help you solve the problem.

array of string with unknown size

I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:

List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");

Or, if you need to be absolutely sure that the strings remain in order:

Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");

Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

remove item from stored array in angular 2

I think the Angular 2 way of doing this is the filter method:

this.data = this.data.filter(item => item !== data_item);

where data_item is the item that should be deleted

Scanning Java annotations at runtime

And another solution is Google reflections.

Quick review:

  • Spring solution is the way to go if you're using Spring. Otherwise it's a big dependency.
  • Using ASM directly is a bit cumbersome.
  • Using Java Assist directly is clunky too.
  • Annovention is super lightweight and convenient. No maven integration yet.
  • Google reflections pulls in Google collections. Indexes everything and then is super fast.

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

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

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

Return rows in random order

The usual method is to use the NEWID() function, which generates a unique GUID. So,

SELECT * FROM dbo.Foo ORDER BY NEWID();

Faster way to zero memory than with memset?

memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.

What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0, if you init large number of small objects.

Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.

Comparing the contents of two files in Sublime Text

View - Layout and View - Groups will do in latest Sublime 3

eg:

Shift+Alt+2 --> creates 2 columns

Ctrl+2 --> move selected file to column 2

This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.

How can I make git show a list of the files that are being tracked?

You might want colored output with this.

I use this one-liner for listing the tracked files and directories in the current directory of the current branch:

ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)

You might want to add it as an alias:

alias gl='ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)'

If you want to recursively list files:

'ls' --color=auto -d $(git ls-tree -rt $(git branch | grep \* | cut -d " " -f2) --name-only)

And an alias:

alias glr="'ls' --color=auto -d \$(git ls-tree -rt \$(git branch | grep \\* | cut -d \" \" -f2) --name-only)"

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

Load a UIView from nib in Swift

I prefer this solution (based on the answer if @GK100):

  1. I created a XIB and a class named SomeView (used the same name for convenience and readability). I based both on a UIView.
  2. In the XIB, I changed the "File's Owner" class to SomeView (in the identity inspector).
  3. I created a UIView outlet in SomeView.swift, linking it to the top level view in the XIB file (named it "view" for convenience). I then added other outlets to other controls in the XIB file as needed.
  4. In SomeView.swift, I loaded the XIB inside the init or init:frame: CGRect initializer. There is no need to assign anything to "self". As soon as the XIB is loaded, all outlets are connected, including the top level view. The only thing missing, is to add the top view to the view hierarchy:

    class SomeView: UIView {
      override init(frame: CGRect) {
        super.init(frame: frame)
        NSBundle.mainBundle().loadNibNamed("SomeObject", owner: self, options: nil)
        self.addSubview(self.view);    // adding the top level view to the view hierarchy
      }
    
      required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        NSBundle.mainBundle().loadNibNamed("SomeObject", owner: self, options: nil)
        self.addSubview(self.view);    // adding the top level view to the view hierarchy
      }
    
    
      ...
    }
    

Installing NumPy and SciPy on 64-bit Windows (with Pip)

If you are on windows , you wouldn't need wheel anyway! You can directly install package by downloading the 32-bit package as win32 from this link [http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy] and then move that downloaded package to cmd's current directory and open cmd and write following codepip install numpy-1.13.1+mkl-cp36-cp36m-win32.whl then do it same for scipy

For 64-bit you need to install mingw-w64 as it is gcc and compiles numpy and scipy as precompiled status.

Currently it works fine with 32-bit.So I had opted for win32 package both for numpy+mkl and scipy in that link.

Hope This works! Give a try

Can I use an HTML input type "date" to collect only a year?

You can do the following:

  1. Generate an Array of the years I'll be accepting,
  2. Use a select box.
  3. Use each item from your Array as an 'option' tag.

Example using PHP (you can do this in any language of your choice):

Server:

<?php $years = range(1900, strftime("%Y", time())); ?>

HTML

<select>
  <option>Select Year</option>
  <?php foreach($years as $year) : ?>
    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
  <?php endforeach; ?>
</select>

As an added benefit, this works has a browser compatibility of a 100% ;-)

What are the benefits of learning Vim?

You can get good functionality out of vim by learning the meanings of only 16 keys: ijkdbw9:q!%s/nNEsc. You can do the bare bones with just i:wqEsc.

The first two keys you need to know are: Esc takes you to command mode (the mode you start in), and i takes you to insert mode (normal typing).


To save you need to

  1. get out of typing mode (Esc)
  2. type a colon :
  3. type lowercase w then Enter

To save-and-quit you need to

  1. get out of typing mode (Esc)
  2. type a colon :
  3. type lowercase wq then Enter

To not-save-and-force-quit you need to

  1. get out of typing mode (Esc)
  2. type a colon :
  3. type lowercase q! then Enter

To learn more you can run vimtutor at the command line. It's a medium-length, well-structured lesson.

Beyond i and Esc: you can replicate or surpass some MS Word functionality with only jkwbd3:%s/nN.

  1. b takes you back a word (Ctrl+)
  2. w takes you forward a word (Ctrl+)
  3. 9w takes you forward nine words
  4. db deletes the preceding word (Ctrl+Backspace)
  5. d3b deletes three preceding words
  6. 9j moves down 9 lines
  7. / ornithopter Enter takes you to the next instance of the word "ornithopter", then n and N to the next and previous occurrence of "ornithopter" respectively.
  8. :%s/confounded/dangfangled/ Enter substitutes every "confounded" with "dangfangled" (like find and replace all in MS Word)

Any of those should be run in "command" mode (Esc), not insert mode (i).

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

How to create a Restful web service with input parameters?

Be careful. For this you need @GET (not @PUT).

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783