Programs & Examples On #Materialized views

A materialized view is a database object that contains the results of a query. They can be local copies of data located remotely, or can be used to create summary tables based on aggregations of a table's data. Materialized views are also known as snapshots.

Computed / calculated / virtual / derived columns in PostgreSQL

Well, not sure if this is what You mean but Posgres normally support "dummy" ETL syntax. I created one empty column in table and then needed to fill it by calculated records depending on values in row.

UPDATE table01
SET column03 = column01*column02; /*e.g. for multiplication of 2 values*/
  1. It is so dummy I suspect it is not what You are looking for.
  2. Obviously it is not dynamic, you run it once. But no obstacle to get it into trigger.

What is the difference between Views and Materialized Views in Oracle?

Adding to Mike McAllister's pretty-thorough answer...

Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.

When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.

How to refresh materialized view in oracle

If you're working with SQL Developer, you have to put the dbms_view in lowercase. The rest compiled fine for me although I haven't called the procedure from code yet.

CREATE OR REPLACE PROCEDURE "MAT_VIEW_FOO_TBL" AS 
BEGIN
  dbms_mview.refresh('v_materialized_foo_tbl');
END;

mySQL Error 1040: Too Many Connection

If you are running out of connections like this, chances are excellent that you are not closing the connections that you have open.

Review code that opens connections and ensure the connections are closed as soon as practical. Typically you want to make use of the using keyword around anything that implements IDisposable (including database connections) to ensure that such objects are disposed as soon as they leave the scope where they are needed.

You can check the current number of active connections with this query:

show processlist

Reference: MySQL show status - active or total connections?

How can I convert a .jar to an .exe?

JSmooth .exe wrapper

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your Java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a website.

JSmooth provides a variety of wrappers for your java application, each of them having their own behavior: Choose your flavor!

Download: http://jsmooth.sourceforge.net/

JarToExe 1.8 Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe on their website:

Can generate “Console”, “Windows GUI”, “Windows Service” three types of .exe files.

Generated .exe files can add program icons and version information. Generated .exe files can encrypt and protect java programs, no temporary files will be generated when the program runs.

Generated .exe files provide system tray icon support. Generated .exe files provide record system event log support. Generated windows service .exe files are able to install/uninstall itself, and support service pause/continue.

Executor

Package your Java application as a jar, and Executor will turn the jar into a Windows .exe file, indistinguishable from a native application. Simply double-clicking the .exe file will invoke the Java Runtime Environment and launch your application.

Save current directory in variable using Bash?

This saves the absolute path of the current working directory to the variable cwd:

cwd=$(pwd)

In your case you can just do:

export PATH=$PATH:$(pwd)+somethingelse

How to use Boost in Visual Studio 2010

I could recommend the following trick: Create a special boost.props file

  1. Open the property manager
  2. Right click on your project node, and select 'Add new project property sheet'.
  3. Select a location and name your property sheet (e.g. c:\mystuff\boost.props)
  4. Modify the additional Include and Lib folders to the search path.

This procedure has the value that boost is included only in projects where you want to explicitly include it. When you have a new project that uses boost, do:

  1. Open the property manager.
  2. Right click on the project node, and select 'Add existing property sheet'.
  3. Select the boost property sheet.

EDIT (following edit from @jim-fred):

The resulting boost.props file looks something like this...

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros">
    <BOOST_DIR>D:\boost_1_53_0\</BOOST_DIR>
  </PropertyGroup>
  <PropertyGroup>
    <IncludePath>$(BOOST_DIR);$(IncludePath)</IncludePath>
    <LibraryPath>$(BOOST_DIR)stage\lib\;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
</Project>

It contains a user macro for the location of the boost directory (in this case, D:\boost_1_53_0) and two other parameters: IncludePath and LibraryPath. A statement #include <boost/thread.hpp> would find thread.hpp in the appropriate directory (in this case, D:\boost_1_53_0\boost\thread.hpp). The 'stage\lib\' directory may change depending on the directory installed to.

This boost.props file could be located in the D:\boost_1_53_0\ directory.

White space showing up on right side of page when background image should extend full length of page

This is a pretty old question, but I thought I'd add my 2 cents. I've tried the above solutions, including the ghost css, which I will definitely be saving for future use. But none of these worked in my situation. Here's how I fixed my issue. Hopefully this will help someone else.

Open inspector (or whatever your preference) and starting with the first div in body tag, add display: none; to just that element. If the scroll bar disappears, you know that element contains the element that's causing the issue. Then, remove the first css rule and go down one level into the containing element. Add the css to that div, and if the scroll bar goes away, you know that element is either causing, or containing the offending element. If adding the CSS does nothing, you know it was not that div that caused the issue, and either another div in the container is causing it, or the container itself is causing it.

This may be too time consuming for some. Lucky for me, my issue was in the header, but I can imagine this taking a bit of time if your issue was say, in the footer or something.

Passing multiple argument through CommandArgument of Button in Asp.net

Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.

Send value of submit button when form gets posted

The initial post mentioned buttons. You can also replace the input tags with buttons.

<button type="submit" name="product" value="Tea">Tea</button>
<button type="submit" name="product" value="Coffee">Coffee</button>

The name and value attributes are required to submit the value when the form is submitted (the id attribute is not necessary in this case). The attribute type=submit specifies that clicking on this button causes the form to be submitted.

When the server is handling the submitted form, $_POST['product'] will contain the value "Tea" or "Coffee" depending on which button was clicked.

If you want you can also require the user to confirm before submitting the form (useful when you are implementing a delete button for example).

<button type="submit" name="product" value="Tea" onclick="return confirm('Are you sure you want tea?');">Tea</button>
<button type="submit" name="product" value="Coffee" onclick="return confirm('Are you sure you want coffee?');">Coffee</button>

Get all dates between two dates in SQL Server

You can try this:

    SET LANGUAGE SPANISH

DECLARE @startDate DATE = GETDATE() -- Your start date
DECLARE @endDate DATE = DATEADD(MONTH, 16, GETDATE()) -- Your end date
DECLARE @years INT = YEAR(@endDate) - YEAR(@startDate)

CREATE TABLE #TMP_YEARS (
    [year] INT
)

-- Get all posible years between the start and end date
WHILE @years >= 0
BEGIN
    INSERT INTO #TMP_YEARS
    ([year])
    SELECT YEAR(@startDate) + @years

    SET @years = @years - 1
END

;WITH [days]([day]) AS -- Posible days at a month
(
    SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL -- days lower than 10
    SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL -- days lower than 20
    SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24 UNION ALL SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29 UNION ALL -- days lower than 30
    SELECT 30 UNION ALL SELECT 31 -- days higher 30
),
[months]([month]) AS -- All months at a year
(
    SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
)
SELECT CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) as [date]
  FROM #TMP_YEARS a
 CROSS JOIN [months] n -- Join all years with all months
 INNER JOIN [days] d on DAY(EOMONTH(CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + CONVERT(VARCHAR, DAY(EOMONTH(CAST(CONVERT(VARCHAR, a.[year]) + '-' + CONVERT(varchar, n.[month]) + '-15' AS DATE)))))) >= d.[day] AND -- The number of the day can't be higher than the last day of the current month and the current year
                      CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) <= ISNULL(@endDate, GETDATE()) AND -- The current date can't be higher than the end date
                      CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) >= ISNULL(@startDate, GETDATE()) -- The current date should be higher than the start date
 ORDER BY a.[year] ASC, n.[month] ASC, d.[day] ASC

The output will be something like this, you can format the date as you like:

2019-01-24
2019-01-25
2019-01-26
2019-01-27
2019-01-28
2019-01-29
2019-01-30
2019-01-31
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06
2019-02-07
2019-02-08
2019-02-09
...

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

This is how I did it. You don't need to delete Java 9 or newer version.

Step 1: Install Java 8

You can download Java 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Step 2: After installation of Java 8. Confirm installation of all versions.Type the following command in your terminal.

/usr/libexec/java_home -V

Step 3: Edit .bash_profile

sudo nano ~/.bash_profile

Step 4: Add 1.8 as default. (Add below line to bash_profile file).

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

Now Press CTRL+X to exit the bash. Press 'Y' to save changes.

Step 5: Reload bash_profile

source ~/.bash_profile

Step 6: Confirm current version of Java

java -version

Get spinner selected items text?

You have to use the index and the Adapter to find out the text you have

See this example of Spinner

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
      Toast.makeText(parent.getContext()), "The planet is " +
          parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView parent) {
      // Do nothing.
    }
}

An invalid XML character (Unicode: 0xc) was found

Whenever invalid xml character comes xml, it gives such error. When u open it in notepad++ it look like VT, SOH,FF like these are invalid xml chars. I m using xml version 1.0 and i validate text data before entering it in database by pattern

Pattern p = Pattern.compile("[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+"); 
retunContent = p.matcher(retunContent).replaceAll("");

It will ensure that no invalid special char will enter in xml

How can I render inline JavaScript with Jade / Pug?

For multi-line content jade normally uses a "|", however:

Tags that accept only text such as script, style, and textarea do not need the leading | character

This said, i cannot reproduce the problem you are having. When i paste that code in a jade template, it produces the right output and prompts me with an alert on page-load.

Get value from text area

Vanilla JS

document.getElementById("textareaID").value

jQuery

$("#textareaID").val()

Cannot do the other way round (it's always good to know what you're doing)

document.getElementById("textareaID").value() // --> TypeError: Property 'value' of object #<HTMLTextAreaElement> is not a function

jQuery:

$("#textareaID").value // --> undefined

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

What does this thread join code mean?

This is a favorite Java interview question.

Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();

while (true) {
    try {
        t1.join(); // 1
        t2.join(); // 2  These lines (1,2) are in in public static void main
        break;
    }
}

t1.join() means, t1 says something like "I want to finish first". Same is the case with t2. No matter who started t1 or t2 thread (in this case the main method), main will wait until t1 and t2 finish their task.

However, an important point to note down, t1 and t2 themselves can run in parallel irrespective of the join call sequence on t1 and t2. It is the main/daemon thread that has to wait.

Convert java.util.date default format to Timestamp in Java

java.time

I am providing the modern answer. The Timestamp class was always poorly designed, a real hack on top of the already poorly designed Date class. Both those classes are now long outdated. Don’t use them.

When the question was asked, you would need a Timestamp for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone (recommended for true timestamps), pass it an OffsetDateTime.

Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013: the time zone abbreviation. IST may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("EEE MMM dd HH:mm:ss ")
            .appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
            .appendPattern(" yyyy")
            .toFormatter(Locale.ROOT);
    String dateString = "Mon May 27 11:46:15 IST 2013";
    OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
            .atOffset(ZoneOffset.UTC);
    System.out.println(dateTime);

This snippet prints:

2013-05-27T06:16:15Z

This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime to your database using one of the PreparedStatement.setObject methods (not setTimestamp).

How can I convert this into timestamp and calculate in seconds the difference between the same and current time?

Calculating the difference in seconds goes very naturally with java.time:

    long differenceInSeconds = ChronoUnit.SECONDS
            .between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
    System.out.println(differenceInSeconds);

When running just now I got:

202213260

Link: Oracle tutorial: Date Time explaining how to use java.time.

Check if number is decimal

I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:

function isDecimal($value) 
{
     return ((float) $value !== floor($value));
}

I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.

How to output something in PowerShell

Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta

Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.

The + $File.FullName is optional, and shows how to put a variable into the string.

How to return a value from __init__ in Python?

Just wanted to add, you can return classes in __init__

@property
def failureException(self):
    class MyCustomException(AssertionError):
        def __init__(self_, *args, **kwargs):
            *** Your code here ***
            return super().__init__(*args, **kwargs)

    MyCustomException.__name__ = AssertionError.__name__
    return MyCustomException

The above method helps you implement a specific action upon an Exception in your test

What is the inclusive range of float and double in Java?

From Primitives Data Types:

  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

For the range of values, see the section 4.2.3 Floating-Point Types, Formats, and Values of the JLS.

How to get cumulative sum

Once the table is created -

select 
    A.id, A.SomeNumt, SUM(B.SomeNumt) as sum
    from @t A, @t B where A.id >= B.id
    group by A.id, A.SomeNumt

order by A.id

Escape double quotes in parameter

Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.

Here's a set of basic rules:

  1. When not wrapped in double-quoted groups, spaces separate parameters:
    program param1 param2 param 3 will pass four parameters to program.exe:
         param1, param2, param, and 3.
  2. A double-quoted group ignores spaces as value separators when passing parameters to programs:
    program one two "three and more" will pass three parameters to program.exe:
         one, two, and three and more.
  3. Now to explain some of the confusion:
  4. Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:
    hello"to the entire"world acts as one parameter: helloto the entireworld.
  5. Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
  6. Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:
    "Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"

Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:

"   open double-quote group
T   inside ""s
i   inside ""s
m   inside ""s
    inside ""s - space doesn't separate
s   inside ""s
a   inside ""s
y   inside ""s
s   inside ""s
,   inside ""s
    inside ""s - space doesn't separate
"   close double-quoted group
"   quote directly follows closer - acts as plain unwrapped text: "
H   outside ""s - gets joined to previous adjacent group
i   outside ""s - ...
!   outside ""s - ...
"   open double-quote group
"   close double-quote group
"   quote directly follows closer - acts as plain unwrapped text: "

Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,  is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
 is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.

As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.

From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:

"Tim said to him, """What's been happening lately?""""

will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.

Here are a few examples to close it off:

program a b                       REM sends (a) and (b)
program """a"""                   REM sends ("a")
program """a b"""                 REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d""            REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes""     REM sends (hello to "quotes")
program """"hello world""         REM sends ("hello world")
program """hello" world""         REM sends ("hello world")
program """hello "world""         REM sends ("hello) and (world")
program "hello ""world"""         REM sends (hello "world")
program "hello """world""         REM sends (hello "world")

Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.

I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).

jquery find class and get the value

You can also get the value by the following way

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});

Injecting $scope into an angular service function()

The $scope that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope and you can create a new child-scope using the $new() method of any scope (including the $rootScope).

The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope into a service.

Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc).

I am sure, various approaches would work for you. One is this:
Since the StudentService is in charge of dealing with student data, you can have the StudentService keep an array of students and let it "share" it with whoever might be interested (e.g. your $scope). This makes even more sense, if there are other views/controllers/filters/services that need to have access to that info (if there aren't any right now, don't be surprised if they start popping up soon).
Every time a new student is added (using the service's save() method), the service's own array of students will be updated and every other object sharing that array will get automatically updated as well.

Based on the approach described above, your code could look like this:

angular.
  module('cfd', []).

  factory('StudentService', ['$http', '$q', function ($http, $q) {
    var path = 'data/people/students.json';
    var students = [];

    // In the real app, instead of just updating the students array
    // (which will be probably already done from the controller)
    // this method should send the student data to the server and
    // wait for a response.
    // This method returns a promise to emulate what would happen 
    // when actually communicating with the server.
    var save = function (student) {
      if (student.id === null) {
        students.push(student);
      } else {
        for (var i = 0; i < students.length; i++) {
          if (students[i].id === student.id) {
            students[i] = student;
            break;
          }
        }
      }

      return $q.resolve(student);
    };

    // Populate the students array with students from the server.
    $http.get(path).then(function (response) {
      response.data.forEach(function (student) {
        students.push(student);
      });
    });

    return {
      students: students,
      save: save
    };     
  }]).

  controller('someCtrl', ['$scope', 'StudentService', 
    function ($scope, StudentService) {
      $scope.students = StudentService.students;
      $scope.saveStudent = function (student) {
        // Do some $scope-specific stuff...

        // Do the actual saving using the StudentService.
        // Once the operation is completed, the $scope's `students`
        // array will be automatically updated, since it references
        // the StudentService's `students` array.
        StudentService.save(student).then(function () {
          // Do some more $scope-specific stuff, 
          // e.g. show a notification.
        }, function (err) {
          // Handle the error.
        });
      };
    }
]);

One thing you should be careful about when using this approach is to never re-assign the service's array, because then any other components (e.g. scopes) will be still referencing the original array and your app will break.
E.g. to clear the array in StudentService:

/* DON'T DO THAT   */  
var clear = function () { students = []; }

/* DO THIS INSTEAD */  
var clear = function () { students.splice(0, students.length); }

See, also, this short demo.


LITTLE UPDATE:

A few words to avoid the confusion that may arise while talking about using a service, but not creating it with the service() function.

Quoting the docs on $provide:

An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function.
[...]
...the $provide service has additional helper methods to register services without specifying a provider:

  • provider(provider) - registers a service provider with the $injector
  • constant(obj) - registers a value/object that can be accessed by providers and services.
  • value(obj) - registers a value/object that can only be accessed by services, not providers.
  • factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
  • service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.

Basically, what it says is that every Angular service is registered using $provide.provider(), but there are "shortcut" methods for simpler services (two of which are service() and factory()).
It all "boils down" to a service, so it doesn't make much difference which method you use (as long as the requirements for your service can be covered by that method).

BTW, provider vs service vs factory is one of the most confusing concepts for Angular new-comers, but fortunately there are plenty of resources (here on SO) to make things easier. (Just search around.)

(I hope that clears it up - let me know if it doesn't.)

Limiting double to 3 decimal places

double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));

Deactivate or remove the scrollbar on HTML

Meder Omuraliev suggested to use an event handler and set scrollTo(0,0). This is an example for Wassim-azirar. Bringing it all together, I assume this is the final solution.

We have 3 problems: the scrollbar, scrolling with mouse, and keyboard. This hides the scrollbar:

       html, body{overflow:hidden;}

Unfortunally, you can still scroll with the keyboard: To prevent this, we can:

    function keydownHandler(e) {
var evt = e ? e:event;
  var keyCode = evt.keyCode;

  if (keyCode==38 || keyCode==39 || keyCode==40 || keyCode==37){ //arrow keys
e.preventDefault()
scrollTo(0,0);
}
}

document.onkeydown=keydownHandler;

The scrolling with the mouse just naturally doesn't work after this code, so we have prevented the scrolling.

For example: https://jsfiddle.net/aL7pes70/1/

Tar archiving that takes input from a list of files

For me on AIX, it worked as follows:

tar -L List.txt -cvf BKP.tar

Override hosts variable of Ansible playbook from the command line

An other solution is to use the special variable ansible_limit which is the contents of the --limit CLI option for the current execution of Ansible.

- hosts: "{{ ansible_limit | default(omit) }}"

If the --limit option is omitted, then Ansible issues a warning, but does nothing since no host matched.

[WARNING]: Could not match supplied host pattern, ignoring: None

PLAY ****************************************************************
skipping: no hosts matched

Android change SDK version in Eclipse? Unable to resolve target android-x

Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.

Print content of JavaScript object?

You could Node's util.inspect(object) to print out object's structure.

It is especially helpful when your object has circular dependencies e.g.

$ node

var obj = {
   "name" : "John",
   "surname" : "Doe"
}
obj.self_ref = obj;

util = require("util");

var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: 'John', surname: 'Doe', self_ref: [Circular] }

It that case JSON.stringify throws exception: TypeError: Converting circular structure to JSON

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

try this

echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static variables are used when only one copy of it is required. Let me explain this with an example:

class circle
{
    public float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * this._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now here we have created 2 instances for our class circle , i.e 2 sets of copies of _PI along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI will be created occupying memory. So in such cases it is better to make such variables like _PI static and operate on them.

class circle
{
    static float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * Circle._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now no matter how many instances are made for the class circle , only one copy exists of variable _PI saving our memory.

Autocompletion in Vim

I've just found the project Eclim linked in another question. This looks quite promising, at least for Java integration.

Run cmd commands through Java

My example (from real project)

folder — File.

zipFile, filesString — String;

        final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
        logger.info("Start unzipping: {}    into the folder {}", command, folder.getPath());
        final Runtime r = Runtime.getRuntime();
        final Process p = r.exec(command, null, folder);
        final int returnCode = p.waitFor();

        if (logger.isWarnEnabled()) {
            final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = is.readLine()) != null) {
                logger.warn(line);
            }
            final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = is2.readLine()) != null) {
                logger.warn(line);
            }
        }

Is there a JavaScript / jQuery DOM change listener?

In addition to the "raw" tools provided by MutationObserver API, there exist "convenience" libraries to work with DOM mutations.

Consider: MutationObserver represents each DOM change in terms of subtrees. So if you're, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j].

Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.

A good convenience library that solves such problems is mutation-summary (disclaimer: I'm not the author, just a satisfied user), which enables you to specify queries of what you're interested in, and get exactly that.

Basic usage example from the docs:

var observer = new MutationSummary({
  callback: updateWidgets,
  queries: [{
    element: '[data-widget]'
  }]
});

function updateWidgets(summaries) {
  var widgetSummary = summaries[0];
  widgetSummary.added.forEach(buildNewWidget);
  widgetSummary.removed.forEach(cleanupExistingWidget);
}

Android view pager with page indicator

you have to do following:

1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.

After importing if you want to make following type of screen then follow below steps -

Screen Shot

change in

Sample circles Default

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter

 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>

Parsing JSON using C

You can have a look at Jansson

The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features:

  • Simple and intuitive API and data model
  • Can both encode to and decode from JSON
  • Comprehensive documentation
  • No dependencies on other libraries
  • Full Unicode support (UTF-8)
  • Extensive test suite

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If you don't see the Active Directory, it's because you did not install AD LS Users and Computer Feature. Go to Manage - Add Roles & Features. Within Add Roles and Features Wizard, on Features tab, select Remote Server Administration Tools, select - Role Admininistration Tools - Select AD DS and DF LDS Tools.

After that, you can see the PS Active Directory package.

Get week number (in the year) from a date PHP

Becomes more difficult when you need year and week.
Try to find out which week is 01.01.2017.
(It is the 52nd week of 2016, which is from Mon 26.12.2016 - Sun 01.01.2017).

After a longer search I found

strftime('%G-%V',strtotime("2017-01-01"))

Result: 2016-52


https://www.php.net/manual/de/function.strftime.php
ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week. (01 through 53)


The equivalent in mysql is DATE_FORMAT(date, '%x-%v') https://www.w3schools.com/sql/func_mysql_date_format.asp
Week where Monday is the first day of the week (01 to 53).


Could not find a corresponding solution with date() or DateTime.
At least not without solutions like "+1day, last monday".

"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

Checking for directory and file write permissions in .NET

The accepted answer by Kev to this question doesn't actually give any code, it just points to other resources that I don't have access to. So here's my best attempt at the function. It actually checks that the permission it's looking at is a "Write" permission and that the current user belongs to the appropriate group.

It might not be complete with regard to network paths or whatever, but it's good enough for my purpose, checking local configuration files under "Program Files" for writability:

using System.Security.Principal;
using System.Security.AccessControl;

private static bool HasWritePermission(string FilePath)
{
    try
    {
        FileSystemSecurity security;
        if (File.Exists(FilePath))
        {
            security = File.GetAccessControl(FilePath);
        }
        else
        {
            security = Directory.GetAccessControl(Path.GetDirectoryName(FilePath));
        }
        var rules = security.GetAccessRules(true, true, typeof(NTAccount));

        var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        bool result = false;
        foreach (FileSystemAccessRule rule in rules)
        {
            if (0 == (rule.FileSystemRights &
                (FileSystemRights.WriteData | FileSystemRights.Write)))
            {
                continue;
            }

            if (rule.IdentityReference.Value.StartsWith("S-1-"))
            {
                var sid = new SecurityIdentifier(rule.IdentityReference.Value);
                if (!currentuser.IsInRole(sid))
                {
                    continue;
                }
            }
            else
            {
                if (!currentuser.IsInRole(rule.IdentityReference.Value))
                {
                    continue;
                }
            }

            if (rule.AccessControlType == AccessControlType.Deny)
                return false;
            if (rule.AccessControlType == AccessControlType.Allow)
                result = true;
        }
        return result;
    }
    catch
    {
        return false;
    }
}

How can I switch to another branch in git?

Check : git branch -a

If you are getting only one branch. Then do below steps.

  • Step 1 : git config --list
  • Step 2 : git config --unset remote.origin.fetch
  • Step 3 : git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/*

Laravel Migration table already exists, but I want to add new not the older

  1. Drop all tables manually at the phpmyadmin.

  2. Go to each migration file at database/migrations. Find and remove these 2 codes :

    a) ->index() (found at 2014_10_12_100000_create_password_resets_table.php at line 17)

    b) ->unique() (found at 2014_10_12_000000_create_users_table.php at line 19)

  3. Run php artisan migrate

  4. Done.

I think this happens because the latest laravel class (at 12th February 2018) has removed the function of ->index() and ->unique()

Circular (or cyclic) imports in Python

I solved the problem the following way, and it works well without any error. Consider two files a.py and b.py.

I added this to a.py and it worked.

if __name__ == "__main__":
        main ()

a.py:

import b
y = 2
def main():
    print ("a out")
    print (b.x)

if __name__ == "__main__":
    main ()

b.py:

import a
print ("b out")
x = 3 + a.y

The output I get is

>>> b out 
>>> a out 
>>> 5

Passing data between different controller action methods

I prefer to use this instead of TempData

public class Home1Controller : Controller 
{
    [HttpPost]
    public ActionResult CheckBox(string date)
    {
        return RedirectToAction("ActionName", "Home2", new { Date =date });
    }
}

and another controller Action is

public class Home2Controller : Controller 
{
    [HttpPost]
    Public ActionResult ActionName(string Date)
    {
       // do whatever with Date
       return View();
    }
}

it is too late but i hope to be helpful for any one in the future

Switch php versions on commandline ubuntu 16.04

Switch from PHP 5.6 to PHP 7.2 using:

sudo a2dismod php5.6 && sudo a2enmod php7.2 && sudo service apache2 restart

Switch from PHP 7.2 to PHP 5.6 using:

sudo a2dismod php7.2 && sudo a2enmod php5.6 && sudo service apache2 restart

Print a file, skipping the first X lines, in Bash

You can do this using the head and tail commands:

head -n <num> | tail -n <lines to print>

where num is 1e6 + the number of lines you want to print.

Targeting only Firefox with CSS

Here is some browser hacks for targeting only the Firefox browser,

Using selector hacks.

_:-moz-tree-row(hover), .selector {}

JavaScript Hacks

var isFF = !!window.sidebar;

var isFF = 'MozAppearance' in document.documentElement.style;

var isFF = !!navigator.userAgent.match(/firefox/i);

Media Query Hacks

This is gonna work on, Firefox 3.6 and Later

@media screen and (-moz-images-in-menus:0) {}

If you need more information,Please visit browserhacks

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I resolved my case by replacing "import" by "require".

// import { parse } from 'node-html-parser';
parse = require('node-html-parser');

How do I hide certain files from the sidebar in Visual Studio Code?

The "Make Hidden" extension works great!

Make Hidden provides more control over your project's directory by enabling context menus that allow you to perform hide/show actions effortlessly, a view pane explorer to see hidden items and the ability to save workspaces to quickly toggle between bulk hidden items.

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.

Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.

In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.

Note

  • Do not blindly delete everything directly from disk that you "think" is not required occupying. I did that once and had to re-download.
  • Make sure you have a list of all active projects with the kind of emulators (if any) and API Levels and Build tools required for those to continue working/compiling properly.

First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:

Steps to safely clear up unwanted stuff from Android SDK folder on the disk

  1. Open the Stand Alone Android SDK Manager. To open do one of the following:
  • Click the SDK Manager button on toolbar in android studio or eclipse
  • In Android Studio, go to settings and search "Android SDK". Click Android SDK -> "Open Standalone SDK Manager"
  • In Eclipse, open the "Window" menu and select "Android SDK Manager"
  • Navigate to the location of the android-sdk directory on your computer and run "SDK Manager.exe"

.

  1. Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.

.

  1. Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.

.

  1. In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.

In the end the clean android sdk installed components should look something like this in the SDK manager.

enter image description here

In C, how should I read a text file and print all strings

There are plenty of good answers here about reading it in chunks, I'm just gonna show you a little trick that reads all the content at once to a buffer and prints it.

I'm not saying it's better. It's not, and as Ricardo sometimes it can be bad, but I find it's a nice solution for the simple cases.

I sprinkled it with comments because there's a lot going on.

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

char* ReadFile(char *filename)
{
   char *buffer = NULL;
   int string_size, read_size;
   FILE *handler = fopen(filename, "r");

   if (handler)
   {
       // Seek the last byte of the file
       fseek(handler, 0, SEEK_END);
       // Offset from the first to the last byte, or in other words, filesize
       string_size = ftell(handler);
       // go back to the start of the file
       rewind(handler);

       // Allocate a string that can hold it all
       buffer = (char*) malloc(sizeof(char) * (string_size + 1) );

       // Read it all in one operation
       read_size = fread(buffer, sizeof(char), string_size, handler);

       // fread doesn't set it so put a \0 in the last position
       // and buffer is now officially a string
       buffer[string_size] = '\0';

       if (string_size != read_size)
       {
           // Something went wrong, throw away the memory and set
           // the buffer to NULL
           free(buffer);
           buffer = NULL;
       }

       // Always remember to close the file.
       fclose(handler);
    }

    return buffer;
}

int main()
{
    char *string = ReadFile("yourfile.txt");
    if (string)
    {
        puts(string);
        free(string);
    }

    return 0;
}

Let me know if it's useful or you could learn something from it :)

iconv - Detected an illegal character in input string

PHP 7.2

iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// "e@uu$`a"

iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"

iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@uu$`a"

PHP 7.4

iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// PHP Notice:  iconv(): Detected an illegal character

iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"

iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@u$`a"

iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate('é@ùµ$`à'))
// "e@uu$`a" -> same as PHP 7.2

How to disable logging on the standard error stream in Python?

I found a solution for this:

logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.

This will prevent logging from being send to the upper logger that includes the console logging.

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

Multiple modals overlay

Try adding the following to your JS on bootply

$('#myModal2').on('show.bs.modal', function () {  
$('#myModal').css('z-index', 1030); })

$('#myModal2').on('hidden.bs.modal', function () {  
$('#myModal').css('z-index', 1040); })

Explanation:

After playing around with the attributes(using Chrome's dev tool), I have realized that any z-index value below 1031 will put things behind the backdrop.

So by using bootstrap's modal event handles I set the z-index to 1030. If #myModal2 is shown and set the z-index back to 1040 if #myModal2 is hidden.

Demo

Remove all whitespace from C# string with regex

Below is the code that would replace the white space from the file name into given URL and also we can remove the same by using string.empty instead of "~"

  if (!string.IsNullOrEmpty(url))
          {
           string origFileName = Path.GetFileName(url);
           string modiFileName = origFileName.Trim().Replace(" ", "~");
           url = url.Replace(origFileName , modiFileName );
          }
          return url;

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How to solve "The specified service has been marked for deletion" error

I had the same problem, finally I decide to kill service process.

for it try below steps:

  • get process id of service with

    sc queryex <service name>

  • kill process with

    taskkill /F /PID <Service PID>

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get the cursor to change to the hand when hovering a <button> tag

All u need is just use one of the attribute of CSS , which is---->

cursor:pointer

just use this property in css , no matter its inline or internal or external

for example(for inline css)

<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>

How do I make a simple makefile for gcc on Linux?

all: program
program.o: program.h headers.h

is enough. the rest is implicit

Checking if a variable is an integer

There's var.is_a? Class (in your case: var.is_a? Integer); that might fit the bill. Or there's Integer(var), where it'll throw an exception if it can't parse it.

Converting java.util.Properties to HashMap<String,String>

You can use this:

Map<String, String> map = new HashMap<>();

props.forEach((key, value) -> map.put(key.toString(), value.toString()));

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Make sure that you are building your web app as "Any CPU". Right click your web project --> Properties --> Build --> and look for the "Platform Target". Choose "Any CPU" or play around with it.

Hope this helps!

What can I use for good quality code coverage for C#/.NET?

I just tested out NCrunch and have to say I am very impressed. It is a continuous testing tool that will add code coverage to your code in Visual Studio at almost real time. At the time as I write this NCrunch is free. It is a little unclear if it going to be free, cost money or be opened source in the future though.

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

How can I replace text with CSS?

Well, as many said this is a hack. However, I'd like to add more up-to-date hack, which takes an advantage of flexbox and rem, i.e.

  • You don't want to manually position this text to be changed, that's why you'd like to take an advantage of flexbox
  • You don't want to use padding and/or margin to the text explicitly using px, which for different screen sizes on different devices and browsers might give different output

Here's the solution, in short flexbox makes sure that it's automatically positioned perfectly and rem is more standardized (and automated) alternative for pixels.

CodeSandbox with code below and output in a form of a screenshot, do please read a note below the code!

h1 {
  background-color: green;
  color: black;
  text-align: center;
  visibility: hidden;
}
h1:after {
  background-color: silver;
  color: yellow;
  content: "This is my great text AFTER";
  display: flex;
  justify-content: center;
  margin-top: -2.3rem;
  visibility: visible;
}
h1:before {
  color: blue;
  content: "However, this is a longer text to show this example BEFORE";
  display: flex;
  justify-content: center;
  margin-bottom: -2.3rem;
  visibility: visible;
}

Note: for different tags you might need different values of rem, this one has been justified for h1 and only on large screens. However with @media you could easily extend this to mobile devices.

A hack how to replace HTML text using CSS

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

iOS 9 (may) force developers to use App Transport Security exclusively. I overheard this somewhere randomly so I don't know whether this is true myself. But I suspect it and have come to this conclusion:

The app running on iOS 9 will (maybe) no longer connect to a Meteor server without SSL.

This means running meteor run ios or meteor run ios-device will (probably?) no longer work.

In the app's info.plist, NSAppTransportSecurity [Dictionary] needs to have a key NSAllowsArbitraryLoads [Boolean] to be set to YES or Meteor needs to use https for its localhost server soon.

Create a temporary table in MySQL with an index from a select

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement

Example :

CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;

Heroku: How to push different local Git branches to Heroku/master

You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

git checkout BRANCH
rake qa deploy

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates

And of course you can make simpler rake tasks if you do something frequently.

Getting unix timestamp from Date()

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class Timeconversion {
    private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH); //Specify your locale

    public long timeConversion(String time) {
        long unixTime = 0;
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); //Specify your timezone
        try {
            unixTime = dateFormat.parse(time).getTime();
            unixTime = unixTime / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return unixTime;
    }
}

add allow_url_fopen to my php.ini using .htaccess

If your host is using suPHP, you can try creating a php.ini file in the same folder as the script and adding:

allow_url_fopen = On

(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script

<?php
echo `id`;
?>

To give the same information, assuming shell_exec is not a disabled function)

Display a tooltip over a button using Windows Forms

Sure, just handle the mousehover event and tell it to display a tool tip. t is a tooltip defined either in the globals or in the constructor using:

ToolTip t = new ToolTip();

then the event handler:

private void control_MouseHover(object sender, EventArgs e)
{
  t.Show("Text", (Control)sender);
}

Padding is invalid and cannot be removed?

I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt

if (Sec.IsFileEncrypted(e.File.FullName))
{
    var stream = Sec.Decrypt(e.File.FullName);
} 
else
{
    // non-encrypted scenario  
}

bash echo number of lines of file given in a bash variable without the file name

An Example Using Your Own Data

You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:

NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")

Explanation: Use Pipes or Redirection to Avoid Filenames in Output

The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:

# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd

# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41

# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41

# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41

As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.

ReactJS and images in public folder

the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info

return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;

Erase the current printed console line

there is a simple trick you can work here but it need preparation before you print, you have to put what ever you wants to print in a variable and then print so you will know the length to remove the string.here is an example.

#include <iostream>
#include <string> //actually this thing is not nessasory in tdm-gcc

using namespace  std;

int main(){

//create string variable

string str="Starting count";

//loop for printing numbers

    for(int i =0;i<=50000;i++){

        //get previous string length and clear it from screen with backspace charactor

        cout << string(str.length(),'\b');

        //create string line

        str="Starting count " +to_string(i);

        //print the new line in same spot

        cout <<str ;
    }

}

Hiding the address bar of a browser (popup)

You might no be able to HIDE it, but if you are looking for the extra space, what I did and seems to work is a very simple thing, the address bar has 60px height, so this is my solution.

@media only screen and (max-width: 1024px){ // only from ipads down
  body{
    padding-bottom: 60px; // push your whole site same height upwards. ;)
  }
}

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

This worked for me too, but with an addition (below).

protected void Page_Load(object sender, EventArgs e) {
  ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
  scriptManager.RegisterPostBackControl(this.btnExcelExport);
  //Further code goes here....
}

I was registering a script on my button to click on another button after its event was finished processing. In order for it to work, I had to remove the other button from the Update Panel (just in case somebody faces the same problem).

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Remember that with the binding redirection

oldVersion="0.0.0.0-6.0.0.0"

You are saying that the old versions of the dll are between version 0.0.0.0 and version 6.0.0.0.

How to run a C# console application with the console hidden

Just write

ProcessStartInfo psi= new ProcessStartInfo("cmd.exe");
......

psi.CreateNoWindow = true;

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

How to set the From email address for mailx command?

On debian where bsd-mailx is installed by default, the -r option does not work. However you can use mailx -s subject [email protected] -- -f [email protected] instead. According to man page, you can specify sendmail options after --.

Newline in JLabel

Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.

http://www.jidesoft.com/articles/StyledLabel.pdf

Owl Carousel Won't Autoplay

This code should work for you

$("#intro").owlCarousel ({

        slideSpeed : 800,
        autoPlay: 6000,
        items : 1,
        stopOnHover : true,
        itemsDesktop : [1199,1],
        itemsDesktopSmall : [979,1],
        itemsTablet :   [768,1],
      });

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Java reverse an int value without using array

public static double reverse(int num)
{
    double num1 = num;
    double ret = 0;
    double counter = 0;

    while (num1 > 1)
    {   
        counter++;
        num1 = num1/10;
    }
    while(counter >= 0)
    {
        int lastdigit = num%10;
        ret += Math.pow(10, counter-1) * lastdigit;
        num = num/10;
        counter--;  
    }
    return ret;
}

Assign output of a program to a variable using a MS batch file

You could use a batch macro for simple capturing of command outputs, a bit like the behaviour of the bash shell.

The usage of the macro is simple and looks like

%$set% VAR=application arg1 arg2

And it works even with pipes

%$set% allDrives="wmic logicaldisk get name /value | findstr "Name""

The macro uses the variable like an array and stores each line in a separate index.
In the sample of %$set% allDrives="wmic logicaldisk there will the following variables created:

allDrives.Len=5
allDrives.Max=4
allDrives[0]=Name=C:
allDrives[1]=Name=D:
allDrives[2]=Name=F:
allDrives[3]=Name=G:
allDrives[4]=Name=Z:
allDrives=<contains the complete text with line feeds>

To use it, it's not important to understand how the macro itself works.

The full example

@echo off
setlocal

call :initMacro

%$set% ipOutput="ipconfig"
call :ShowVariable ipOutput
echo First line is %ipOutput[0]%

echo( 
%$set% driveNames="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveNames

exit /b

:ShowVariable
setlocal EnableDelayedExpansion
for /L %%n in (0 1 !%~1.max!) do (
    echo %%n: !%~1[%%n]!
)
echo(
exit /b

:initMacro
if "!!"=="" (
    echo ERROR: Delayed Expansion must be disabled while defining macros
    (goto) 2>nul
    (goto) 2>nul
)
(set LF=^
%=empty=%
)
(set \n=^^^
%=empty=%
)

set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %\n%
    setlocal EnableDelayedExpansion                                 %\n%
    for /f "tokens=1,* delims== " %%1 in ("!argv!") do (            %\n%
        endlocal                                                    %\n%
        endlocal                                                    %\n%
        set "%%~1.Len=0"                                            %\n%
        set "%%~1="                                                 %\n%
        if "!!"=="" (                                               %\n%
            %= Used if delayed expansion is enabled =%              %\n%
                setlocal DisableDelayedExpansion                    %\n%
                for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                if "!!" NEQ "" (                                    %\n%
                    endlocal                                        %\n%
                    )                                               %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set pathExt=:                                       %\n%
                set path=;                                          %\n%
                set "line=!line:^=^^!"                              %\n%
                set "line=!line:"=q"^""!"                           %\n%
                call set "line=%%line:^!=q""^!%%"                   %\n%
                set "line=!line:q""=^!"                             %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") do (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") Do (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L" !                      %\n%
                        if %%C == 0 (                               %\n%
                            set "%%~1=%%~L" !                       %\n%
                        ) ELSE (                                    %\n%
                            set "%%~1=!%%~1!!LF!%%~L" !             %\n%
                        )                                           %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        ) ELSE (                                                    %\n%
            %= Used if delayed expansion is disabled =%             %\n%
            for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") DO (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") DO (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L"                        %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        )                                                           %\n%
        set /a %%~1.Max=%%~1.Len-1                                  %\n%
)                                                                   %\n%
    ) else setlocal DisableDelayedExpansion^&set argv=

goto :eof

How to get today's Date?

Use this code to easy get Date & Time :

package date.time;

import java.text.SimpleDateFormat;    
import java.util.Date;

public class DateTime {

    public static void main(String[] args) {
        SimpleDateFormat dnt = new SimpleDateFormat("dd/MM/yy :: HH:mm:ss");
        Date date = new Date();
        System.out.println("Today Date & Time at Now :"+dnt.format(date));  
    } 
}

Counting repeated elements in an integer array

 public static void duplicatesInteger(int arr[]){
    Arrays.sort(arr);       
    int count=0;
    Set s=new HashSet();
    for(int i=0;i<=arr.length-1;i++){
        for(int j=i+1;j<=arr.length-1;j++){
            if(arr[i]==arr[j] && s.add(arr[i])){
                count=count+1;              
                                }
        }
        System.out.println(count);
    }
}

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

Function to calculate distance between two coordinates

Try this. It is in VB.net and you need to convert it to Javascript. This function accepts parameters in decimal minutes.

    Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
    long1 = Double.Parse(long1)
    lat1 = Double.Parse(lat1)
    long2 = Double.Parse(long2)
    lat2 = Double.Parse(lat2)

    'conversion to radian
    lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
    long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
    lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
    long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0

    ' use to different earth axis length
    Dim a As Double = 6378137.0        ' Earth Major Axis (WGS84)
    Dim b As Double = 6356752.3142     ' Minor Axis
    Dim f As Double = (a - b) / a        ' "Flattening"
    Dim e As Double = 2.0 * f - f * f      ' "Eccentricity"

    Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
    Dim cos As Double = Math.Cos(lat1)
    Dim x As Double = beta * cos * Math.Cos(long1)
    Dim y As Double = beta * cos * Math.Sin(long1)
    Dim z As Double = beta * (1 - e) * Math.Sin(lat1)

    beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
    cos = Math.Cos(lat2)
    x -= (beta * cos * Math.Cos(long2))
    y -= (beta * cos * Math.Sin(long2))
    z -= (beta * (1 - e) * Math.Sin(lat2))

    Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function

Edit The converted function in javascript

function calculateDistance(lat1, long1, lat2, long2)
  {    

      //radians
      lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;      
      long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;    
      lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;   
      long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;       


      // use to different earth axis length    
      var a = 6378137.0;        // Earth Major Axis (WGS84)    
      var b = 6356752.3142;     // Minor Axis    
      var f = (a-b) / a;        // "Flattening"    
      var e = 2.0*f - f*f;      // "Eccentricity"      

      var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));    
      var cos = Math.cos( lat1 );    
      var x = beta * cos * Math.cos( long1 );    
      var y = beta * cos * Math.sin( long1 );    
      var z = beta * ( 1 - e ) * Math.sin( lat1 );      

      beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));    
      cos = Math.cos( lat2 );   
      x -= (beta * cos * Math.cos( long2 ));    
      y -= (beta * cos * Math.sin( long2 ));    
      z -= (beta * (1 - e) * Math.sin( lat2 ));       

      return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);  
    }

How to filter WooCommerce products by custom attribute

A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.

https://wordpress.org/plugins/woocommerce-products-filter/

This one seems to do exactly what you are after

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

The first row:

$result = mysql_query($query);  

return php db resource.

The second row

while ($row = mysql_fetch_array($result))  

Loops all the records returned by the query.

Use mysql_fetch_assoc instead
In that case the row has key=>value pairs.
In the while just put this:
print_r($row) and you will understand
If you use mysql_fetch_assoc the format of the row will be:

$row["column1_name"] = column1_value;  
$row["column2_name"] = column2_value;  

For this one:

$row = mysql_fetch_assoc($result)  
foreach ($row as $columnName => $columnValue) {  
    ...  
}  

You will get the firs row from the query and you will iterate all columns in the first result of the query.

Reducing the gap between a bullet and text in a list item

You might try using:

li {list-style-position: inside; }

But I can't remember if that adjusts the space, or changes where the space occurs.


Edited

The above doesn't seem to make any substantial difference. There doesn't seem to be any way to decrease the space between the list-style-type marker and the text, though it can be increased using margin-left or text-indent.

Sorry I can't be of more use.


Edited

Just out of curiosity, how about 'faking' the bullet with a background image?

ul {list-style-type: none;
    margin: 0;
    padding: 0;
}

ul li {background: #fff url(path/to/bullet-image.png) 0 50% no-repeat;
       margin: 0;
       padding: 0 0 0 10px; /* change 10px to whatever you feel best suits you */
}

It might allow for more fine-tuning.

difference between primary key and unique key

For an organization or a business, there are so many physical entities (such as people, resources, machines, etc.) and virtual entities (their Tasks, transactions, activities). Typically, business needs to record and process information of those business entities. These business entities are identified within a whole business domain by a Key.

As per RDBMS prospective, Key (a.k.a Candidate Key) is a value or set of values that uniquely identifies an entity.

For a DB-Table, there are so many keys are exist and might be eligible for Primary Key. So that all keys, primary key, unique key, etc are collectively called as Candidate Key. However, DBA selected a key from candidate key for searching records is called Primary key.

Difference between Primary Key and Unique key

1. Behavior: Primary Key is used to identify a row (record) in a table, whereas Unique-key is to prevent duplicate values in a column (with the exception of a null entry).

2. Indexing: By default SQL-engine creates Clustered Index on primary-key if not exists and Non-Clustered Index on Unique-key.

3. Nullability: Primary key does not include Null values, whereas Unique-key can.

4. Existence: A table can have at most one primary key, but can have multiple Unique-key.

5. Modifiability: You can’t change or delete primary values, but Unique-key values can.

For more information and Examples:

http://dotnetauthorities.blogspot.in/2013/11/Microsoft-SQL-Server-Training-Online-Learning-Classes-Integrity-Constraints-PrimaryKey-Unique-Key_27.html

How do you properly return multiple values from a Promise?

Here is how I reckon you should be doing.

splitting the chain

Because both functions will be using amazingData, it makes sense to have them in a dedicated function. I usually do that everytime I want to reuse some data, so it is always present as a function arg.

As your example is running some code, I will suppose it is all declared inside a function. I will call it toto(). Then we will have another function which will run both afterSomething() and afterSomethingElse().

function toto() {
    return somethingAsync()
        .then( tata );
}

You will also notice I added a return statement as it is usually the way to go with Promises - you always return a promise so we can keep chaining if required. Here, somethingAsync() will produce amazingData and it will be available everywhere inside the new function.

Now what this new function will look like typically depends on is processAsync() also asynchronous?

processAsync not asynchronous

No reason to overcomplicate things if processAsync() is not asynchronous. Some old good sequential code would make it.

function tata( amazingData ) {
    var processed = afterSomething( amazingData );
    return afterSomethingElse( amazingData, processed );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}

Note that it does not matter if afterSomethingElse() is doing something async or not. If it does, a promise will be returned and the chain can continue. If it is not, then the result value will be returned. But because the function is called from a then(), the value will be wrapped into a promise anyway (at least in raw Javascript).

processAsync asynchronous

If processAsync() is asynchronous, the code will look slightly different. Here we consider afterSomething() and afterSomethingElse() are not going to be reused anywhere else.

function tata( amazingData ) {
    return afterSomething()
        .then( afterSomethingElse );

    function afterSomething( /* no args */ ) {
        return processAsync( amazingData );
    }
    function afterSomethingElse( processedData ) {
        /* amazingData can be accessed here */
    }
}

Same as before for afterSomethingElse(). It can be asynchronous or not. A promise will be returned, or a value wrapped into a resolved promise.


Your coding style is quite close to what I use to do, that is why I answered even after 2 years. I am not a big fan of having anonymous functions everywhere. I find it hard to read. Even if it is quite common in the community. It is as we replaced the callback-hell by a promise-purgatory.

I also like to keep the name of the functions in the then short. They will only be defined locally anyway. And most of the time they will call another function defined elsewhere - so reusable - to do the job. I even do that for functions with only 1 parameter, so I do not need to get the function in and out when I add/remove a parameter to the function signature.

Eating example

Here is an example:

function goingThroughTheEatingProcess(plenty, of, args, to, match, real, life) {
    return iAmAsync()
        .then(chew)
        .then(swallow);

        function chew(result) {
            return carefullyChewThis(plenty, of, args, "water", "piece of tooth", result);
        }

        function swallow(wine) {
            return nowIsTimeToSwallow(match, real, life, wine);
        }
}

function iAmAsync() {
    return Promise.resolve("mooooore");
}

function carefullyChewThis(plenty, of, args, and, some, more) {
    return true;
}

function nowIsTimeToSwallow(match, real, life, bobool) {
}

Do not focus too much on the Promise.resolve(). It is just a quick way to create a resolved promise. What I try to achieve by this is to have all the code I am running in a single location - just underneath the thens. All the others functions with a more descriptive name are reusable.

The drawback with this technique is that it is defining a lot of functions. But it is a necessary pain I am afraid in order to avoid having anonymous functions all over the place. And what is the risk anyway: a stack overflow? (joke!)


Using arrays or objects as defined in other answers would work too. This one in a way is the answer proposed by Kevin Reid.

You can also use bind() or Promise.all(). Note that they will still require you to split your code.

using bind

If you want to keep your functions reusable but do not really need to keep what is inside the then very short, you can use bind().

function tata( amazingData ) {
    return afterSomething( amazingData )
        .then( afterSomethingElse.bind(null, amazingData) );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}

To keep it simple, bind() will prepend the list of args (except the first one) to the function when it is called.

using Promise.all

In your post you mentionned the use of spread(). I never used the framework you are using, but here is how you should be able to use it.

Some believe Promise.all() is the solution to all problems, so it deserves to be mentioned I guess.

function tata( amazingData ) {
    return Promise.all( [ amazingData, afterSomething( amazingData ) ] )
        .then( afterSomethingElse );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( args ) {
    var amazingData = args[0];
    var processedData = args[1];
}

You can pass data to Promise.all() - note the presence of the array - as long as promises, but make sure none of the promises fail otherwise it will stop processing.

And instead of defining new variables from the args argument, you should be able to use spread() instead of then() for all sort of awesome work.

PostgreSQL: Why psql can't connect to server?

My issue with this error message was in wrong permissions on key and pem certificates, which I have manipulated. What helped me a lot was: /var/log/postgresql/postgresql-9.5-main.log where are all the errors.

How to check string length with JavaScript

The quick and dirty way would be to simple bind to the keyup event.

_x000D_
_x000D_
$('#mytxt').keyup(function(){_x000D_
    $('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
_x000D_
_x000D_

But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup )

How to escape a JSON string containing newline characters using JavaScript?

Like you, I have been looking into several comments and post to replace special escape characters in my JSON which contains html object inside that.

My object is to remove the special characters in JSON object and also render the html which is inside the json object.

Here is what I did and hope its very simple to use.

First I did JSON.stringify my json object and JSON.parse the result.

For eg:

JSON.parse(JSON.stringify(jsonObject));

And it solves my problem and done using Pure Javascript.

Saving a select count(*) value to an integer (SQL Server)

If @myInt is zero it means no rows in the table: it would be NULL if never set at all.

COUNT will always return a row, even for no rows in a table.

Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?

Your count/assign is correct but could be either way:

select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)

However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:

IF NOT EXISTS (SELECT * FROM myTable)

sprintf like functionality in Python

If you want something like the python3 print function but to a string:

def sprint(*args, **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, file=sio)
    return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"

or without the '\n' at the end:

def sprint(*args, end='', **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, end=end, file=sio)
    return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

Convert HH:MM:SS string to seconds only in javascript

Javascript's static method Date.UTC() does the trick:

alert(getSeconds('00:22:17'));

function getSeconds(time)
{
    var ts = time.split(':');
    return Date.UTC(1970, 0, 1, ts[0], ts[1], ts[2]) / 1000;
}

How to add hyperlink in JLabel?

The following code requires JHyperLink to be added to your build path.

JHyperlink stackOverflow = new JHyperlink("Click HERE!",
                "https://www.stackoverflow.com/");

JComponent[] messageComponents = new JComponent[] { stackOverflow };

JOptionPane.showMessageDialog(null, messageComponents, "StackOverflow",
                JOptionPane.PLAIN_MESSAGE);

Note that you can fill the JComponent array with more Swing components.

Result:

How to start IIS Express Manually

Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on

https://jexusmanager.com

Jexus Manager for IIS Express

Start a site and the process will be launched for you.

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

Here is the code - The code is in asp.net core 2.0 but should work in above versions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace UnityAssets.Website.Services
{
    public class EmailSender : IEmailSender
    {
        public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
            email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = htmlMessage
            };

            email.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //provider specific settings
                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }
}

Easy way to get a test file into JUnit

If you need to actually get a File object, you could do the following:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

How to Add Stacktrace or debug Option when Building Android Studio Project

You can use GUI to add these gradle command line flags from

File > Settings > Build, Execution, Deployment > Compiler

For MacOS user, it's here

Android Studio > Preferences > Build, Execution, Deployment > Compiler

like this (add --stacktrace or --debug)

enter image description here

Note that the screenshot is from before 0.8.10, the option is no longer in the Compiler > Gradle section, it's now in a separate section named Compiler (Gradle-based Android Project)

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

How to run C program on Mac OS X using Terminal?

On Mac gcc is installed by default in /usr/local/bin

To run C:

gcc -o tutor tutor.c 

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

How can I create an array with key value pairs?

$data =array();
$data['user_code']  = 'JOY' ;
$data['user_name']  = 'JOY' ;
$data['user_email'] = '[email protected]';

Migration: Cannot add foreign key constraint

make sure your foreing column is over wide rage of foreing key column

I means your foreingkey (in second table) must be same type of your ponter pricipal key (in first table)

your pointer principal key must be add unsigned method, let me show:

on your FIRST migration table:

$table->increments('column_name'); //is INTEGER and UNSIGNED

on your SECOND migration table:

$table->integer('column_forein_name')->unsigned(); //this must be INTEGER and UNSIGNED
$table->foreign('column_forein_name')->references('column_name')->on('first_table_name');

ANOTHER EXAMPLE TO SEE DIFFERENCE

on your FIRST migration table:

$table->mediumIncrements('column_name'); //is MEDIUM-INTEGER and UNSIGNED

on your SECOND migration table:

$table->mediumInteger('column_forein_name')->unsigned(); //this must be MEDIUM-INTEGER and UNSIGNED
$table->foreign('column_forein_name')->references('column_name')->on('first_table_name');

SEE MYSQL NUMERIC TYPES TABLE RANGES

MongoDB inserts float when trying to insert integer

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

The Number Data Type

Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

Child with max-height: 100% overflows parent

http://jsfiddle.net/mpalpha/71Lhcb5q/

_x000D_
_x000D_
.container {  
display: flex;
  background: blue; 
  padding: 10px; 
  max-height: 200px; 
  max-width: 200px; 
}

img { 
 object-fit: contain;
  max-height: 100%; 
  max-width: 100%; 
}
_x000D_
<div class="container">
  <img src="http://placekitten.com/400/500" />
</div>
_x000D_
_x000D_
_x000D_

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

In my case it turns out my
new server was running MySQL 5.5,
old server was running MySQL 5.6.
So I got this error when trying to import the .sql file I'd exported from my old server.

MySQL 5.5 does not support utf8mb4_unicode_520_ci, but
MySQL 5.6 does.

Updating to MySQL 5.6 on the new server solved collation the error !

If you want to retain MySQL 5.5, you can:
- make a copy of your exported .sql file
- replace instances of utf8mb4unicode520_ci and utf8mb4_unicode_520_ci
...with utf8mb4_unicode_ci
- import your updated .sql file.

How can I add new dimensions to a Numpy array?

There is no structure in numpy that allows you to append more data later.

Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.

So you will have two kinds of solutions:

  1. Pre-allocate the memory for the numpy array and fill in the values, like in JoshAdel's answer, or
  2. Keep your data in a normal python list until it's actually needed to put them all together (see below)

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

Passing parameters to click() & bind() event in jquery?

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

PHP cURL error code 60

Use this certificate root certificate bundle:

https://curl.haxx.se/ca/cacert.pem

Copy this certificate bundle on your disk. And use this on php.ini

curl.cainfo = "path_to_cert\cacert.pem"

Adding blank spaces to layout

Below is the simple way to create blank line with line size. Here we can adjust size of the blank line. Try this one.

           <TextView
            android:id="@id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="5dp"/>

Execute SQLite script

For those using PowerShell

PS C:\> Get-Content create.sql -Raw | sqlite3 auction.db

How to build and run Maven projects after importing into Eclipse IDE

Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification. Maven Project Update based on changes on pom.xml

iCheck check if checkbox is checked

$('input').on('ifChanged', function(event) {
             if($(".checkbox").is(":checked")) {
                $value = $(this).val();
             }

             else if($(".checkbox").is(":not(:checked)")) {
                $value= $(this).val();
             }
        });

Is "else if" faster than "switch() case"?

Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.

I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.

Waiting till the async task finish its work

Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.

You've got pretty much 2 options here;

  1. You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.

  2. If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

forcing web-site to show in landscape mode only

Try this It may be more appropriate for you

_x000D_
_x000D_
#container { display:block; }_x000D_
@media only screen and (orientation:portrait){_x000D_
  #container {  _x000D_
    height: 100vw;_x000D_
    -webkit-transform: rotate(90deg);_x000D_
    -moz-transform: rotate(90deg);_x000D_
    -o-transform: rotate(90deg);_x000D_
    -ms-transform: rotate(90deg);_x000D_
    transform: rotate(90deg);_x000D_
  }_x000D_
}_x000D_
@media only screen and (orientation:landscape){_x000D_
  #container {  _x000D_
     -webkit-transform: rotate(0deg);_x000D_
     -moz-transform: rotate(0deg);_x000D_
     -o-transform: rotate(0deg);_x000D_
     -ms-transform: rotate(0deg);_x000D_
     transform: rotate(0deg);_x000D_
  }_x000D_
}
_x000D_
<div id="container">_x000D_
    <!-- your html for your website -->_x000D_
    <H1>This text is always in Landscape Mode</H1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will automatically manage even rotation.

How to get certain commit from GitHub project

If you want to go with any certain commit or want to code of any certain commit then you can use below command:

git checkout <BRANCH_NAME>
git reset --hard  <commit ID which code you want>
git push --force

Example:

 git reset --hard fbee9dd 
 git push --force

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

set -e
fail () {
    touch .failure
}
expect () {
    wait
    if [ -f .failure ]; then
        rm -f .failure
        exit 1
    fi
}

sleep 2 || fail &
sleep 2 && false || fail &
sleep 2 || fail
expect

The set -e at top makes your script stop on failure.

expect will return 1 if any subjob failed.

How to do sed like text replace with python?

If you really want to use a sed command without installing a new Python module, you could simply do the following:

import subprocess
subprocess.call("sed command")

HTML 5 input type="number" element for floating point numbers on Chrome

Try this

_x000D_
_x000D_
<input onkeypress='return event.charCode >= 48 && _x000D_
                          event.charCode <= 57 || _x000D_
                          event.charCode == 46'>
_x000D_
_x000D_
_x000D_

How to install Python MySQLdb module using pip?

actually, follow @Nick T's answer doesn't work for me, i try apt-get install python-mysqldb work for me

root@2fb0da64a933:/home/test_scrapy# apt-get install python-mysqldb
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libmariadbclient18 mysql-common
Suggested packages:
  default-mysql-server | virtual-mysql-server python-egenix-mxdatetime python-mysqldb-dbg
The following NEW packages will be installed:
  libmariadbclient18 mysql-common python-mysqldb
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 843 kB of archives.
After this operation, 4611 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 mysql-common all 5.8+1.0.2 [5608 B]
Get:2 http://deb.debian.org/debian stretch/main amd64 libmariadbclient18 amd64 10.1.38-0+deb9u1 [785 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 python-mysqldb amd64 1.3.7-1.1 [52.1 kB]                    
Fetched 843 kB in 23s (35.8 kB/s)                                                                                 
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package mysql-common.
(Reading database ... 13223 files and directories currently installed.)
Preparing to unpack .../mysql-common_5.8+1.0.2_all.deb ...
Unpacking mysql-common (5.8+1.0.2) ...
Selecting previously unselected package libmariadbclient18:amd64.
Preparing to unpack .../libmariadbclient18_10.1.38-0+deb9u1_amd64.deb ...
Unpacking libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Selecting previously unselected package python-mysqldb.
Preparing to unpack .../python-mysqldb_1.3.7-1.1_amd64.deb ...
Unpacking python-mysqldb (1.3.7-1.1) ...
Setting up mysql-common (5.8+1.0.2) ...
update-alternatives: using /etc/mysql/my.cnf.fallback to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Setting up libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Processing triggers for libc-bin (2.24-11+deb9u3) ...
Setting up python-mysqldb (1.3.7-1.1) ...
root@2fb0da64a933:/home/test_scrapy# python 
Python 2.7.13 (default, Nov 24 2017, 17:33:09) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> 

Insert into C# with SQLCommand

Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;

 using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
 {
            connection.Open();
            string sql =  "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
            using(SqlCommand cmd = new SqlCommand(sql,connection)) 
            {
                  cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;  
                  cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
                  cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
                  cmd.CommandType = CommandType.Text;
                  cmd.ExecuteNonQuery(); 
            }
 }

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

Thread.Sleep(5000);

This did help me but InterruptedException exception needs to be taken care of. So better surround it with try and catch:

try {
    Thread.Sleep(5000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

OR

Add throws declaration:

public class myClass {
    public static void main(String[] args) throws InterruptedException
    { ... }

I would prefer the second one since one can then use sleep() as many times as it wants and avoid the repetition of try and catch block every time wherever sleep() has been used.

Removing Data From ElasticSearch

The documentation (or The Definitive Guide) says, that you can also use the next query to delete all indices:

curl -XDELETE 'http://localhost:9200/*'

And there's an important note:

For some, the ability to delete all your data with a single command is a very scary prospect. If you want to eliminate the possibility of an accidental mass-deletion, you can set the following to true in your elasticsearch.yml:

action.destructive_requires_name: true

Difference between using bean id and name in Spring configuration file

Both id and name are bean identifiers in Spring IOC container/ApplicationContecxt. The id attribute lets you specify exactly one id but using name attribute you can give alias name to that bean.

You can check the spring doc here.

Python: Get HTTP headers from urllib2.urlopen call?

urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).

iOS 7's blurred overlay effect using CSS?

This might help you!!

This Dynamically changes the background just IOS does

.myBox {
  width: 750px;
  height: 500px;
  border: rgba(0, 0, 0, 0.5) 1px solid;
  background-color: #ffffff;
}

.blurBg {
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.blurBg img {
  -webkit-filter: blur(50px);
  margin-top: -150px;
  margin-left: -150px;
  width: 150%;
  opacity: 0.6;
}

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

How does tuple comparison work in Python?

The python 2.5 documentation explains it well.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

Unfortunately that page seems to have disappeared in the documentation for more recent versions.

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

Exception 'open failed: EACCES (Permission denied)' on Android

I'm experiencing the same. What I found is that if you go to Settings -> Application Manager -> Your App -> Permissions -> Enable Storage, it solves the issue.

How Should I Set Default Python Version In Windows?

This worked for me:

Go to

Control Panel\System and Security\System

select

Advanced system settings from the left panel
from Advanced tab click on Environment Variables

In the System variables section search for (create if doesn't exist)

PYTHONPATH

and set

C:\Python27\;C:\Python27\Scripts;

or your desired version

You need to restart CMD.

In case it still doesn't work you might want to leave in the PATH variable only your desired version.

Resizing SVG in html?

Here is an example of getting the bounds using svg.getBox(): https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44

At the end you get numbers that you can plug into the svg to set the viewbox properly. Then use any css on the parent div and you're done.

 // get all SVG objects in the DOM
 var svgs = document.getElementsByTagName("svg");
 var svg = svgs[0],
    box = svg.getBBox(), // <- get the visual boundary required to view all children
    viewBox = [box.x, box.y, box.width, box.height].join(" ");

    // set viewable area based on value above
    svg.setAttribute("viewBox", viewBox);

How do you pass a function as a parameter in C?

You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.

change pgsql port

You can also change the port when starting up:

$ pg_ctl -o "-F -p 5433" start

Or

$ postgres -p 5433

More about this in the manual.

How to output MySQL query results in CSV format?

This is simple, and it works on anything without needing batch mode or output files:

select concat_ws(',',
    concat('"', replace(field1, '"', '""'), '"'),
    concat('"', replace(field2, '"', '""'), '"'),
    concat('"', replace(field3, '"', '""'), '"'))

from your_table where etc;

Explanation:

  1. Replace " with "" in each field --> replace(field1, '"', '""')
  2. Surround each result in quotation marks --> concat('"', result1, '"')
  3. Place a comma between each quoted result --> concat_ws(',', quoted1, quoted2, ...)

That's it!

How to set a parameter in a HttpServletRequest?

Sorry, but why not use the following construction:

request.getParameterMap().put(parameterName, new String[] {parameterValue});

Resolve Javascript Promise outside function scope

You can wrap the Promise in a class.

class Deferred {
    constructor(handler) {
        this.promise = new Promise((resolve, reject) => {
            this.reject = reject;
            this.resolve = resolve;
            handler(resolve, reject);
        });

        this.promise.resolve = this.resolve;
        this.promise.reject = this.reject;

        return this.promise;
    }
    promise;
    resolve;
    reject;
}

// How to use.
const promise = new Deferred((resolve, reject) => {
  // Use like normal Promise.
});

promise.resolve(); // Resolve from any context.

How to put more than 1000 values into an Oracle IN clause

I am almost sure you can split values across multiple INs using OR:

select * from table1 where ID in (1,2,3,4,...,1000) or 
ID in (1001,1002,...,2000)

Avoid dropdown menu close on click inside

I've found none of the solutions worked as I would like using default bootstrap nav. Here is my solution to this problem:

       $(document).on('hide.bs.dropdown', function (e) {
        if ($(e.currentTarget.activeElement).hasClass('dropdown-toggle')) {
          $(e.relatedTarget).parent().removeClass('open');
          return true;
        }
        return false;
       });

You have not concluded your merge (MERGE_HEAD exists)

I resolved conflicts and also committed but still getting this error message on git push

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

I did these steps to resolve error:

rm -rf .git/MERGE*
git pull origin branch_name 
git push origin branch_name

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

Delay/Wait in a test case of Xcode UI testing

Additionally, you can just sleep:

sleep(10)

Since the UITests run in another process, this works. I don’t know how advisable it is, but it works.

Create space at the beginning of a UITextField

* Extending UITextField in Swift 5 *

import UIKit

@IBDesignable
extension UITextField {

    @IBInspectable var paddingLeftCustom: CGFloat {
        get {
            return leftView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            leftView = paddingView
            leftViewMode = .always
        }
    }

    @IBInspectable var paddingRightCustom: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always
        }
    }

}

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

System.web.mvc missing

Get the latest version of MVC3 via NuGet. Open your project in Dev Studio. Open the Package Manager Console tab at the bottom of Dev Studio. Then use this command:

PM> Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1

If you click the tab key after "-Version" you will get a list of all of the available versions.

If you have an old version of NuGet you may get an error indicating you have to upgrade it. If so, open Tools->Extension Manager to install the latest version of NuGet. Note, you will need to run Dev Studio as Administrator before you can install NuGet.

Installing MVC3 should update Web.config in your project.

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.1" newVersion="3.0.0.1" />
  </dependentAssembly>
</assemblyBinding>

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

Creating and appending text to txt file in VB.NET

Why not just use the following simple call (with any exception handling added)?

File.AppendAllText(strFile, "Start Error Log for today")


EDITED ANSWER
This should answer the question fully!

If File.Exists(strFile)
  File.AppendAllText(strFile, String.Format("Error Message in  Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
  File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in  Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

here is another solution I started using after being fed up with the copy and paste issue:

  1. Download MRemote (for pc). this is an alternative to remote desktop manager. You can use remote desktop manager if you like.
  2. Change the VMNet settings to NAT or add another VMNet and set it to NAT.
  3. Configure the vm ip address with an ip in the same network as you host machine. if you want to keep networks separated use a second vmnet and set it's ip address in the same network as the host. that's what I use.
  4. Enable RDP connections on the guest (I only use windows guests)
  5. Create a batch file with this command. add your guest machines:

vmrun start D:\VM\MySuperVM1\vm1.vmx nogui vmrun start D:\VM\MySuperVM2\vm2.vmx nogui

save the file to startmyvms.cmd

create another batch file and add your vms

vmrun stop D:\VM\MySuperVM1\vm1.vmx nogui vmrun stop D:\VM\MySuperVM2\vm2.vmx nogui

save the file to stopmyvms.cmd

  1. Open Mremote go to tools => External tools Add external tool => filename will be the startmyvms.cmd file Add external tool => filename will be the stopmyvms.cmd file So to start working with your vms:

  2. Create you connections to your VMs in mremote

Now to work with your vm 1. You open mremote 2. You go to tools => external tools 3. You click the startmyvms tool when you're done 1. You go to tools => external tools 2. You click the stopmyvms external tool

you could add the vmrun start on the connection setting => external tool before connection and add the vmrun stop in the connection settings => external tool after

Voilà !

?: ?? Operators Instead Of IF|ELSE

The ternary operator (?:) is not designed for control flow, it's only designed for conditional assignment. If you need to control the flow of your program, use a control structure, such as if/else.

C# list.Orderby descending

list.OrderByDescending();

works for me.

How to turn on line numbers in IDLE?

As @StahlRat already answered. I would like to add another method for it. There is extension pack for Python Default idle editor Python Extensions Package.

Single Line Nested For Loops

You might be interested in itertools.product, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B) yields all values of the form (a, b), where the a values come from A and the b values come from B. For example:

import itertools

A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]

print [a + b for a, b in itertools.product(A, B)]

This prints:

[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]

Notice how the final argument passed to itertools.product is the "inner" one. Generally, itertools.product(a0, a1, ... an) is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

What is a Maven artifact?

I know this is an ancient thread but I wanted to add a few nuances.

There are Maven artifacts, repository manager artifacts and then there are Maven Artifacts.

A Maven artifact is just as other commenters/responders say: it is a thing that is spat out by building a Maven project. That could be a .jar file, or a .war file, or a .zip file, or a .dll, or what have you.

A repository manager artifact is a thing that is, well, managed by a repository manager. A repository manager is basically a highly performant naming service for software executables and libraries. A repository manager doesn't care where its artifacts come from (maybe they came from a Maven build, or a local file, or an Ant build, or a by-hand compilation...).

A Maven Artifact is a Java class that represents the kind of "name" that gets dereferenced by a repository manager into a repository manager artifact. When used in this sense, an Artifact is just a glorified name made up of such parts as groupId, artifactId, version, scope, classifier and so on.

To put it all together:

  • Your Maven project probably depends on several Artifacts by way of its <dependency> elements.
  • Maven interacts with a repository manager to resolve those Artifacts into files by instructing the repository manager to send it some repository manager artifacts that correspond to the internal Artifacts.
  • Finally, after resolution, Maven builds your project and produces a Maven artifact. You may choose to "turn this into" a repository manager artifact by, in turn, using whatever tool you like, sending it to the repository manager with enough coordinating information that other people can find it when they ask the repository manager for it.

Hope that helps.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a fast way to encode the array, the array shape and the array dtype:

def numpy_to_bytes(arr: np.array) -> str:
    arr_dtype = bytearray(str(arr.dtype), 'utf-8')
    arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
    sep = bytearray('|', 'utf-8')
    arr_bytes = arr.ravel().tobytes()
    to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
    return to_return

def bytes_to_numpy(serialized_arr: str) -> np.array:
    sep = '|'.encode('utf-8')
    i_0 = serialized_arr.find(sep)
    i_1 = serialized_arr.find(sep, i_0 + 1)
    arr_dtype = serialized_arr[:i_0].decode('utf-8')
    arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
    arr_str = serialized_arr[i_1 + 1:]
    arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
    return arr

To use the functions:

a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype

How to get a file directory path from file path?

If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.

if [ -h $file ]
then
 base=$(dirname $(readlink $file))
else
 base=$(dirname $file)
fi

How to "crop" a rectangular image into a square with CSS?

I had a similar issue and could not "compromise" with background images. I came up with this.

<div class="container">
    <img src="http://lorempixel.com/800x600/nature">
</div>

.container {
    position: relative;
    width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
    border: 2px solid #fff; /* just to separate the images */
    overflow: hidden; /* "crop" the image */
    background: #000; /* incase the image is wider than tall/taller than wide */
}

.container img {
    position: absolute;
    display: block;
    height: 100%; /* all images at least fill the height */
    top: 50%; /* top, left, transform trick to vertically and horizontally center image */
    left: 50%;
    transform: translate3d(-50%,-50%,0);
}

//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});

Hope this helps!

Example: https://jsfiddle.net/cfbuwxmr/1/

In Python, can I call the main() of an imported module?

It's just a function. Import it and call it:

import myModule

myModule.main()

If you need to parse arguments, you have two options:

  • Parse them in main(), but pass in sys.argv as a parameter (all code below in the same module myModule):

    def main(args):
        # parse arguments using optparse or argparse or what have you
    
    if __name__ == '__main__':
        import sys
        main(sys.argv[1:])
    

    Now you can import and call myModule.main(['arg1', 'arg2', 'arg3']) from other another module.

  • Have main() accept parameters that are already parsed (again all code in the myModule module):

    def main(foo, bar, baz='spam'):
        # run with already parsed arguments
    
    if __name__ == '__main__':
        import sys
        # parse sys.argv[1:] using optparse or argparse or what have you
        main(foovalue, barvalue, **dictofoptions)
    

    and import and call myModule.main(foovalue, barvalue, baz='ham') elsewhere and passing in python arguments as needed.

The trick here is to detect when your module is being used as a script; when you run a python file as the main script (python filename.py) no import statement is being used, so python calls that module "__main__". But if that same filename.py code is treated as a module (import filename), then python uses that as the module name instead. In both cases the variable __name__ is set, and testing against that tells you how your code was run.

How do I select last 5 rows in a table without sorting?

In SQL Server, it does not seem possible without using ordering in the query. This is what I have used.

SELECT *
FROM
(
    SELECT TOP 5 *
    FROM [MyTable]
    ORDER BY Id DESC /*Primary Key*/
) AS T
ORDER BY T.Id ASC; /*Primary Key*/

Generate Java class from JSON?

If you're using Jackson (the most popular library there), try

https://github.com/astav/JsonToJava

Its open source (last updated on Jun 7, 2013 as of year 2020) and anyone should be able to contribute.

Summary

A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generates the necessary java data structures.

It encourages teams to think in Json first, before writing actual code.

Features

  • Can generate classes for an arbitrarily complex hierarchy (recursively)
  • Can read your existing Java classes and if it can deserialize into those structures, will do so
  • Will prompt for user input when ambiguous cases exist

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

Is there any way to call a function periodically in JavaScript?

You will want to have a look at setInterval() and setTimeout().

Here is a decent tutorial article.

How to scroll to specific item using jQuery?

Scroll element to center of container

To bring the element to the center of the container.

DEMO on CODEPEN

JS

function scrollToCenter() {
  var container = $('.container'),
    scrollTo = $('.5');

  container.animate({
    //scrolls to center
    scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
  });
}

HTML

<div class="container">
   <div class="1">
    1
  </div>
  <div class="2">
    2
  </div>
  <div class="3">
    3
  </div>
  <div class="4">
    4
  </div>
  <div class="5">
    5
  </div>
  <div class="6">
    6
  </div>
  <div class="7">
    7
  </div>
  <div class="8">
    8
  </div>
  <div class="9">
    9
  </div>
  <div class="10">
    10
  </div>


</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
  Scroll
</button>

css

.container {
  height: 60px;
  overflow-y: scroll;
  width 60px;
  background-color: white;
}

It is not exact to the center but you will not recognice it on larger bigger elements.

package javax.mail and javax.mail.internet do not exist

It might be that you do not have the necessary .jar files that give you access to the Java Mail API. These can be downloaded from here.

Finding all positions of substring in a larger string in C#

Without Regex, using string comparison type:

string search = "123aa456AA789bb9991AACAA";
string pattern = "AA";
Enumerable.Range(0, search.Length)
   .Select(index => { return new { Index = index, Length = (index + pattern.Length) > search.Length ? search.Length - index : pattern.Length }; })
   .Where(searchbit => searchbit.Length == pattern.Length && pattern.Equals(search.Substring(searchbit.Index, searchbit.Length),StringComparison.OrdinalIgnoreCase))
   .Select(searchbit => searchbit.Index)

This returns {3,8,19,22}. Empty pattern would match all positions.

For multiple patterns:

string search = "123aa456AA789bb9991AACAA";
string[] patterns = new string[] { "aa", "99" };
patterns.SelectMany(pattern => Enumerable.Range(0, search.Length)
   .Select(index => { return new { Index = index, Length = (index + pattern.Length) > search.Length ? search.Length - index : pattern.Length }; })
   .Where(searchbit => searchbit.Length == pattern.Length && pattern.Equals(search.Substring(searchbit.Index, searchbit.Length), StringComparison.OrdinalIgnoreCase))
   .Select(searchbit => searchbit.Index))

This returns {3, 8, 19, 22, 15, 16}

Jenkins: Is there any way to cleanup Jenkins workspace?

If you want to just remove one dir (or file) you can use Groovy and Manage Jenkins ? Scripts Console run a script which removes it.

For example, you can look at the files with:

dh = new File('./bitnami/jenkins/jenkins_home/workspace/jobname/folder')
dh.eachFile {
  println(it)
}

And then, when you have the folder you want to delete in dh, you could simply append the next code:

dh.deleteDir()

And it will be deleted.

Note: The path shown in the example is for a Bitnami Jenkins installation, yours could be different.

Good Linux (Ubuntu) SVN client

If TortoiseSVN is really ingrained you could try using it through WINE? Though I haven't tried it.

Failing that, I've found Eclipse with Subversive to be pretty good.

Get epoch for a specific date using Javascript

Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

Explore more at: Date.parse()

How to send parameters from a notification-click to an activity?

After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.

like this:

   Intent notificationIntent = new Intent(Main.this, Main.class);
   notificationIntent.putExtra("sport_id", "sport"+id);
   notificationIntent.putExtra("game_url", "gameURL"+id);

   notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime()))); 

I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...

Is it not possible to define multiple constructors in Python?

The easiest way is through keyword arguments:

class City():
  def __init__(self, city=None):
    pass

someCity = City(city="Berlin")

This is pretty basic stuff. Maybe look at the Python documentation?

What exactly does big ? notation represent?

It means that the algorithm is both big-O and big-Omega in the given function.

For example, if it is ?(n), then there is some constant k, such that your function (run-time, whatever), is larger than n*k for sufficiently large n, and some other constant K such that your function is smaller than n*K for sufficiently large n.

In other words, for sufficiently large n, it is sandwiched between two linear functions :

For k < K and n sufficiently large, n*k < f(n) < n*K

How to set a ripple effect on textview or imageview on Android?

addition to above answers is adding focusable to avoid UI editor's warning

android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:focusable="true"

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

Access: Move to next record until EOF

If (Not IsNull(Me.id.Value)) Then
DoCmd.GoToRecord , , acNext
End If

Hi, you need to put this in form activate, and have an id field named id...

this way it passes until it reaches the one without id (AKA new one)...

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here