Programs & Examples On #Tclientsocket

close fxml window by code, javafx

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)

How to change css property using javascript

var hello = $('.right') // or var hello = document.getElementByClassName('right')
var bye = $('.right1')
hello.onmouseover = function()
{
    bye.style.visibility = 'visible'
}
hello.onmouseout = function()
{
    bye.style.visibility = 'hidden'
}

How do I make bootstrap table rows clickable?

<tr height="70" onclick="location.href='<%=site_adres2 & urun_adres%>'"
    style="cursor:pointer;">

Date constructor returns NaN in IE, but works in Firefox and Chrome

Try out using getDate feature of datepicker.

$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(Child) child:Child;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();
  }

  (...)
}

How to display both icon and title of action inside ActionBar?

What worked for me was using 'always|withText'. If you have many menus, consider using 'ifRoom' instead of 'always'.

<item android:id="@id/resource_name"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

Turns out I didn't enable openssl in my php.ini so when I created my new project with composer it was installed from source. I changed that and ran

composer update

now the vendor folder was created.

How to make an AlertDialog in Flutter?

showAlertDialog(BuildContext context, String message, String heading,
      String buttonAcceptTitle, String buttonCancelTitle) {
    // set up the buttons
    Widget cancelButton = FlatButton(
      child: Text(buttonCancelTitle),
      onPressed: () {},
    );
    Widget continueButton = FlatButton(
      child: Text(buttonAcceptTitle),
      onPressed: () {

      },
    );

    // set up the AlertDialog
    AlertDialog alert = AlertDialog(
      title: Text(heading),
      content: Text(message),
      actions: [
        cancelButton,
        continueButton,
      ],
    );

    // show the dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

called like:

showAlertDialog(context, 'Are you sure you want to delete?', "AppName" , "Ok", "Cancel");

SQL - using alias in Group By

I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY to create the alias. You then use it in the GROUP BY clause, like so:

SELECT 
 itemName as ItemName,
 FirstLetter,
 Count(itemName)
FROM table1
CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
GROUP BY itemName, FirstLetter

Detecting arrow key presses in JavaScript

If you use jquery then you can also do like this,

 $(document).on("keydown", '.class_name', function (event) {
    if (event.keyCode == 37) {
        console.log('left arrow pressed');
    }
    if (event.keyCode == 38) {
        console.log('up arrow pressed');
    }
    if (event.keyCode == 39) {
        console.log('right arrow pressed');
    }
    if (event.keyCode == 40) {
        console.log('down arrow pressed');
    }
 });

Best way to work with transactions in MS SQL Server Management Studio

I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.

Example below:

USE AdventureWorks;
GO
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute
BEGIN TRANSACTION;

BEGIN TRY
     IF @TEST= 1
        BEGIN
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
        END    
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;

     IF @TEST= 1
        BEGIN
            SELECT *FROM Production.Product
                WHERE ProductID = 980;
            IF @@TRANCOUNT > 0
                ROLLBACK TRANSACTION;
        END    
END TRY

BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0 AND @TEST = 0
    COMMIT TRANSACTION;
GO

Git SSH error: "Connect to host: Bad file number"

Creating the config file to use port 443 didn't work for me. Finally I tried to turn off my wifi connection, turn it on again and the problem disappeared. Weird. Silly solution but it may help someone :)

How do you return the column names of a table?

I use

SELECT st.NAME, sc.NAME, sc.system_type_id
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%Tablename%'

java: use StringBuilder to insert at the beginning

As an alternative solution you can use a LIFO structure (like a stack) to store all the strings and when you are done just take them all out and put them into the StringBuilder. It naturally reverses the order of the items (strings) placed in it.

Stack<String> textStack = new Stack<String>();
// push the strings to the stack
while(!isReadingTextDone()) {
    String text = readText();
    textStack.push(text);
}
// pop the strings and add to the text builder
String builder = new StringBuilder(); 
while (!textStack.empty()) {
      builder.append(textStack.pop());
}
// get the final string
String finalText =  builder.toString();

How to read the Stock CPU Usage data

So far this has been the most helpful source of information regarding this I could find. Apparently the numbers do NOT reperesent load average in %: http://forum.xda-developers.com/showthread.php?t=1495763

Removing duplicates from a String in Java

String output = "";
    HashMap<Character,Boolean> map = new HashMap<>();
    for(int i=0;i<str.length();i++){
        char ch = str.charAt(i);
        if (!map.containsKey(ch)){
            output += ch;
            map.put(ch,true);
        }
    }
    return output;

This is the simple approach using HashMap in Java in one pass .

Time Complexity : O(n)

Space Complexity : O(n)

Difference between OData and REST web services

REST is a generic design technique used to describe how a web service can be accessed. Using REST you can make http requests to get data. If you try it in your browser it would be just like going to a website except instead of returning a web page you would get back XML. Some services will also return data in JSON format which is easier to use with Javascript.

OData is a specific technology that exposes data through REST.

If you want to sum it up real quick, think of it as:

  • REST - design pattern
  • OData - enabling technology

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

For IntelHAXM to install you have to activate Intel Virtual Technology.

To activate it, you have to restart your PC and go to BIOS. There is an option called Intel Virtual Technology that you have to enable to activate it.

After enabling it, reinstall IntelHAXM. That should solve the problem.

How does Python's super() work with multiple inheritance?

I understand this doesn't directly answer the super() question, but I feel it's relevant enough to share.

There is also a way to directly call each inherited class:


class First(object):
    def __init__(self):
        print '1'

class Second(object):
    def __init__(self):
        print '2'

class Third(First, Second):
    def __init__(self):
        Second.__init__(self)

Just note that if you do it this way, you'll have to call each manually as I'm pretty sure First's __init__() won't be called.

Find out how much memory is being used by an object in Python

There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).

There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.

You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).

How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

How to get a list of all files that changed between two Git commits?

If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type

git status -- it will show the files with changes

then if you want to know what changes are to be made it can be checked in ways ,

git diff -- will show all the changes in all files

it is good only when only one file is modified

and if you want to check particular file then use

git diff

Remove the title bar in Windows Forms

You can set the Property FormBorderStyle to none in the designer, or in code:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

Python unittest - opposite of assertRaises?

If you pass an Exception class to assertRaises(), a context manager is provided. This can improve the readability of your tests:

# raise exception if Application created with bad data
with self.assertRaises(pySourceAidExceptions.PathIsNotAValidOne):
    application = Application("abcdef", "")

This allows you to test error cases in your code.

In this case, you are testing the PathIsNotAValidOne is raised when you pass invalid parameters to the Application constructor.

Under which circumstances textAlign property works in Flutter?

In Colum widget Text alignment will be centred automatically, so use crossAxisAlignment: CrossAxisAlignment.start to align start.

Column( 
    crossAxisAlignment: CrossAxisAlignment.start, 
    children: <Widget>[ 
    Text(""),
    Text(""),
    ]);

Bootstrap 3 - How to load content in modal body via AJAX?

In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3 Demo
Bootstrap 4 Demo

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

Do we have router.reload in vue-router?

The simplest solution is to add a :key attribute to :

<router-view :key="$route.fullPath"></router-view>

This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.

How to find and replace string?

Yes: replace_all is one of the boost string algorithms:

Although it's not a standard library, it has a few things on the standard library:

  1. More natural notation based on ranges rather than iterator pairs. This is nice because you can nest string manipulations (e.g., replace_all nested inside a trim). That's a bit more involved for the standard library functions.
  2. Completeness. This isn't hard to be 'better' at; the standard library is fairly spartan. For example, the boost string algorithms give you explicit control over how string manipulations are performed (i.e., in place or through a copy).

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

You can also use this code to extend ObservableCollection:

public static class ObservableCollectionExtend
{
    public static void AddRange<TSource>(this ObservableCollection<TSource> source, IEnumerable<TSource> items)
    {
        foreach (var item in items)
        {
            source.Add(item);
        }
    }
}

Then you don't need to change class in existing code.

Could not commit JPA transaction: Transaction marked as rollbackOnly

Could not commit JPA transaction: Transaction marked as rollbackOnly

This exception occurs when you invoke nested methods/services also marked as @Transactional. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.

Suppose we have two Spring services: Service1 and Service2. From our program we call Service1.method1() which in turn calls Service2.method2():

class Service1 {
    @Transactional
    public void method1() {
        try {
            ...
            service2.method2();
            ...
        } catch (Exception e) {
            ...
        }
    }
}

class Service2 {
    @Transactional
    public void method2() {
        ...
        throw new SomeException();
        ...
    }
}

SomeException is unchecked (extends RuntimeException) unless stated otherwise.

Scenarios:

  1. Transaction marked for rollback by exception thrown out of method2. This is our default case explained by JB Nizet.

  2. Annotating method2 as @Transactional(readOnly = true) still marks transaction for rollback (exception thrown when exiting from method1).

  3. Annotating both method1 and method2 as @Transactional(readOnly = true) still marks transaction for rollback (exception thrown when exiting from method1).

  4. Annotating method2 with @Transactional(noRollbackFor = SomeException) prevents marking transaction for rollback (no exception thrown when exiting from method1).

  5. Suppose method2 belongs to Service1. Invoking it from method1 does not go through Spring's proxy, i.e. Spring is unaware of SomeException thrown out of method2. Transaction is not marked for rollback in this case.

  6. Suppose method2 is not annotated with @Transactional. Invoking it from method1 does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.

  7. Annotating method2 with @Transactional(propagation = Propagation.REQUIRES_NEW) makes method2 start new transaction. That second transaction is marked for rollback upon exit from method2 but original transaction is unaffected in this case (no exception thrown when exiting from method1).

  8. In case SomeException is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1).

See all scenarios tested in this gist.

Why would an Enum implement an Interface?

One of the best use case for me to use enum's with interface is Predicate filters. It's very elegant way to remedy lack of typness of apache collections (If other libraries mayn't be used).

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;


public class Test {
    public final static String DEFAULT_COMPONENT = "Default";

    enum FilterTest implements Predicate {
        Active(false) {
            @Override
            boolean eval(Test test) {
                return test.active;
            }
        },
        DefaultComponent(true) {
            @Override
            boolean eval(Test test) {
                return DEFAULT_COMPONENT.equals(test.component);
            }
        }

        ;

        private boolean defaultValue;

        private FilterTest(boolean defautValue) {
            this.defaultValue = defautValue;
        }

        abstract boolean eval(Test test);

        public boolean evaluate(Object o) {
            if (o instanceof Test) {
                return eval((Test)o);
            }
            return defaultValue;
        }

    }

    private boolean active = true;
    private String component = DEFAULT_COMPONENT;

    public static void main(String[] args) {
        Collection<Test> tests = new ArrayList<Test>();
        tests.add(new Test());

        CollectionUtils.filter(tests, FilterTest.Active);
    }
}

Redirection of standard and error output appending to the same log file

Like Unix shells, PowerShell supports > redirects with most of the variations known from Unix, including 2>&1 (though weirdly, order doesn't matter - 2>&1 > file works just like the normal > file 2>&1).

Like most modern Unix shells, PowerShell also has a shortcut for redirecting both standard error and standard output to the same device, though unlike other redirection shortcuts that follow pretty much the Unix convention, the capture all shortcut uses a new sigil and is written like so: *>.

So your implementation might be:

& myjob.bat *>> $logfile

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

How do I pipe or redirect the output of curl -v?

The following worked for me:

Put your curl statement in a script named abc.sh

Now run:

sh abc.sh 1>stdout_output 2>stderr_output

You will get your curl's results in stdout_output and the progress info in stderr_output.

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

How to set background color of HTML element using css properties in JavaScript

var element = document.getElementById('element');
element.style.background = '#FF00AA';

Print Pdf in C#

Another approach, if you simply wish to print a PDF file programmatically, is to use the LPR command: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/lpr.mspx?mfr=true

LPR is available on newer versions of Windows too (e.g. Vista/7), but you need to enable it in the Optional Windows Components.

For example:

Process.Start("LPR -S printerdnsalias -P raw C:\files\file.pdf");

You can also use the printer IP address instead of the alias.

This assumes that your printer supports PDF Direct Printing otherwise this will only work for PostScript and ASCII files. Also, the printer needs to have a network interface installed and you need to know it's IP address or alias.

How to start Fragment from an Activity

You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

Remove leading and trailing spaces?

Starting file:

     line 1
   line 2
line 3  
      line 4 

Code:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

Output:

line 1
line 2
line 3
line 4

Why is a ConcurrentModificationException thrown and how to debug it

I ran into this exception when try to remove x last items from list. myList.subList(lastIndex, myList.size()).clear(); was the only solution that worked for me.

Tricks to manage the available memory in an R session

I quite like the improved objects function developed by Dirk. Much of the time though, a more basic output with the object name and size is sufficient for me. Here's a simpler function with a similar objective. Memory use can be ordered alphabetically or by size, can be limited to a certain number of objects, and can be ordered ascending or descending. Also, I often work with data that are 1GB+, so the function changes units accordingly.

showMemoryUse <- function(sort="size", decreasing=FALSE, limit) {

  objectList <- ls(parent.frame())

  oneKB <- 1024
  oneMB <- 1048576
  oneGB <- 1073741824

  memoryUse <- sapply(objectList, function(x) as.numeric(object.size(eval(parse(text=x)))))

  memListing <- sapply(memoryUse, function(size) {
        if (size >= oneGB) return(paste(round(size/oneGB,2), "GB"))
        else if (size >= oneMB) return(paste(round(size/oneMB,2), "MB"))
        else if (size >= oneKB) return(paste(round(size/oneKB,2), "kB"))
        else return(paste(size, "bytes"))
      })

  memListing <- data.frame(objectName=names(memListing),memorySize=memListing,row.names=NULL)

  if (sort=="alphabetical") memListing <- memListing[order(memListing$objectName,decreasing=decreasing),] 
  else memListing <- memListing[order(memoryUse,decreasing=decreasing),] #will run if sort not specified or "size"

  if(!missing(limit)) memListing <- memListing[1:limit,]

  print(memListing, row.names=FALSE)
  return(invisible(memListing))
}

And here is some example output:

> showMemoryUse(decreasing=TRUE, limit=5)
      objectName memorySize
       coherData  713.75 MB
 spec.pgram_mine  149.63 kB
       stoch.reg  145.88 kB
      describeBy    82.5 kB
      lmBandpass   68.41 kB

Compare two different files line by line in python

If you are specifically looking for getting the difference between two files, then this might help:

with open('first_file', 'r') as file1:
    with open('second_file', 'r') as file2:
        difference = set(file1).difference(file2)

difference.discard('\n')

with open('diff.txt', 'w') as file_out:
    for line in difference:
        file_out.write(line)

Generating a PDF file from React Components

you can user canvans with jsPDF

import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

 _exportPdf = () => {

     html2canvas(document.querySelector("#capture")).then(canvas => {
        document.body.appendChild(canvas);  // if you want see your screenshot in body.
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'PNG', 0, 0);
        pdf.save("download.pdf"); 
    });

 }

and you div with id capture is:

example

<div id="capture">
  <p>Hello in my life</p>
  <span>How can hellp you</span>
</div>

What is the default lifetime of a session?

The default in the php.ini for the session.gc_maxlifetime directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:

http://www.php.net/manual/en/session.configuration.php

You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:

php_value session.gc_maxlifetime "3600"

Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.

The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.

Java 8 - Difference between Optional.flatMap and Optional.map

What helped me was a look at the source code of the two functions.

Map - wraps the result in an Optional.

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
    }
}

flatMap - returns the 'raw' object

public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Objects.requireNonNull(mapper.apply(value)); //<---  returns 'raw' object
    }
}

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

I worked on both Travis and Jenkins: I will list down some of the features of both:

Setup CI for a project

Travis comes in first place. It's very easy to setup. Takes less than a minute to setup with GitHub.

  1. Login to GitHub
  2. Create Web Hook for Travis.
  3. Return to Travis, and login with your GitHub credentials
  4. Sync your GitHub repo and enable Push and Pull requests.

Jenkins:

  1. Create an Environment (Master Jenkins)
  2. Create web hooks
  3. Configure each job (takes time compare to Travis)

Re-running builds

Travis: Anyone with write access on GitHub can re-run the build by clicking on `restart build

Jenkins: Re-run builds based on a phrase. You provide phrase text in PR/commit description, like reverify jenkins.

Controlling environment

Travis: Travis provides hosted environment. It installs required software for every build. It’s a time-consuming process.

Jenkins: One-time setup. Installs all required software on a node/slave machine, and then builds/tests on a pre-installed environment.

Build Logs:

Travis: Supports build logs to place in Amazon S3.

Jenkins: Easy to setup with build artifacts plugin.

Fastest way to determine if an integer's square root is an integer

If you do a binary chop to try to find the "right" square root, you can fairly easily detect if the value you've got is close enough to tell:

(n+1)^2 = n^2 + 2n + 1
(n-1)^2 = n^2 - 2n + 1

So having calculated n^2, the options are:

  • n^2 = target: done, return true
  • n^2 + 2n + 1 > target > n^2 : you're close, but it's not perfect: return false
  • n^2 - 2n + 1 < target < n^2 : ditto
  • target < n^2 - 2n + 1 : binary chop on a lower n
  • target > n^2 + 2n + 1 : binary chop on a higher n

(Sorry, this uses n as your current guess, and target for the parameter. Apologise for the confusion!)

I don't know whether this will be faster or not, but it's worth a try.

EDIT: The binary chop doesn't have to take in the whole range of integers, either (2^x)^2 = 2^(2x), so once you've found the top set bit in your target (which can be done with a bit-twiddling trick; I forget exactly how) you can quickly get a range of potential answers. Mind you, a naive binary chop is still only going to take up to 31 or 32 iterations.

Stop an input field in a form from being submitted

Handle the form's submit in a function via onSubmit() and perform something like below to remove the form element: Use getElementById() of the DOM, then using [object].parentNode.removeChild([object])

suppose your field in question has an id attribute "my_removable_field" code:

var remEl = document.getElementById("my_removable_field");
if ( remEl.parentNode && remEl.parentNode.removeChild ) {
remEl.parentNode.removeChild(remEl);
}

This will get you exactly what you are looking for.

Creating a copy of an object in C#

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.

Android widget: How to change the text of a button

//text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" text button" />

// color text button:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/color text"/>

// background button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/ background button"/>

// text size button

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text button" 
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:textSize="text size"/>

Get property value from C# dynamic object by string (reflection?)

This will give you all property names and values defined in your dynamic variable.

dynamic d = { // your code };
object o = d;
string[] propertyNames = o.GetType().GetProperties().Select(p => p.Name).ToArray();
foreach (var prop in propertyNames)
{
    object propValue = o.GetType().GetProperty(prop).GetValue(o, null);
}

How to create a Restful web service with input parameters?

If you want query parameters, you use @QueryParam.

public Todo getXML(@QueryParam("summary") String x, 
                   @QueryParam("description") String y)

But you won't be able to send a PUT from a plain web browser (today). If you type in the URL directly, it will be a GET.

Philosophically, this looks like it should be a POST, though. In REST, you typically either POST to a common resource, /todo, where that resource creates and returns a new resource, or you PUT to a specifically-identified resource, like /todo/<id>, for creation and/or update.

How to disable an input box using angular.js

<input data-ng-model="userInf.username"  class="span12 editEmail" type="text"  placeholder="[email protected]"  pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required ng-disabled="true"/>

How can I enable MySQL's slow query log without restarting MySQL?

Try SET GLOBAL slow_query_log = 'ON'; and perhaps FLUSH LOGS;

This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

How to change the default GCC compiler in Ubuntu?

I used just the lines below and it worked. I just wanted to compile VirtualBox and VMWare WorkStation using kernel 4.8.10 on Ubuntu 14.04. Initially, most things were not working for example graphics and networking. I was lucky that VMWare workstation requested for gcc 6.2.0. I couldn't start my Genymotion Android emulators because virtualbox was down. Will post results later if necessary.

VER=4.6 ; PRIO=60
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=6 ; PRIO=50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=4.8 ; PRIO=40
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER

cast a List to a Collection

Casting never needs a new:

Collection<T> collection = myList;

You don't even make the cast explicit, because Collection is a super-type of List, so it will work just like this.

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

In my case there was problem in URL. I've use https://example.com - but they ensure 'www.' - so when i switched to https://www.example.com everything was ok. The proper header was sent 'Host: www.example.com'.

You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

How do you Sort a DataTable given column and direction?

Actually got the same problem. For me worked this easy way:

Adding the data to a Datatable and sort it:

dt.DefaultView.Sort = "columnname";
dt = dt.DefaultView.ToTable();

JQuery, setTimeout not working

You've got a couple of issues here.

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

because the function pointer update is within scope of that block.

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

or

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

and both of these work. The second works because the update() within the code block is within scope now.

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

Hope that clears that up.

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

How do I line up 3 divs on the same row?

Why don't try to use bootstrap's solutions. They are perfect if you don't want to meddle with tables and floats.

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <!--- This line is just linking the bootstrap thingie in the file. The real thing starts below -->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
    <div class="col-sm-4">_x000D_
      One of three columns_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

No meddling with complex CSS, and the best thing is that you can edit the width of the columns by changing the number. You can find more examples at https://getbootstrap.com/docs/4.0/layout/grid/

How to configure PostgreSQL to accept all incoming connections

Addition to above great answers, if you want some range of IPs to be authorized, you could edit /var/lib/pgsql/{VERSION}/data file and put something like

host all all 172.0.0.0/8 trust

It will accept incoming connections from any host of the above range. Source: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/c15679_002.htm

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Wait for shell command to complete

Add the following Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub

If you add a reference to C:\Windows\system32\wshom.ocx you can also use:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub

This version should be more efficient.

What is the best way to measure execution time of a function?

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

Using a PagedList with a ViewModel ASP.Net MVC

I modified the code as follow:

ViewModel

using System.Collections.Generic;
using ContosoUniversity.Models;

namespace ContosoUniversity.ViewModels
{
    public class InstructorIndexData
    {
     public PagedList.IPagedList<Instructor> Instructors { get; set; }
     public PagedList.IPagedList<Course> Courses { get; set; }
     public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
    }
}

Controller

public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
 int instructPageNumber = (InstructorPage?? 1);
 int CoursePageNumber = (CoursePage?? 1);
 int EnrollmentPageNumber = (EnrollmentPage?? 1);
 var viewModel = new InstructorIndexData();
 viewModel.Instructors = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses.Select(c => c.Department))
    .OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);

 if (id != null)
 {
    ViewBag.InstructorID = id.Value;
    viewModel.Courses = viewModel.Instructors.Where(
        i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
 }

 if (courseID != null)
 {
    ViewBag.CourseID = courseID.Value;
    viewModel.Enrollments = viewModel.Courses.Where(
        x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
 }

 return View(viewModel);
}

View

<div>
   Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount

   @Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))

</div>

I hope this would help you!!

Add disabled attribute to input element using Javascript

If you're using jQuery then there are a few different ways to set the disabled attribute.

var $element = $(...);
    $element.prop('disabled', true);
    $element.attr('disabled', true); 

    // The following do not require jQuery
    $element.get(0).disabled = true;
    $element.get(0).setAttribute('disabled', true);
    $element[0].disabled = true;
    $element[0].setAttribute('disabled', true);

Angular 4 checkbox change value

This it what you are looking for:

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />

Inside your class:

checkValue(event: any){
   console.log(event);
}

Also include FormsModule in app.module.ts to make ngModel work !

Hope it Helps!

Display Two <div>s Side-by-Side

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}??

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.

add a temporary column with a value

select field1, field2, 'example' as TempField
from table1

This should work across different SQL implementations.

jQuery Validation using the class instead of the name value

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

comparing two strings in ruby

Comparison of strings is very easy in Ruby:

v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true

Make sure your var2 is not an array (which seems to be like)

Returning Arrays in Java

You have a couple of basic misconceptions about Java:

I want it to return the array without having to explicitly tell the console to print.

1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)

2) The "main" doesn't "return" anything. The method signature is:

  public static void main(String[] args)

and the void means "no value is returned". (And, sorry, no you can't replace the void with something else. If you do then the java command won't recognize the "main" method.)

3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return statement ...

Printing leading 0's in C

You will save yourself a heap of trouble (long term) if you store a ZIP Code as a character string, which it is, rather than a number, which it is not.

Converting Integers to Roman Numerals - Java

String convert(int i){

    String ones = "";
    String tens = "";
    String hundreds = "";
    String thousands = "";
    String result ;

    boolean error = false;

    Vector v = new Vector();

    //assign passed integer to temporary value temp
    int temp=i;

    //flags an error if number is greater than 3999
    if (temp >=4000) {
       error = true;
    }

    /*loops while temp can no more be divided by 10.
        Lets say i = 3254, then temp is also 3254 at line 14.

                           3254 
          3254/10 = 25    /   \ 3254%10 = 4
                         /     \
    now temp = 25       325     4  - here 4 is added to the vector v's 0th index.
                        / \
    now temp = 32     32   5  - here 5 is added to the vector v's 1st index.
                     /  \
    now temp = 3    3    2  - here 2 is added to the vector v's 2nd index, and loop exits
                   / \        since temp/10 = 0
                  0   3  - here 3 is not added to the vector v's 3rd index as loop exits when
                            temp/10 = 0.


    */
    while (temp/10 != 0) {
        if (temp / 10 != 0 && temp <4000) {
            v.add(temp%10);
            temp = temp / 10;
        }else {     
            break;
        }
    }

    //therefore you have to add temp one last time to the vector
    v.add(temp);

    //as in the example now you have 4,5,2,3 respectively in v's 0,1,2,3 indices.


    for (int j = 0; j < v.size(); j++) {

        //you see that v's 0th index has number of ones. So make them roman ones here.
        if (j==0) {
            switch (v.get(0).toString()){
                case "0" : ones = ""; break;
                case "1" : ones = "I"; break;
                case "2" : ones = "II"; break;
                case "3" : ones = "III"; break;
                case "4" : ones = "IV"; break;
                case "5" : ones = "V"; break;
                case "6" : ones = "VI"; break;
                case "7" : ones = "VII"; break;
                case "8" : ones = "VIII"; break;
                case "9" : ones = "IX"; break;
            }


            //in the second iteration of the loop (when j==1) 
            //index 1 of v is checked. Now you understand that v's 1st index
            //has the tens
        } else if (j == 1) {
            switch (v.get(1).toString()){
                case "0" : tens = ""; break;
                case "1" : tens = "X"; break;
                case "2" : tens = "XX"; break;
                case "3" : tens = "XXX"; break;
                case "4" : tens = "XL"; break;
                case "5" : tens = "L"; break;
                case "6" : tens = "LX"; break;
                case "7" : tens = "LXX"; break;
                case "8" : tens = "LXXX"; break;
                case "9" : tens = "XC"; break;
            }
        } else if(j == 2){  //and hundreds
            switch (v.get(2).toString()){
                case "0" : hundreds = ""; break;
                case "1" : hundreds = "C"; break;
                case "2" : hundreds = "CC"; break;
                case "3" : hundreds = "CCC"; break;
                case "4" : hundreds = "CD"; break;
                case "5" : hundreds = "D"; break;
                case "6" : hundreds = "DC"; break;
                case "7" : hundreds = "DCC"; break;
                case "8" : hundreds = "DCCC"; break;
                case "9" : hundreds = "CM"; break;
            }
        }   else if(j == 3){ //and finally thousands.
            switch (v.get(3).toString()){           
                case "0" : thousands = ""; break;
                case "1" : thousands = "M"; break;
                case "2" : thousands = "MM"; break;
                case "3" : thousands = "MMM"; break;

            }
        } 
    }



    if (error) {
       result = "Error!";
    }else{
        result = thousands + hundreds + tens + ones;
    }

    return result;

}

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

There could be several things causing this and it somewhat depends on what you have set up in your database.

First, you could be using a PK in the table that is also an FK to another table making the relationship 1-1. IN this case you may need to do an update rather than an insert. If you really can have only one address record for an order this may be what is happening.

Next you could be using some sort of manual process to determine the id ahead of time. The trouble with those manual processes is that they can create race conditions where two records gab the same last id and increment it by one and then the second one can;t insert.

Third, you query as it is sent to the database may be creating two records. To determine if this is the case, Run Profiler to see exactly what SQL code you are sending and if ti is a select instead of a values clause, then run the select and see if you have due to the joins gotten some records to be duplicated. IN any even when you are creating code on the fly like this the first troubleshooting step is ALWAYS to run Profiler and see if what got sent was what you expected to be sent.

How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

Scroll to element on click in Angular 4

I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)) and using the .focus() call.

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Oracle - What TNS Names file am I using?

On my development machine I have three different versions of Oracle client software. I manage the tnsnames.ora file in one of them. In the other two, I have entered in the tnsnames.ora file:

ifile=path_to_tnsnames.ora_file/tnsnames.ora

This way, if for some reason the wrong tnsnames.ora file is used by a client, it will always end up at the up-to-date version.

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

Is there a foreach loop in Go?

Go has a foreach-like syntax. It supports arrays/slices, maps and channels.

Iterate over array or slice:

// index and value
for i, v := range slice {}

// index only
for i := range slice {}

// value only
for _, v := range slice {}

Iterate over a map:

// key and value
for key, value := range theMap {}

// key only
for key := range theMap {}

// value only
for _, value := range theMap {}

Iterate over a channel:

for v := range theChan {}

Iterating over a channel is equivalent to receiving from a channel until it is closed:

for {
    v, ok := <-theChan
    if !ok {
        break
    }
}

duplicate 'row.names' are not allowed error

In my case was a comma at the end of every line. By removing that worked

Difference between Convert.ToString() and .ToString()

ToString() can not handle null values and convert.ToString() can handle values which are null, so when you want your system to handle null value use convert.ToString().

installation app blocked by play protect

If you are using some trackers like google analytics or amplitude and you are trying to release your app in another platforms other than Google Play, this errors appears for users. So there are two possible solutions:

  1. Use special trackers in your app (firebase and appmetrica are tested and are ok)
  2. Release your app in Google Play

How to get week numbers from dates?

If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).

library(dplyr)
library(lubridate)

# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
                                   "2016-01-03",
                                   "2016-01-04",
                                   "2018-12-30",
                                   "2018-12-31",
                                   "2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"

# this codes provides correct year-week numbers
test <- test %>%
        mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
        mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
        mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
                                 yes  = yearweek + 100,
                                 no   = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
                                               yes  = yearweek - 100,
                                               no   = yearweek)))
# print the result
print(test)

    date_txt       date yearweek yearweek2
1 2015-12-31 2015-12-31   201553    201553
2 2016-01-03 2016-01-03   201653    201553
3 2016-01-04 2016-01-04   201601    201601
4 2018-12-30 2018-12-30   201852    201852
5 2018-12-31 2018-12-31   201801    201901
6 2019-01-01 2019-01-01   201901    201901

How to detect lowercase letters in Python?

There are 2 different ways you can look for lowercase characters:

  1. Use str.islower() to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:

    lowercase = [c for c in s if c.islower()]
    
  2. You could use a regular expression:

    import re
    
    lc = re.compile('[a-z]+')
    lowercase = lc.findall(s)
    

The first method returns a list of individual characters, the second returns a list of character groups:

>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']

How to access SOAP services from iPhone

My solution was to have a proxy server accept REST, issue the SOAP request, and return result, using PHP.

Time to implement: 15-30 minutes.

Not most elegant, but solid.

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

HTML5 Number Input - Always show 2 decimal places

Using the step attribute will enable it. It not only determines how much it's supposed to cycle, but the allowable numbers, as well. Using step="0.01" should do the trick but this may depend on how the browser adheres to the standard.

_x000D_
_x000D_
<input type='number' step='0.01' value='5.00'>
_x000D_
_x000D_
_x000D_

Convert pyQt UI to python

You don't have to install PyQt4 with all its side features, you just need the PyQt4 package itself. Inside the package you could use the module pyuic.py ("C:\Python27\Lib\site-packages\PyQt4\uic") to convert your Ui file.

C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py -help

update python3: use pyuic5 -help # add filepath if needed. pyuic version = 4 or 5.

You will get all options listed:

Usage: pyuic4 [options] <ui-file>

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -p, --preview         show a preview of the UI instead of generating code
  -o FILE, --output=FILE
                        write generated code to FILE instead of stdout
  -x, --execute         generate extra code to test and display the class
  -d, --debug           show debug output
  -i N, --indent=N      set indent width to N spaces, tab if N is 0 [default:
                        4]
  -w, --pyqt3-wrapper   generate a PyQt v3 style wrapper

  Code generation options:
    --from-imports      generate imports relative to '.'
    --resource-suffix=SUFFIX
                        append SUFFIX to the basename of resource files
                        [default: _rc]

So your command will look like this:

C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py test_dialog.ui -o test.py -x

You could also use full file paths to your file to convert it.

Why do you want to convert it anyway? I prefer creating widgets in the designer and implement them with via the *.ui file. That makes it much more comfortable to edit it later. You could also write your own widget plugins and load them into the Qt Designer with full access. Having your ui hard coded doesn't makes it very flexible.

I reuse a lot of my ui's not only in Maya, also for Max, Nuke, etc.. If you have to change something software specific, you should try to inherit the class (with the parented ui file) from a more global point of view and patch or override the methods you have to adjust. That saves a lot of work time. Let me know if you have more questions about it.

iOS 7.0 No code signing identities found

Go to the Issue navigator and check if Signing Identity: is present in your Keychain Access. If no, download .cer file and append it to the keychain.

Using python PIL to turn a RGB image into a pure black and white image

Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy


def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file = Image.open(img_path)
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)


def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input",
                        dest="input",
                        help="read this file",
                        metavar="FILE",
                        required=True)
    parser.add_argument("-o", "--output",
                        dest="output",
                        help="write binarized file hre",
                        metavar="FILE",
                        required=True)
    parser.add_argument("--threshold",
                        dest="threshold",
                        default=200,
                        type=int,
                        help="Threshold when to show white")
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200:

enter image description here

How to use WebRequest to POST some data and read response?

Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.

StringBuilder sb = new StringBuilder();
    string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
    string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
    request.Referer = "http://www.yourdomain.com";
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    Char[] readBuffer = new Char[256];
    int count = reader.Read(readBuffer, 0, 256);

    while (count > 0)
    {
        String output = new String(readBuffer, 0, count);
        sb.Append(output);
        count = reader.Read(readBuffer, 0, 256);
    }
    string xml = sb.ToString();

How can I delete a newline if it is the last character in a file?

A fast solution is using the gnu utility truncate:

[ -z $(tail -c1 file) ] && truncate -s-1 file

The test will be true if the file does have a trailing new line.

The removal is very fast, truly in place, no new file is needed and the search is also reading from the end just one byte (tail -c1).

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

I think your MySQL server has not started. So start the server using one of the following commands.

#services mysql start

or

#/etc/init.d/mysql start

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%, date/t, and date that break the original batch-file.

It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:
echo:^|date
date/t

This is a sample of the output you should get from the batch-file:

C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103

Here is the revised code with comments on why:

:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by [email protected] for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
::            set '%%c'=%%k
::            set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
::        if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
    set v_day=
    set v_month=
    set v_year=

    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
      for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
        if "%%a" GEQ "A" (
          for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
            set '%%a'=%%i
            set '%%b'=%%j
            set 'yy'=%%k
          )
        )
      )
      if %'yy'% LSS 100 set 'yy'=20%'yy'%
      set Today=%'yy'%-%'mm'%-%'dd'%

    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
    set datestring=%V_Year%%V_Month%%V_Day%
    echo %datestring%

    :EOF

--jeroen

How to display an IFRAME inside a jQuery UI dialog

The problems were:

  1. iframe content comes from another domain
  2. iframe dimensions need to be adjusted for each video

The solution based on omerkirk's answer involves:

  • Creating an iframe element
  • Creating a dialog with autoOpen: false, width: "auto", height: "auto"
  • Specifying iframe source, width and height before opening the dialog

Here is a rough outline of code:

HTML

<div class="thumb">
    <a href="http://jsfiddle.net/yBNVr/show/"   data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
    <a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>

jQuery

$(function () {
    var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
    var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: "auto",
        height: "auto",
        close: function () {
            iframe.attr("src", "");
        }
    });
    $(".thumb a").on("click", function (e) {
        e.preventDefault();
        var src = $(this).attr("href");
        var title = $(this).attr("data-title");
        var width = $(this).attr("data-width");
        var height = $(this).attr("data-height");
        iframe.attr({
            width: +width,
            height: +height,
            src: src
        });
        dialog.dialog("option", "title", title).dialog("open");
    });
});

Demo here and code here. And another example along similar lines

In Android EditText, how to force writing uppercase?

You should put android:inputType="textCapCharacters" with Edittext in xml file.

Use of Application.DoEvents()

Check out the MSDN Documentation for the Application.DoEvents method.

How to parse XML using jQuery?

There is the $.parseXML function for this: http://api.jquery.com/jQuery.parseXML/

You can use it like this:

var xml = $.parseXML(yourfile.xml),
  $xml = $( xml ),
  $test = $xml.find('test');

console.log($test.text());

If you really want an object, you need a plugin for that. This plugin for instance, will convert your XML to JSON: http://www.fyneworks.com/jquery/xml-to-json/

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

The foo.bar reference should not contain the braces:

<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>

Angular expressions need to be within the curly-brace bindings, where as Angular directives do not.

See also Understanding Angular Templates.

Using Spring RestTemplate in generic method with generic parameter

Actually, you can do this, but with additional code.

There is Guava equivalent of ParameterizedTypeReference and it's called TypeToken.

Guava's class is much more powerful then Spring's equivalent. You can compose the TypeTokens as you wish. For example:

static <K, V> TypeToken<Map<K, V>> mapToken(TypeToken<K> keyToken, TypeToken<V> valueToken) {
  return new TypeToken<Map<K, V>>() {}
    .where(new TypeParameter<K>() {}, keyToken)
    .where(new TypeParameter<V>() {}, valueToken);
}

If you call mapToken(TypeToken.of(String.class), TypeToken.of(BigInteger.class)); you will create TypeToken<Map<String, BigInteger>>!

The only disadvantage here is that many Spring APIs require ParameterizedTypeReference and not TypeToken. But we can create ParameterizedTypeReference implementation which is adapter to TypeToken itself.

import com.google.common.reflect.TypeToken;
import org.springframework.core.ParameterizedTypeReference;

import java.lang.reflect.Type;

public class ParameterizedTypeReferenceBuilder {

    public static <T> ParameterizedTypeReference<T> fromTypeToken(TypeToken<T> typeToken) {
        return new TypeTokenParameterizedTypeReference<>(typeToken);
    }

    private static class TypeTokenParameterizedTypeReference<T> extends ParameterizedTypeReference<T> {

        private final Type type;

        private TypeTokenParameterizedTypeReference(TypeToken<T> typeToken) {
            this.type = typeToken.getType();
        }

        @Override
        public Type getType() {
            return type;
        }

        @Override
        public boolean equals(Object obj) {
            return (this == obj || (obj instanceof ParameterizedTypeReference &&
                    this.type.equals(((ParameterizedTypeReference<?>) obj).getType())));
        }

        @Override
        public int hashCode() {
            return this.type.hashCode();
        }

        @Override
        public String toString() {
            return "ParameterizedTypeReference<" + this.type + ">";
        }

    }

}

Then you can use it like this:

public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
   ParameterizedTypeReference<ResponseWrapper<T>> responseTypeRef =
           ParameterizedTypeReferenceBuilder.fromTypeToken(
               new TypeToken<ResponseWrapper<T>>() {}
                   .where(new TypeParameter<T>() {}, clazz));
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        responseTypeRef);
    return response;
}

And call it like:

ResponseWrapper<MyClass> result = makeRequest(uri, MyClass.class);

And the response body will be correctly deserialized as ResponseWrapper<MyClass>!

You can even use more complex types if you rewrite your generic request method (or overload it) like this:

public <T> ResponseWrapper<T> makeRequest(URI uri, TypeToken<T> resultTypeToken) {
   ParameterizedTypeReference<ResponseWrapper<T>> responseTypeRef =
           ParameterizedTypeReferenceBuilder.fromTypeToken(
               new TypeToken<ResponseWrapper<T>>() {}
                   .where(new TypeParameter<T>() {}, resultTypeToken));
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        responseTypeRef);
    return response;
}

This way T can be complex type, like List<MyClass>.

And call it like:

ResponseWrapper<List<MyClass>> result = makeRequest(uri, new TypeToken<List<MyClass>>() {});

Tomcat Servlet: Error 404 - The requested resource is not available

try this (if the Java EE V6)

package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet(name="hello",urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

now reach the servlet by http://127.0.0.1:8080/yourapp/hello

where 8080 is default tomcat port, and yourapp is the context name of your applciation

Date query with ISODate in mongodb doesn't seem to work

From the MongoDB cookbook page comments:

"dt" : 
{
    "$gte" : ISODate("2014-07-02T00:00:00Z"), 
    "$lt" : ISODate("2014-07-03T00:00:00Z") 
}

This worked for me. In full context, the following command gets every record where the dt date field has a date on 2013-10-01 (YYYY-MM-DD) Zulu:

db.mycollection.find({ "dt" : { "$gte" : ISODate("2013-10-01T00:00:00Z"), "$lt" : ISODate("2013-10-02T00:00:00Z") }})

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Eslint: How to disable "unexpected console statement" in Node.js?

Alternatively instead of turning 'no-console' off, you can allow. In the .eslintrc.js file put

  rules: {
    "no-console": [
     "warn",
     { "allow": ["clear", "info", "error", "dir", "trace", "log"] }
    ]
  }

This will allow you to do console.log and console.clear etc without throwing errors.

How to read a HttpOnly cookie using JavaScript

The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.

The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?

Where do I find the Instagram media ID of a image

So the most up-voted "Better Way" is a little deprecated so here is my edit and other solutions:

Javascript + jQuery

$.ajax({
    type: 'GET',
    url: 'http://api.instagram.com/oembed?callback=&url='+Url, //You must define 'Url' for yourself
    cache: false,
    dataType: 'json',
    jsonp: false,
    success: function (data) {
       var MediaID = data.media_id;
   }
});

PHP

$your_url = "" //Input your url
$api = file_get_contents("http://api.instagram.com/oembed?callback=&url=" . your_url);      
$media_id = json_decode($api,true)['media_id'];

So, this is just an updated version of @George's code and is currently working. However, I made other solutions, and some even avoid an ajax request:


Shortcode Ajax Solution

Certain Instagram urls use a shortened url syntax. This allows the client to just use the shortcode in place of the media id if requested properly.

An example shortcode url looks like this: https://www.instagram.com/p/Y7GF-5vftL/

The Y7GF-5vftL is your shortcode for the picture.

Using Regexp:

var url = "https://www.instagram.com/p/Y7GF-5vftL/"; //Define this yourself
var Key = /p\/(.*?)\/$/.exec(url)[1];

In the same scope, Key will contain your shortcode. Now to request, let's say, a low res picture using this shortcode, you would do something like the following:

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "https://api.instagram.com/v1/media/shortcode/" + Key + "?access_token=" + access_token, //Define your 'access_token'
        success: function (RawData) {
            var LowResURL = RawData.data.images.low_resolution.url;
        }
    });

There is lots of other useful information, including the media id, in the returned RawData structure. Log it or look up the api documentation to see.


Shortcode Conversion Solution

You can actually convert your shortcode to the id fairly easily! Here's a simple way to do it in javascript:

function shortcodeToInstaID(Shortcode) {
      var char;
      var id = 0;
      var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
      for (var i = 0; i < Shortcode.length; i++) {
          char = Shortcode[i];
          id = (id * 64) + alphabet.indexOf(char);
      }
      return id;
  }

Note: If you want a more robust node.js solution, or want to see how you would convert it back, check out @Slang's module on npm.


Full Page Solution

So what if you have the URL to a full Instagram page like: https://www.instagram.com/p/BAYYJBwi0Tssh605CJP2bmSuRpm_Jt7V_S8q9A0/

Well, you can actually read the HTML to find a meta property that contains the Media ID. There are also a couple other algorithms you can perform on the URL itself to get it, but I believe that requires too much effort so we will keep it simple. Either query the meta tag al:ios:url or iterate through the html. Since reading metatags is posted all over, I'll show you how to iterate.

NOTE: This is a little unstable and is vulnerable to being patched. This method does NOT work on a page that uses a preview box. So if you give it the current HTML when you click on a picture in someone's profile, this WILL break and return a bad Media ID.

function getMediaId(HTML_String) {
  var MediaID = "";
  var e = HTML_String.indexOf("al:ios:url") + 42; //HTML_String is a variable that contains all of the HTML text as a string for the current document. There are many different ways to retrieve this so look one up. 
  for (var i = e; i <= e + 100; i++) { //100 should never come close to being reached
      if (request.source.charAt(i) == "\"")
         break;
      MediaID += request.source.charAt(i);
  }
  return MediaID;
}

And there you go, a bunch of different ways to use Instagram's api to get a Media ID. Hope one fixes your struggles.

jQuery: Handle fallback for failed AJAX Request

Dougs answer is correct, but you actually can use $.getJSON and catch errors (not having to use $.ajax). Just chain the getJSON call with a call to the fail function:

$.getJSON('/foo/bar.json')
    .done(function() { alert('request successful'); })
    .fail(function() { alert('request failed'); });

Live demo: http://jsfiddle.net/NLDYf/5/

This behavior is part of the jQuery.Deferred interface.
Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.

Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/

Sort array of objects by string property value

A simple function that sort an array of object by a property

function sortArray(array, property, direction) {
    direction = direction || 1;
    array.sort(function compare(a, b) {
        let comparison = 0;
        if (a[property] > b[property]) {
            comparison = 1 * direction;
        } else if (a[property] < b[property]) {
            comparison = -1 * direction;
        }
        return comparison;
    });
    return array; // Chainable
}

Usage:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

sortArray(objs, "last_nom"); // Asc
sortArray(objs, "last_nom", -1); // Desc

What is w3wp.exe?

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.

Creating .pem file for APNS?

Launch the Terminal application and enter the following command after the prompt

  openssl pkcs12 -in CertificateName.p12 -out CertificateName.pem -nodes

WAMP shows error 'MSVCR100.dll' is missing when install

To solve this issue you have to install all Microsoft redistribution packages 2010,2012(x86 and x64) than uninstall wampserver from control panel and reinstall new copy of wamp server this error will be get fixed

Check if image exists on server using JavaScript?

If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here

getInitialState: function(event) {
    return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
    this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
    return (
        <img onError={this.handleError} src={src} />;
    );
}

Reading a .txt file using Scanner class in Java

File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file. Please log the file.getAbsolutePath() to verify that file is correct.

How to create a byte array in C++?

If you want exactly one byte, uint8_t defined in cstdint would be the most expressive.

http://www.cplusplus.com/reference/cstdint/

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

For your interest, to do the same with double

double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75

or just

double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n",  doubleVal);
System.out.printf("bdTest1: %.2f%n",  doubleVal2);

both print

bdTest: 1.75
bdTest1: 0.75

I prefer to keep code as simple as possible. ;)

As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335 are a little less than they appear.

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

Can dplyr package be used for conditional mutating?

The derivedFactor function from mosaic package seems to be designed to handle this. Using this example, it would look like:

library(dplyr)
library(mosaic)
df <- mutate(df, g = derivedFactor(
     "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
     "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
     .method = "first",
     .default = NA
     ))

(If you want the result to be numeric instead of a factor, you can wrap derivedFactor in an as.numeric call.)

derivedFactor can be used for an arbitrary number of conditionals, too.

Fluid width with equally spaced DIVs

The easiest way to do this now is with a flexbox:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The CSS is then simply:

#container {
    display: flex;
    justify-content: space-between;
}

demo: http://jsfiddle.net/QPrk3/

However, this is currently only supported by relatively recent browsers (http://caniuse.com/flexbox). Also, the spec for flexbox layout has changed a few times, so it's possible to cover more browsers by additionally including an older syntax:

http://css-tricks.com/old-flexbox-and-new-flexbox/

http://css-tricks.com/using-flexbox/

Installing RubyGems in Windows

Check that ruby interpreter is already installed and try "ruby setup.rb" in command prompt.

How to execute powershell commands from a batch file?

Looking for the possibility to put a powershell script into a batch file, I found this thread. The idea of walid2mi did not worked 100% for my script. But via a temporary file, containing the script it worked out. Here is the skeleton of the batch file:

;@echo off
;setlocal ENABLEEXTENSIONS
;rem make from X.bat a X.ps1 by removing all lines starting with ';' 
;Findstr -rbv "^[;]" %0 > %~dpn0.ps1 
;powershell -ExecutionPolicy Unrestricted -File %~dpn0.ps1 %*
;del %~dpn0.ps1
;endlocal
;goto :EOF
;rem Here start your power shell script.
param(
    ,[switch]$help
)

Difference between & and && in Java?

& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

Display alert message and redirect after click on accept

The redirect function cleans the output buffer and does a header('Location:...'); redirection and exits script execution. The part you are trying to echo will never be outputted.

You should either notify on the download page or notify on the page you redirect to about the missing data.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:

    class mydict(dict): pass
    a = mydict()        
    a["b=c"] = 'value'
    a.test = False

How to change default format at created_at and updated_at value laravel

If anyone is looking for a simple solution in Laravel 5.3:

  1. Let default timestamps() be saved as is i.e. '2016-11-14 12:19:49'
  2. In your views, format the field as below (or as required):

    date('F d, Y', strtotime($list->created_at))
    

It worked for me very well for me.

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

Where can I find documentation on formatting a date in JavaScript?

_x000D_
_x000D_
d = Date.now();_x000D_
d = new Date(d);_x000D_
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");_x000D_
_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

Is there a reason for C#'s reuse of the variable in a foreach?

In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.

The language specification says:

8.8.4 The foreach statement

(...)

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
      while (e.MoveNext()) {
          V v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

(...)

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:

int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
    if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();

If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.)

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

How to check whether the user uploaded a file in PHP?

I checked your code and think you should try this:

if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name'])) 
    {
        echo 'No upload';
    }   
    else
        echo 'upload';

How to load GIF image in Swift?

This is working for me

Podfile:

platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end

Usage:

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

For more information follow this link: https://github.com/swiftgif/SwiftGif

Read from file or stdin

You can just read from stdin unless the user supply a filename ?

If not, treat the special "filename" - as meaning "read from stdin". The user would have to start the program like cat file | myprogram - if he wants to pipe data to it, and myprogam file if he wants it to read from a file.

int main(int argc,char *argv[] ) {
  FILE *input;
  if(argc != 2) {
     usage();
     return 1;
   }
   if(!strcmp(argv[1],"-")) {
     input = stdin;
    } else {
      input = fopen(argv[1],"rb");
      //check for errors
    }

If you're on *nix, you can check whether stdin is a fifo:

 struct stat st_info;
 if(fstat(0,&st_info) != 0)
   //error
  }
  if(S_ISFIFO(st_info.st_mode)) {
     //stdin is a pipe
  }

Though that won't handle the user doing myprogram <file

You can also check if stdin is a terminal/console

if(isatty(0)) {
  //stdin is a terminal
}

How to split a line into words separated by one or more spaces in bash?

It depends upon what you mean by split. If you want to iterate over words in a line, which is in a variable, you can just iterate. For example, let's say the variable line is this is a line. Then you can do this:

for word in $line; do echo $word; done

This will print:

this
is
a
line

for .. in $var splits $var using the values in $IFS, the default value of which means "split blanks and newlines".

If you want to read lines from user or a file, you can do something like:

cat $filename | while read line
do
    echo "Processing new line" >/dev/tty
    for word in $line
    do
        echo $word
    done
done

For anything else, you need to be more explicit and define your question in more detail.

Note: Edited to remove bashism, but I still kept cat $filename | ... because I like it more than redirection.

how to find 2d array size in c++

Suppose you were only allowed to use array then you could find the size of 2-d array by the following way.

  int ary[][5] = { {1, 2, 3, 4, 5},
                   {6, 7, 8, 9, 0}
                 };

  int rows =  sizeof ary / sizeof ary[0]; // 2 rows  

  int cols = sizeof ary[0] / sizeof(int); // 5 cols

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/__init__.py:

"""
The mod module
"""

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

Using malloc for allocation of multi-dimensional arrays with different row lengths

Equivalent memory allocation for char a[10][20] would be as follows.

char **a;

a=(char **) malloc(10*sizeof(char *));

for(i=0;i<10;i++)
    a[i]=(char *) malloc(20*sizeof(char));

I hope this looks simple to understand.

Favorite Visual Studio keyboard shortcuts

Stock Visual Studio? F12 - Edit.GoToDefinition.

Having DevExpress' Refactor! installed means that Ctrl + ` is my all-time fave, though ;)

How to recompile with -fPIC

Briefly, the error means that you can't use a static library to be linked w/ a dynamic one. The correct way is to have a libavcodec compiled into a .so instead of .a, so the other .so library you are trying to build will link well.

The shortest way to do so is to add --enable-shared at ./configure options. Or even you may try to disable shared (or static) libraries at all... you choose what is suitable for you!

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

How do I delete everything in Redis?

i think sometimes stop the redis-server and delete rdb,aof files? make sure there’s no data can be reloading. then start the redis-server,now it's new and empty.

Expected response code 220 but got code "", with message "" in Laravel

I was facing the same issue. After researching too much on Google and StackOverflow. I found a solution very simple

First, you need to set environment like this

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=example44
MAIL_ENCRYPTION=tls
[email protected]

you have to change your Gmail address and password

Now you have to on less secure apps by following this link https://myaccount.google.com/lesssecureapps

Maven artifact and groupId naming

Weirdness is highly subjective, I just suggest to follow the official recommendation:

Guide to naming conventions on groupId, artifactId and version

  • groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.

    eg. org.apache.maven, org.apache.commons

    A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.

    eg. org.apache.maven, org.apache.maven.plugins, org.apache.maven.reporting

  • artifactId is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.

    eg. maven, commons-math

  • version if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.

    eg. 2.0, 2.0.1, 1.3.1

See line breaks and carriage returns in editor

Just to clarify why :set list won't show CR's as ^M without e ++ff=unix and why :set list has nothing to do with ^M's.

Internally when Vim reads a file into its buffer, it replaces all line-ending characters with its own representation (let's call it $'s). To determine what characters should be removed, it firstly detects in what format line endings are stored in a file. If there are only CRLF '\r\n' or only CR '\r' or only LF '\n' line-ending characters, then the 'fileformat' is set to dos, mac and unix respectively.

When list option is set, Vim displays $ character when the line break occurred no matter what fileformat option has been detected. It uses its own internal representation of line-breaks and that's what it displays.

Now when you write buffer to the disc, Vim inserts line-ending characters according to what fileformat options has been detected, essentially converting all those internal $'s with appropriate characters. If the fileformat happened to be unix then it will simply write \n in place of its internal line-break.

The trick is to force Vim to read a dos encoded file as unix one. The net effect is that it will remove all \n's leaving \r's untouched and display them as ^M's in your buffer. Setting :set list will additionally show internal line-endings as $. After all, you see ^M$ in place of dos encoded line-breaks.

Also notice that :set list has nothing to do with showing ^M's. You can check it by yourself (make sure you have disabled list option first) by inserting single CR using CTRL-V followed by Enter in insert mode. After writing buffer to disc and opening it again you will see ^M despite list option being set to 0.

You can find more about file formats on http://vim.wikia.com/wiki/File_format or by typing:help 'fileformat' in Vim.

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

Pretty-Print JSON Data to a File using Python

You can parse the JSON, then output it again with indents like this:

import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)

See http://docs.python.org/library/json.html for more info.

How to erase the file contents of text file in Python?

In python:

open('file.txt', 'w').close()

Or alternatively, if you have already an opened file:

f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+

In C++, you could use something similar.

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

C# DataRow Empty-check

public static bool AreAllCellsEmpty(DataRow row)
{
  if (row == null) throw new ArgumentNullException("row");

  for (int i = row.Table.Columns.Count - 1; i >= 0; i--)
    if (!row.IsNull(i))
      return false;

  return true;
}

ActiveRecord find and only return selected columns

My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

Convert Unicode to ASCII without errors in Python

For broken consoles like cmd.exe and HTML output you can always use:

my_unicode_string.encode('ascii','xmlcharrefreplace')

This will preserve all the non-ascii chars while making them printable in pure ASCII and in HTML.

WARNING: If you use this in production code to avoid errors then most likely there is something wrong in your code. The only valid use case for this is printing to a non-unicode console or easy conversion to HTML entities in an HTML context.

And finally, if you are on windows and use cmd.exe then you can type chcp 65001 to enable utf-8 output (works with Lucida Console font). You might need to add myUnicodeString.encode('utf8').

How to find the array index with a value?

Use indexOf

imageList.indexOf(200)

iPhone Safari Web App opens links in new window

I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
    if ($(this).attr('target') !== '_blank') {
        e.preventDefault();
        window.location = $(this).attr('href');
    }
});

How to have multiple colors in a Windows batch file?

Without external tools.This is a self-compiled bat/.net hybrid (should be saved as .BAT) that can be used on any system that have installed .net framework (it's a rare thing to see an windows without .NET framework even for the oldest XP/2003 installations) . It uses jscript.net compiler to create an exe capable to print strings with different background/foreground color only for the current line.

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal

for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)

%~n0.exe %*

endlocal & exit /b %errorlevel%

*/

import System;

var arguments:String[] = Environment.GetCommandLineArgs();

var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;


//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
  'n': '\n',
  'r': '\r',
  't': '\t',
  'f': '\f',
  'v': '\v',
  'b': '\b'
};

function decodeJsEscape(_, hex0, hex1, octal, other) {
  var hex = hex0 || hex1;
  if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
  if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
  return jsEscapes[other] || other;
}

function decodeJsString(s) {
  return s.replace(
      // Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
      // octal in group 3, and arbitrary other single-character escapes in group 4.
      /\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
      decodeJsEscape);
}


function printHelp( ) {
   print( arguments[0] + "  -s string [-f foreground] [-b background] [-n] [-e]" );
   print( " " );
   print( " string          String to be printed" );
   print( " foreground      Foreground color - a " );
   print( "                 number between 0 and 15." );
   print( " background      Background color - a " );
   print( "                 number between 0 and 15." );
   print( " -n              Indicates if a new line should" );
   print( "                 be written at the end of the ");
   print( "                 string(by default - no)." );
   print( " -e              Evaluates special character " );
   print( "                 sequences like \\n\\b\\r and etc ");
   print( "" );
   print( "Colors :" );
   for ( var c = 0 ; c < 16 ; c++ ) {

        Console.BackgroundColor = c;
        Console.Write( " " );
        Console.BackgroundColor=currentBackground;
        Console.Write( "-"+c );
        Console.WriteLine( "" );
   }
   Console.BackgroundColor=currentBackground;



}

function errorChecker( e:Error ) {
        if ( e.message == "Input string was not in a correct format." ) {
            print( "the color parameters should be numbers between 0 and 15" );
            Environment.Exit( 1 );
        } else if (e.message == "Index was outside the bounds of the array.") {
            print( "invalid arguments" );
            Environment.Exit( 2 );
        } else {
            print ( "Error Message: " + e.message );
            print ( "Error Code: " + ( e.number & 0xFFFF ) );
            print ( "Error Name: " + e.name );
            Environment.Exit( 666 );
        }
}

function numberChecker( i:Int32 ){
    if( i > 15 || i < 0 ) {
        print("the color parameters should be numbers between 0 and 15");
        Environment.Exit(1);
    }
}


if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help"   ) {
    printHelp();
    Environment.Exit(0);
}

for (var arg = 1; arg <= arguments.length-1; arg++ ) {
    if ( arguments[arg].toLowerCase() == "-n" ) {
        newLine=true;
    }

    if ( arguments[arg].toLowerCase() == "-e" ) {
        evaluate=true;
    }

    if ( arguments[arg].toLowerCase() == "-s" ) {
        output=arguments[arg+1];
    }


    if ( arguments[arg].toLowerCase() == "-b" ) {

        try {
            backgroundColor=Int32.Parse( arguments[arg+1] );
        } catch(e) {
            errorChecker(e);
        }
    }

    if ( arguments[arg].toLowerCase() == "-f" ) {
        try {
            foregroundColor=Int32.Parse(arguments[arg+1]);
        } catch(e) {
            errorChecker(e);
        }
    }
}

Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;

if ( evaluate ) {
    output=decodeJsString(output);
}

if ( newLine ) {
    Console.WriteLine(output);  
} else {
    Console.Write(output);

}

Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;

Example coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e

You can also check carlos' color function -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453

How to remove unused imports in Intellij IDEA on commit?

When you commit, tick the Optimize imports option on the right. This will become the default until you change it.

I prefer using the Reformat code option as well.

Creating a UIImage from a UIColor to use as a background image for UIButton

Are you using ARC? The problem here is that you don't have a reference to the UIColor object that you're trying to apply; the CGColor is backed by that UIColor, but ARC will deallocate the UIColor before you have a chance to use the CGColor.

The clearest solution is to have a local variable pointing to your UIColor with the objc_precise_lifetime attribute.

You can read more about this exact case on this article about UIColor and short ARC lifetimes or get more details about the objc_precise_lifetime attribute.

How can I get the content of CKEditor using JQuery?

version 4.8.0

$('textarea').data('ckeditorInstance').getData();

UIButton title text color

use

Objective-C

[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];

Swift

headingButton.setTitleColor(.black, for: .normal)

How do I create a simple 'Hello World' module in Magento?

I will rather recommend Mage2Gen, this will help you generate the boilerplate and you can just focus on the core business logic. it just helps speed up the things.

How to type a new line character in SQL Server Management Studio

You can't.

Use a "new query" window instead, and do a manual update:

UPDATE mytable
SET textvalue = 
'This text
can include
line breaks'
WHERE rowid = 1234

How to prevent long words from breaking my div?

Two fixes:

  1. overflow:scroll -- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden -- just cuts off any overflow. It means people can't read the content though.

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-word doesn't appear to work in Firefox).

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

Edit 2 (to address your comment below):

Start off using the CSS overflow property isn't perfect but it stops designs breaking. Apply overflow:hidden first. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:auto or overflow:scroll instead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenator a look in (as mentioned below).

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

Setting up Gradle for api 26 (Android)

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 compile 'com.android.support:appcompat-v7:26.0.1'
    compile 'com.android.support:recyclerview-v7:26.0.1'
    compile 'com.android.support:cardview-v7:26.0.1'

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

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

How to get the difference between two dictionaries in Python?

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

how do I get a new line, after using float:left?

Also such way

<br clear="all" />

How to Display Selected Item in Bootstrap Button Dropdown Title

you need to use add class open in <div class="btn-group open">

and in li add class="active"

Jquery resizing image

So much code here, but I think this is the best answer

function resize() {
            var input = $("#picture");
            var maxWidth = 300;
            var maxHeight = 300;
            var width = input.width();
            var height = input.height();
            var ratioX = (maxWidth / width);
            var ratioY = (maxHeight / height);
            var ratio = Math.min(ratioX, ratioY);

            var newWidth  = (width * ratio);
            var newHeight = (height * ratio);
            input.css("width", newWidth);
            input.css("height", newHeight);
};

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

I found using jQuery was my best solution.

$( "#my_number_field" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

Comparing two .jar files

In Linux/CygWin a handy script I use at times is:

#Extract the jar (war or ear)
cd dir1
jar xvf jar-file1
for i in `ls *.class`
do
 javap $i > ${i}.txt #list the functions/variables etc
done

cd dir2
jar xvf jar-file2
for i in `ls *.class`
do
 javap $i > ${i}.txt #list the functions/variables etc
done

diff -r dir1 dir2 #diff recursively

Scanner only reads first word instead of line

Javadoc to the rescue :

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

nextLine is probably the method you should use.

Android background music service

Create a foreground service with the START_STICKY flag.

@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
   if (startIntent != null) {
       String action = startIntent.getAction();
       String command = startIntent.getStringExtra(CMD_NAME);
       if (ACTION_CMD.equals(action)) {
           if (CMD_PAUSE.equals(command)) {
               if (mPlayback != null && mPlayback.isPlaying()) {
                   handlePauseRequest();
               }
           } else if (CMD_PLAY.equals(command)) {
               ArrayList<Track> queue = new ArrayList<>();
               for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
                   queue.add((Track) Parcels.unwrap(input));
               }
               int index = startIntent.getIntExtra(ARG_INDEX, 0);
               playWithQueue(queue, index);
           }
       }
   }

   return START_STICKY;
}

This can then be called from any activity to play some music

Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)

You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.

Here's a good tutorial about Playing music in the background on Android

How to add a new row to an empty numpy array

In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.

for i in range(0,len(0,100)):
    SOMECALCULATEDARRAY = .......
    if(i==0):
        finalArrayCollection = SOMECALCULATEDARRAY
    else:
        finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)

This is mainly useful when the shape of the array is unknown

Show and hide a View with a slide up/down animation

you can slide up and down any view or layout by using bellow code in android app

boolean isClicked=false;
LinearLayout mLayoutTab = (LinearLayout)findViewById(R.id.linearlayout);

        if(isClicked){
                    isClicked = false;
                    mLayoutTab.animate()
                    .translationYBy(120)
                    .translationY(0)     
                    .setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));

        }else{
                isClicked = true;
                mLayoutTab.animate()
                .translationYBy(0)
                .translationY(120)
                .setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
                }

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

Java program to connect to Sql Server and running the sample query From Eclipse

Add sqlserver.jar Here is link

As the name suggests ClassNotFoundException in Java is a subclass of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and doesn't found the requested class in classpath.

Another important point about this Exception is that, It is a checked Exception and you need to provide explicitly Exception handling while using methods which can possibly throw ClassNotFoundException in java either by using try-catch block or by using throws clause.

Oracle docs

public class ClassNotFoundException
 extends ReflectiveOperationException

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

Svn switch from trunk to branch

You don't need to --relocate since the branch is within the same repository URL. Just do:

svn switch https://www.example.com/svn/branches/v1p2p3

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Difference between Spring, Struts and Hibernate are following:

  1. Spring is an Application Framework but Struts and hibernate is not.
  2. Spring and Hibernate are Light weighted but Struts 2 is not.
  3. Spring and Hibernate has layered architecture but Struts 2 doesn't.
  4. Spring and Hibernate support loose coupling but Struts 2 doesn't.
  5. Struts 2 and Hibernate have tag library but Spring doesn't.
  6. Spring and Hibernate have easy integration with ORM technologies but Struts doesn't.
  7. Struts 2 has easy integration with client-side technologies but Spring and Hibernate don't have.

Find the PID of a process that uses a port on Windows

If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:

$processPID =  $($(netstat -aon | findstr "9999")[0] -split '\s+')[-1]
taskkill /f /pid $processPID

However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr "0.0.0.0:9999" will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999 in it, like this:

TCP    0.0.0.0:9999                        0.0.0.0:0       LISTENING       15776
UDP    [fe80::81ad:9999:d955:c4ca%2]:1900  *:*                             12331

The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.

How to check java bit version on Linux?

Why don't you examine System.getProperty("os.arch") value in your code?

How to show all privileges from a user in oracle?

More simpler single query oracle version.

WITH data 
     AS (SELECT granted_role 
         FROM   dba_role_privs 
         CONNECT BY PRIOR granted_role = grantee 
         START WITH grantee = '&USER') 
SELECT 'SYSTEM'     typ, 
       grantee      grantee, 
       privilege    priv, 
       admin_option ad, 
       '--'         tabnm, 
       '--'         colnm, 
       '--'         owner 
FROM   dba_sys_privs 
WHERE  grantee = '&USER' 
        OR grantee IN (SELECT granted_role 
                       FROM   data) 
UNION 
SELECT 'TABLE'    typ, 
       grantee    grantee, 
       privilege  priv, 
       grantable  ad, 
       table_name tabnm, 
       '--'       colnm, 
       owner      owner 
FROM   dba_tab_privs 
WHERE  grantee = '&USER' 
        OR grantee IN (SELECT granted_role 
                       FROM   data) 
ORDER  BY 1; 

What's a concise way to check that environment variables are set in a Unix shell script?

In my opinion the simplest and most compatible check for #!/bin/sh is:

if [ "$MYVAR" = "" ]
then
   echo "Does not exist"
else
   echo "Exists"
fi

Again, this is for /bin/sh and is compatible also on old Solaris systems.

How to get an array of unique values from an array containing duplicates in JavaScript?

function array_unique(arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i]);
        }
    }
    return result;
}

Not a built in function. If the product list does not contain the item, add it to unique list and return unique list.

Setting the focus to a text field

None of the above worked for me, because my window is a JPopupMenu.

What did work was this:

addAncestorListener(new AncestorListener() {
    @Override
    public void ancestorAdded(AncestorEvent ae) {
        myEdit.requestFocus();
    }

    // ... other ancestor listener methods
}

counting number of directories in a specific directory

find is also printing the directory itself:

$ find .vim/ -maxdepth 1 -type d
.vim/
.vim/indent
.vim/colors
.vim/doc
.vim/after
.vim/autoload
.vim/compiler
.vim/plugin
.vim/syntax
.vim/ftplugin
.vim/bundle
.vim/ftdetect

You can instead test the directory's children and do not descend into them at all:

$ find .vim/* -maxdepth 0 -type d
.vim/after
.vim/autoload
.vim/bundle
.vim/colors
.vim/compiler
.vim/doc
.vim/ftdetect
.vim/ftplugin
.vim/indent
.vim/plugin
.vim/syntax

$ find .vim/* -maxdepth 0 -type d | wc -l
11
$ find .vim/ -maxdepth 1 -type d | wc -l
12

You can also use ls:

$ ls -l .vim | grep -c ^d
11


$ ls -l .vim
total 52
drwxrwxr-x  3 anossovp anossovp 4096 Aug 29  2012 after
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 autoload
drwxrwxr-x 13 anossovp anossovp 4096 Aug 29  2012 bundle
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 colors
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 compiler
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 doc
-rw-rw-r--  1 anossovp anossovp   48 Aug 29  2012 filetype.vim
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftdetect
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftplugin
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 indent
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 plugin
-rw-rw-r--  1 anossovp anossovp 2505 Aug 29  2012 README.rst
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 syntax

$ ls -l .vim | grep ^d
drwxrwxr-x  3 anossovp anossovp 4096 Aug 29  2012 after
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 autoload
drwxrwxr-x 13 anossovp anossovp 4096 Aug 29  2012 bundle
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 colors
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 compiler
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 doc
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftdetect
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftplugin
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 indent
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 plugin
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 syntax

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub