Programs & Examples On #Ioc container

In object oriented languages, an inversion of control container (ioc-container) can be used for configuring and managing objects in an application.

How do the major C# DI/IoC frameworks compare?

Disclaimer: As of early 2015, there is a great comparison of IoC Container features from Jimmy Bogard, here is a summary:

Compared Containers:

  • Autofac
  • Ninject
  • Simple Injector
  • StructureMap
  • Unity
  • Windsor

The scenario is this: I have an interface, IMediator, in which I can send a single request/response or a notification to multiple recipients:

public interface IMediator 
{ 
    TResponse Send<TResponse>(IRequest<TResponse> request);

    Task<TResponse> SendAsync<TResponse>(IAsyncRequest<TResponse> request);

    void Publish<TNotification>(TNotification notification)
        where TNotification : INotification;

    Task PublishAsync<TNotification>(TNotification notification)
        where TNotification : IAsyncNotification; 
}

I then created a base set of requests/responses/notifications:

public class Ping : IRequest<Pong>
{
    public string Message { get; set; }
}
public class Pong
{
    public string Message { get; set; }
}
public class PingAsync : IAsyncRequest<Pong>
{
    public string Message { get; set; }
}
public class Pinged : INotification { }
public class PingedAsync : IAsyncNotification { }

I was interested in looking at a few things with regards to container support for generics:

  • Setup for open generics (registering IRequestHandler<,> easily)
  • Setup for multiple registrations of open generics (two or more INotificationHandlers)

Setup for generic variance (registering handlers for base INotification/creating request pipelines) My handlers are pretty straightforward, they just output to console:

public class PingHandler : IRequestHandler<Ping, Pong> { /* Impl */ }
public class PingAsyncHandler : IAsyncRequestHandler<PingAsync, Pong> { /* Impl */ }

public class PingedHandler : INotificationHandler<Pinged> { /* Impl */ }
public class PingedAlsoHandler : INotificationHandler<Pinged> { /* Impl */ }
public class GenericHandler : INotificationHandler<INotification> { /* Impl */ }

public class PingedAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
public class PingedAlsoAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }

Autofac

var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, explicitly

Ninject

var kernel = new StandardKernel();
kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>()
    .SelectAllClasses()
    .BindDefaultInterface());
kernel.Bind(scan => scan.FromAssemblyContaining<Ping>()
    .SelectAllClasses()
    .BindAllInterfaces());
kernel.Bind<TextWriter>().ToConstant(Console.Out);
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, with user-built extensions

Simple Injector

var container = new Container();
var assemblies = GetAssemblies().ToArray();
container.Register<IMediator, Mediator>();
container.Register(typeof(IRequestHandler<,>), assemblies);
container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
  • Open generics: yes, explicitly
  • Multiple open generics: yes, explicitly
  • Generic contravariance: yes, implicitly (with update 3.0)

StructureMap

var container = new Container(cfg =>
{
    cfg.Scan(scanner =>
    {
        scanner.AssemblyContainingType<Ping>();
        scanner.AssemblyContainingType<IMediator>();
        scanner.WithDefaultConventions();
        scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
        scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>));
        scanner.AddAllTypesOf(typeof(INotificationHandler<>));
        scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>));
    });
});
  • Open generics: yes, explicitly
  • Multiple open generics: yes, explicitly
  • Generic contravariance: yes, implicitly

Unity

container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly),
   WithMappings.FromAllInterfaces,
   GetName,
   GetLifetimeManager);

/* later down */

static bool IsNotificationHandler(Type type)
{
    return type.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(INotificationHandler<>) || x.GetGenericTypeDefinition() == typeof(IAsyncNotificationHandler<>)));
}

static LifetimeManager GetLifetimeManager(Type type)
{
    return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
}

static string GetName(Type type)
{
    return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
}
  • Open generics: yes, implicitly
  • Multiple open generics: yes, with user-built extension
  • Generic contravariance: derp

Windsor

var container = new WindsorContainer();
container.Register(Classes.FromAssemblyContaining<IMediator>().Pick().WithServiceAllInterfaces());
container.Register(Classes.FromAssemblyContaining<Ping>().Pick().WithServiceAllInterfaces());
container.Kernel.AddHandlersFilter(new ContravariantFilter());
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, with user-built extension

Why do I need an IoC container as opposed to straightforward DI code?

I just so happen to be in the process of yanking out home grown DI code and replacing it with an IOC. I have probably removed well over 200 lines of code and replaced it with about 10. Yes, I had to do a little bit of learning on how to use the container (Winsor), but I'm an engineer working on internet technologies in the 21st century so I'm used to that. I probably spent about 20 minutes looking over the how tos. This was well worth my time.

How does autowiring work in Spring?

Standard way:

@RestController
public class Main {
    UserService userService;

    public Main(){
        userService = new UserServiceImpl();
    }

    @GetMapping("/")
    public String index(){
        return userService.print("Example test");
    }
}

User service interface:

public interface UserService {
    String print(String text);
}

UserServiceImpl class:

public class UserServiceImpl implements UserService {
    @Override
    public String print(String text) {
        return text + " UserServiceImpl";
    }
}

Output: Example test UserServiceImpl

That is a great example of tight coupled classes, bad design example and there will be problem with testing (PowerMockito is also bad).

Now let's take a look at SpringBoot dependency injection, nice example of loose coupling:

Interface remains the same,

Main class:

@RestController
public class Main {
    UserService userService;

    @Autowired
    public Main(UserService userService){
        this.userService = userService;
    }

    @GetMapping("/")
    public String index(){
        return userService.print("Example test");
    }
}

ServiceUserImpl class:

@Component
public class UserServiceImpl implements UserService {
    @Override
    public String print(String text) {
        return text + " UserServiceImpl";
    }
}

Output: Example test UserServiceImpl

and now it's easy to write test:

@RunWith(MockitoJUnitRunner.class)
public class MainTest {
    @Mock
    UserService userService;

    @Test
    public void indexTest() {
        when(userService.print("Example test")).thenReturn("Example test UserServiceImpl");

        String result = new Main(userService).index();

        assertEquals(result, "Example test UserServiceImpl");
    }
}

I showed @Autowired annotation on constructor but it can also be used on setter or field.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

The namespace name http://www.w3.org/1999/xhtml 
is intended for use in various specifications such as:

Recommendations:

    XHTML™ 1.0: The Extensible HyperText Markup Language
    XHTML Modularization
    XHTML 1.1
    XHTML Basic
    XHTML Print
    XHTML+RDFa

Check here for more detail

How to return a resolved promise from an AngularJS Service using $q?

From your service method:

function serviceMethod() {
    return $timeout(function() {
        return {
            property: 'value'
        };
    }, 1000);
}

And in your controller:

serviceName
    .serviceMethod()
    .then(function(data){
        //handle the success condition here
        var x = data.property
    });

Changing the cursor in WPF sometimes works, sometimes doesn't

Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:

Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}

This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.

Send Email Intent

If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

I found this in https://developer.android.com/guide/components/intents-common.html#Email

CodeIgniter - accessing $config variable in view

$this->config->item('config_var') did not work for my case.

I could only use the config_item('config_var'); to echo variables in the view

How to select only the first rows for each unique value of a column?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on. Even if you added an order by to the end of your query, it would preserve the ordering in the over command when numbering.

select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1

Check if a value is in an array (C#)

   string[] array = { "cat", "dot", "perls" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

// Display bools.
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
----------------------------output-----------------------------------

1)True 2)False 3)True 4)False

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

python -m pip install --user opencv-contrib-python

After doing this just Restart your system and then if you are on Opencv >= 4.* use :
recognizer = cv2.face.LBPHFaceRecognizer_create()

This should solve 90% of the problem.

Java time-based map/cache with expiring keys

This is a sample implementation that i did for the same requirement and concurrency works well. Might be useful for someone.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author Vivekananthan M
 *
 * @param <K>
 * @param <V>
 */
public class WeakConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {

    private static final long serialVersionUID = 1L;

    private Map<K, Long> timeMap = new ConcurrentHashMap<K, Long>();
    private long expiryInMillis = 1000;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss:SSS");

    public WeakConcurrentHashMap() {
        initialize();
    }

    public WeakConcurrentHashMap(long expiryInMillis) {
        this.expiryInMillis = expiryInMillis;
        initialize();
    }

    void initialize() {
        new CleanerThread().start();
    }

    @Override
    public V put(K key, V value) {
        Date date = new Date();
        timeMap.put(key, date.getTime());
        System.out.println("Inserting : " + sdf.format(date) + " : " + key + " : " + value);
        V returnVal = super.put(key, value);
        return returnVal;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (K key : m.keySet()) {
            put(key, m.get(key));
        }
    }

    @Override
    public V putIfAbsent(K key, V value) {
        if (!containsKey(key))
            return put(key, value);
        else
            return get(key);
    }

    class CleanerThread extends Thread {
        @Override
        public void run() {
            System.out.println("Initiating Cleaner Thread..");
            while (true) {
                cleanMap();
                try {
                    Thread.sleep(expiryInMillis / 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void cleanMap() {
            long currentTime = new Date().getTime();
            for (K key : timeMap.keySet()) {
                if (currentTime > (timeMap.get(key) + expiryInMillis)) {
                    V value = remove(key);
                    timeMap.remove(key);
                    System.out.println("Removing : " + sdf.format(new Date()) + " : " + key + " : " + value);
                }
            }
        }
    }
}


Git Repo Link (With Listener Implementation)

https://github.com/vivekjustthink/WeakConcurrentHashMap

Cheers!!

How to use OrderBy with findAll in Spring Data

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public List<StudentEntity> findAllByOrderByIdAsc();
}

The code above should work. I'm using something similar:

public List<Pilot> findTop10ByOrderByLevelDesc();

It returns 10 rows with the highest level.

IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:

findAllByOrderByIdAsc(); // don't miss "by"
       ^

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

Programmatically check Play Store for app updates

You can get current Playstore Version using JSoup with some modification like below:

@Override
protected String doInBackground(Void... voids) {

    String newVersion = null;
    try {
        newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
                .timeout(30000)
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get()
                .select(".hAyfc .htlgb")
                .get(7)
                .ownText();
        return newVersion;
    } catch (Exception e) {
        return newVersion;
    }
}

@Override
protected void onPostExecute(String onlineVersion) {
    super.onPostExecute(onlineVersion);

    Log.d("update", "playstore version " + onlineVersion);
}

answer of @Tarun is not working anymore.

Windows command for file size only

Use a function to get rid off some limitation in the ~z operator. It is especially useful with a for loop:

@echo off
set size=0
call :filesize "C:\backup\20120714-0035\error.log"
echo file size is %size%
goto :eof

:: Set filesize of first argument in %size% variable, and return
:filesize
  set size=%~z1
  exit /b 0

What would be the Unicode character for big bullet in the middle of the character?

You can search for “bullet” when using e.g. BabelPad (which has a Character Map where you can search by character name), but you will hardly find anything larger than U+2022 BULLET (though the size depends on font). Searching for “circle” finds many characters, too many, as the string appears in so many names. The largest simple circle is probably U+25CF BLACK CIRCLE “?”. If it’s too large U+26AB MEDIUM BLACK CIRCLE “?” might be suitable.

Beware that few fonts contain these characters.

Mysql command not found in OS X 10.7

I had same issue after installing mariadb via HomeBrew, brew doctor suggested to run brew link mariadb - which fixed the issue.

Subprocess changing directory

subprocess.call and other methods in the subprocess module have a cwd parameter.

This parameter determines the working directory where you want to execute your process.

So you can do something like this:

subprocess.call('ls', shell=True, cwd='path/to/wanted/dir/')

Check out docs subprocess.popen-constructor

Copy all the lines to clipboard

On Ubuntu 12

you might try to install the vim-gnome package:

sudo apt-get install vim-gnome

I tried it, because vim --version told me that it would have the flag xterm_clipboard disabled (indicated by - ), which is needed in order to use the clipboard functionality.

-> installing the vim-gnome package on Ubuntu 12 also installed a console based version of vim, that has this option enabled (indicated by a + before the xterm_clipboard flag)

On Arch Linux

you may install vim-clipboard for the same reason.

If you run neovim then you should install xclip (as explained by help clipboard-tool)

How to set the matplotlib figure default size in ipython notebook?

If you don't have this ipython_notebook_config.py file, you can create one by following the readme and typing

ipython profile create

Can an int be null in Java?

A great way to find out:

public static void main(String args[]) {
    int i = null;
}

Try to compile.

BAT file to map to network drive without running as admin

@echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass

net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"

echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%

cscript /nologo %SCRIPT%
del %SCRIPT%

Finding duplicate values in a SQL table

SELECT id, COUNT(id) FROM table1 GROUP BY id HAVING COUNT(id)>1;

I think this will work properly to search repeated values in a particular column.

How can I recover a lost commit in Git?

Sadly git is so unrelable :( I just lost 2 days of work :(

It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.

I learned my lesson - next time backup first and only then commit. Never trust git for anything.

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

How do I convert a Python 3 byte-string variable into a regular string?

You had it nearly right in the last line. You want

str(bytes_string, 'utf-8')

because the type of bytes_string is bytes, the same as the type of b'abc'.

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/

How do I force my .NET application to run as administrator?

The detailed steps are as follow.

  1. Add application manifest file to solution
  2. Change application setting to "app.manifest"
  3. Update tag of "requestedExecutionLevel" to requireAdministrator.

Adding file in Solution

Select Application Manifest File

Select Manifest option

Update Manifest file

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security

How to create a jar with external libraries included in Eclipse?

You could use the Export->Java->Runnable Jar to create a jar that includes its dependencies

Alternatively, you could use the fatjar eclipse plugin as well to bundle jars together

How can I check if an InputStream is empty without reading from it?

Without reading you can't do this. But you can use a work around like below.

You can use mark() and reset() methods to do this.

mark(int readlimit) method marks the current position in this input stream.

reset() method repositions this stream to the position at the time the mark method was last called on this input stream.

Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.

The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.

To apply this functionalities for this use case, we need to mark the position as 0 and then read the input stream. There after we need to reset the input stream and the input stream will be reverted to the original one.

    if (inputStream.markSupported()) {
          inputStream.mark(0);
          if (inputStream.read() != -1) {
               inputStream.reset();
          } else {
               //Inputstream is empty
          }
    }

Here if the input stream is empty then read() method will return -1.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Convert normal date to unix timestamp

You can use Date.parse(), but the input formats that it accepts are implementation-dependent. However, if you can convert the date to ISO format (YYYY-MM-DD), most implementations should understand it.

See Why does Date.parse give incorrect results?.

What are the obj and bin folders (created by Visual Studio) used for?

The obj directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.

You can change the actual directories used for both purposes within the project settings, if you like.

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

What is the difference between git pull and git fetch + git rebase?

It should be pretty obvious from your question that you're actually just asking about the difference between git merge and git rebase.

So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:

- o - o - o - H - A - B - C (master)
               \
                P - Q - R (origin/master)

If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:

- o - o - o - H - A - B - C - X (master)
               \             /
                P - Q - R --- (origin/master)

If on the other hand you did the appropriate rebase, you'd end up with this:

- o - o - o - H - P - Q - R - A' - B' - C' (master)
                          |
                          (origin/master)

The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R), instead of where you originally committed (H). You should never use the rebase approach if someone else has already pulled from your master branch.

Finally, note that you can actually set up git pull for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase to true. You can also do this for a single pull using git pull --rebase.

Killing a process using Java

Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().

import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);

And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:

Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
    Field f = proc.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    int pid = f.get(proc);
}

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Get exit code for command in bash/ksh

Below is the fixed code:

#!/bin/ksh
safeRunCommand() {
  typeset cmnd="$*"
  typeset ret_code

  echo cmnd=$cmnd
  eval $cmnd
  ret_code=$?
  if [ $ret_code != 0 ]; then
    printf "Error : [%d] when executing command: '$cmnd'" $ret_code
    exit $ret_code
  fi
}

command="ls -l | grep p"
safeRunCommand "$command"

Now if you look into this code few things that I changed are:

  • use of typeset is not necessary but a good practice. It make cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand "$command". If you dont then cmnd will get only the value ls and not ls -l. And it is even more important if your command contains pipes.
  • you can use typeset cmnd="$*" instead of typeset cmnd="$1" if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • eval is used to evaluate so that command containing pipes can work fine

NOTE: Do remember some commands give 1 as return code even though there is no error like grep. If grep found something it will return 0 else 1.

I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.

How to import or copy images to the "res" folder in Android Studio?

For Android Studio:

Right click on res, new Image Asset

Select the image radio button in 3rd option i.e Asset Type

Select the path of the image and click next and then finish

All the images are added to the respective folder, its very simple

ASP.NET custom error page - Server.GetLastError() is null

A combination of what NailItDown and Victor said. The preferred/easiest way is to use your Global.Asax to store the error and then redirect to your custom error page.

Global.asax:

    void Application_Error(object sender, EventArgs e) 
{
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError();
    Application["TheException"] = ex; //store the error for later
    Server.ClearError(); //clear the error so we can continue onwards
    Response.Redirect("~/myErrorPage.aspx"); //direct user to error page
}

In addition, you need to set up your web.config:

  <system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/myErrorPage.aspx">
    </customErrors>
  </system.web>

And finally, do whatever you need to with the exception you've stored in your error page:

protected void Page_Load(object sender, EventArgs e)
{

    // ... do stuff ...
    //we caught an exception in our Global.asax, do stuff with it.
    Exception caughtException = (Exception)Application["TheException"];
    //... do stuff ...
}

How do I compile the asm generated by GCC?

If you have main.s file. you can generate object file by GCC and also as

# gcc -c main.s
# as main.s -o main.o

check this link, it will help you learn some binutils of GCC http://www.thegeekstuff.com/2017/01/gnu-binutils-commands/

Select statement to find duplicates on certain fields

To get the list of fields for which there are multiple records, you can use..

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

Check this link for more information on how to delete the rows.

http://support.microsoft.com/kb/139444

There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.

How do I find the install time and date of Windows?

In regedit.exe go to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate

It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.)

To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this Unix Time Conversion online tool.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Convert data.frame columns from factors to characters

Or you can try transform:

newbob <- transform(bob, phenotype = as.character(phenotype))

Just be sure to put every factor you'd like to convert to character.

Or you can do something like this and kill all the pests with one blow:

newbob_char <- as.data.frame(lapply(bob[sapply(bob, is.factor)], as.character), stringsAsFactors = FALSE)
newbob_rest <- bob[!(sapply(bob, is.factor))]
newbob <- cbind(newbob_char, newbob_rest)

It's not good idea to shove the data in code like this, I could do the sapply part separately (actually, it's much easier to do it like that), but you get the point... I haven't checked the code, 'cause I'm not at home, so I hope it works! =)

This approach, however, has a downside... you must reorganize columns afterwards, while with transform you can do whatever you like, but at cost of "pedestrian-style-code-writting"...

So there... =)

Display image as grayscale using matplotlib

I would use the get_cmap method. Ex.:

import matplotlib.pyplot as plt

plt.imshow(matrix, cmap=plt.get_cmap('gray'))

Is it possible to set ENV variables for rails development environment in my code?

I think the best way is to store them in some yml file and then load that file using this command in intializer file

APP_CONFIG = YAML.load_file("#{Rails.root}/config/CONFIG.yml")[Rails.env].to_hash

you can easily access environment related config variables.

Your Yml file key value structure:

development:
  app_key: 'abc'
  app_secret: 'abc'

production:
  app_key: 'xyz'
  app_secret: 'ghq'

PHP refresh window? equivalent to F5 page reload?

<?php 
echo "<script>window.opener.location.reload();</script>";
echo "<script>window.close();</script>";
?>

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

In place of 1.+ use the latest version of crashlytics -

 dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
    }

you should use this way -

dependencies {
            classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
        }

your problem will be resolved for sure. Happy coding !!

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

Handling a Menu Item Click Event - Android

This code is work for me

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

     if (id == R.id.action_settings) {
  // add your action here that you want
        return true;
    }

    else if (id==R.id.login)
     {
         // add your action here that you want
     }


    return super.onOptionsItemSelected(item);
}

PHPExcel auto size column width

If you try to iterate with for ($col = 2; $col <= 'AC'; ++ $col){...}, or with foreach(range('A','AC') as $col) {...} it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AC').

In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:

$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
    for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
    $col = PHPExcel_Cell::stringFromColumnIndex($index);

    // do something, like set the column width...
    $sheet->getColumnDimension($col)->setAutoSize(TRUE);
}

With this, you easy iterate pass the 'Z' column and set autosize to every column.

Responsive web design is working on desktop but not on mobile device

Responsive meta tag

To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>.

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

Linux command to check if a shell script is running or not

The solutions above are great for interactive use, where you can eyeball the result and weed out false positives that way.

False positives can occur if the executable itself happens to match, or any arguments that are not script names match - the likelihood is greater with scripts that have no filename extensions.

Here's a more robust solution for scripting, using a shell function:

getscript() {
  pgrep -lf ".[ /]$1( |\$)"
}

Example use:

# List instance(s) of script "aa.sh" that are running.
getscript "aa.sh"  # -> (e.g.): 96112 bash /Users/jdoe/aa.sh

# Use in a test:
if getscript "aa.sh" >/dev/null; then
  echo RUNNING
fi
  • Matching is case-sensitive (on macOS, you could add -i to the pgrep call to make it case-insensitive; on Linux, that is not an option.)
  • The getscript function also works with full or partial paths that include the filename component; partial paths must not start with / and each component specified must be complete. The "fuller" the path specified, the lower the risk of false positives. Caveat: path matching will only work if the script was invoked with a path - this is generally true for scripts in the $PATH that are invoked directly.
  • Even this function cannot rule out all false positives, as paths can have embedded spaces, yet neither ps nor pgrep reflect the original quoting applied to the command line. All the function guarantees is that any match is not the first token (which is the interpreter), and that it occurs as a separate word, optionally preceded by a path.
  • Another approach to minimizing the risk of false positives could be to match the executable name (i.e., interpreter, such as bash) as well - assuming it is known; e.g.
# List instance(s) of a running *bash* script.
getbashscript() {
  pgrep -lf "(^|/)bash( | .*/)$1( |\$)"
}

If you're willing to make further assumptions - such as script-interpreter paths never containing embedded spaces - the regexes could be made more restrictive and thus further reduce the risk of false positives.

How best to read a File into List<string>

A little update to Evan Mulawski answer to make it shorter

List<string> allLinesText = File.ReadAllLines(fileName).ToList()

Eclipse not recognizing JVM 1.8

Here are steps:

  • download 1.8 JDK from this site
  • install it
  • copy the jre folder & paste it in "C:\Program Files (x86)\EclipseNeon\"
  • rename the folder to "jre"
  • start the eclipse again

It should work.

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

Tab separated values in awk

Make sure they're really tabs! In bash, you can insert a tab using C-v TAB

$ echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Validate decimal numbers in JavaScript - IsNumeric()

I think my code is perfect ...

_x000D_
_x000D_
/**_x000D_
 * @param {string} s_x000D_
 * @return {boolean}_x000D_
 */_x000D_
var isNumber = function(s) {_x000D_
    return s.trim()!=="" && !isNaN(Number(s));_x000D_
};
_x000D_
_x000D_
_x000D_

How do I format axis number format to thousands with a comma in matplotlib?

Short answer without importing matplotlib as mpl

plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))

Modified from @AlexG's answer

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

How to vertically center a "div" element for all browsers using CSS?

For new comers please try

display: flex;
align-items: center;
justify-content: center;

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

Polished version + case ignoring support:

public static int[] AllIndexesOf(string str, string substr, bool ignoreCase = false)
{
    if (string.IsNullOrWhiteSpace(str) ||
        string.IsNullOrWhiteSpace(substr))
    {
        throw new ArgumentException("String or substring is not specified.");
    }

    var indexes = new List<int>();
    int index = 0;

    while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
    {
        indexes.Add(index++);
    }

    return indexes.ToArray();
}

ArrayList insertion and retrieval order

If you always add to the end, then each element will be added to the end and stay that way until you change it.

If you always insert at the start, then each element will appear in the reverse order you added them.

If you insert them in the middle, the order will be something else.

Convert an integer to a float number

There is no float type. Looks like you want float64. You could also use float32 if you only need a single-precision floating point value.

package main

import "fmt"

func main() {
    i := 5
    f := float64(i)
    fmt.Printf("f is %f\n", f)
}

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

The above assumes that you have a folder called CSS in the root of your website like this:

http://www.website.com/CSS/Style.css

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

You can't do it client-side. You'll have to do it on the server.

Edit: This answer is outdated!

As the time of this edit, HTML file API is now supported on all major browsers.

I'd provide an update with solution, but @mark.inman.winning already did it.

Keep in mind that even if it's now possible to validate on the client, you should still validate it on the server, though. All client side validations can be bypassed.

How to force a UIViewController to Portrait orientation in iOS 6

This answer relates to the questions asked in the comments of the OP's post:

To force a view to appear in a given oriention put the following in viewWillAppear:

UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
    UIViewController *c = [[UIViewController alloc]init];
    [self presentModalViewController:c animated:NO];
    [self dismissModalViewControllerAnimated:NO];
}

It's a bit of a hack, but this forces the UIViewController to be presented in portrait even if the previous controller was landscape

UPDATE for iOS7

The methods above are now deprecated, so for iOS 7 use the following:

UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
     UIViewController *c = [[UIViewController alloc]init];
     [c.view setBackgroundColor:[UIColor redColor]];
     [self.navigationController presentViewController:c animated:NO completion:^{
            [self.navigationController dismissViewControllerAnimated:YES completion:^{
            }];
     }];
}

Interestingly, at the time of writing, either the present or dismiss must be animated. If neither are, then you will get a white screen. No idea why this makes it work, but it does! The visual effect is different depending on which is animated.

Formatting a double to two decimal places

I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.

With this option you can even have a configurable number of decimal places:

public string ValueAsString(double value, int decimalPlaces)
{
    return value.ToString($"F{decimalPlaces}");
}

Delete default value of an input text on click

This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:

<script>
function onBlur(el) {
    if (el.value == '') {
        el.value = el.defaultValue;
    }
}
function onFocus(el) {
    if (el.value == el.defaultValue) {
        el.value = '';
    }
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>

pip install returning invalid syntax

Don't enter in the python shall, Install in the command directory.

Not inside the python pip cannot be installed inside the python.

Even in the version 3.+ you don't have to write the python 3 instead just python.

which looks like

python -m pip install --upgrade pip

and then install others

python -m pip install jupyter

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

How to use "raise" keyword in Python

You can use it to raise errors as part of error-checking:

if (a < b):
    raise ValueError()

Or handle some errors, and then pass them on as part of error-handling:

try:
    f = open('file.txt', 'r')
except IOError:
    # do some processing here
    # and then pass the error on
    raise

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

How to get the insert ID in JDBC?

With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query

INSERT INTO bla (a,b) VALUES (2,3) RETURNING id

like

INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1

if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).

jQuery date formatting

Just use this:

var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);

How to get current date & time in MySQL?

The correct answer is SYSDATE().

INSERT INTO servers (
    server_name, online_status, exchange, disk_space,
    network_shares, date_time
)
VALUES (
    'm1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE', SYSDATE()
);

We can change this behavior and make NOW() behave in the same way as SYSDATE() by setting sysdate_is_now command line argument to True.

Note that NOW() (which has CURRENT_TIMESTAMP() as an alias), differs from SYSDATE() in a subtle way:

SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.)

As indicated by Erandi, it is best to create your table with the DEFAULT clause so that the column gets populated automatically with the timestamp when you insert a new row:

date_time datetime NOT NULL DEFAULT SYSDATE()

If you want the current date in epoch format, then you can use UNIX_TIMESTAMP(). For example:

select now(3), sysdate(3), unix_timestamp();

would yield

+-------------------------+-------------------------+------------------+
| now(3)                  | sysdate(3)              | unix_timestamp() |
+-------------------------+-------------------------+------------------+
| 2018-11-27 01:40:08.160 | 2018-11-27 01:40:08.160 |       1543282808 |
+-------------------------+-------------------------+------------------+

Related:

What exactly is the meaning of an API?

In layman's terms, I've always said an API is like a translator between two people who speak different languages. In software, data can be consumed or distributed using an API (or translator) so that two different kinds of software can communicate. Good software has a strong translator (API) that follows rules and protocols for security and data cleanliness.

I"m a Marketer, not a coder. This all might not be quite right, but it's what I"ve tried to express for about 10 years now...

How do I encode a JavaScript object as JSON?

I think you can use JSON.stringify:

// after your each loop
JSON.stringify(values);

How to call a function from another controller in angularjs?

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:

$scope.$parent.parentmethod();

You can try it over here

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

What does upstream mean in nginx?

It's used for proxying requests to other servers.

An example from http://wiki.nginx.org/LoadBalanceExample is:

http {
  upstream myproject {
    server 127.0.0.1:8000 weight=3;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;    
    server 127.0.0.1:8003;
  }

  server {
    listen 80;
    server_name www.domain.com;
    location / {
      proxy_pass http://myproject;
    }
  }
}

This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.

How to disable "prevent this page from creating additional dialogs"?

I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.

So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:

var countdown = 99;
function annoy(){
    if(countdown>0){
        alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
        countdown--;

        // Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
        setTimeout(function(){
            annoy();
        }, 1000);
    }
}

// Don't alert right away or Chrome will catch you
setTimeout(function(){
    annoy();
}, 1000);

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

Hex to ascii string conversion

If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.

Have not run any benchmarks but I assume it is not the peak of efficiency.

static char ByteToAscii(const char *input) {
  char singleChar, out;
  memcpy(&singleChar, input, 2);
  sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
  return out;
}

int HexStringToAscii(const char *input, unsigned int length,
                            char **output) {
  int mIndex, sIndex = 0;
  char buffer[length];
  for (mIndex = 0; mIndex < length; mIndex++) {
    sIndex = mIndex * 2;
    char b = ByteToAscii(&input[sIndex]);
    memcpy(&buffer[mIndex], &b, 1);
  }
  *output = strdup(buffer);
  return 0;
}

ld cannot find an existing library

In Ubuntu, you can install libtool which resolves the libraries automatically.

$ sudo apt-get install libtool

This resolved a problem with ltdl for me, which had been installed as libltdl.so.7 and wasn't found as simply -lltdl in the make.

How do you add PostgreSQL Driver as a dependency in Maven?

PostgreSQL drivers jars are included in Central Repository of Maven:

For PostgreSQL up to 9.1, use:

<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>VERSION</version>
</dependency>

or for 9.2+

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>VERSION</version>
</dependency>

(Thanks to @Caspar for the correction)

Keep overflow div scrolled to bottom unless user scrolls up

I was able to get this working with CSS only.

The trick is to use display: flex; and flex-direction: column-reverse;

The browser treats the bottom like its the top. Assuming the browsers you're targeting support flex-box, the only caveat is that the markup has to be in reverse order.

Here is a working example. https://codepen.io/jimbol/pen/YVJzBg

How can I tell if a Java integer is null?

There is no exists for a SCALAR in Perl, anyway. The Perl way is

defined( $x ) 

and the equivalent Java is

anInteger != null

Those are the equivalents.

exists $hash{key}

Is like the Java

map.containsKey( "key" )

From your example, I think you're looking for

if ( startIn != null ) { ...

Lodash - difference between .extend() / .assign() and .merge()

It might be also helpful to consider what they do from a semantic point of view:

_.assign

   will assign the values of the properties of its second parameter and so on,
   as properties with the same name of the first parameter. (shallow copy & override)

_.merge

   merge is like assign but does not assign objects but replicates them instead.
  (deep copy)

_.defaults

   provides default values for missing values.
   so will assign only values for keys that do not exist yet in the source.

_.defaultsDeep

   works like _defaults but like merge will not simply copy objects
   and will use recursion instead.

I believe that learning to think of those methods from the semantic point of view would let you better "guess" what would be the behavior for all the different scenarios of existing and non existing values.

Test if a vector contains a given element

I will group the options based on output. Assume the following vector for all the examples.

v <- c('z', 'a','b','a','e')

For checking presence:

%in%

> 'a' %in% v
[1] TRUE

any()

> any('a'==v)
[1] TRUE

is.element()

> is.element('a', v)
[1] TRUE

For finding first occurance:

match()

> match('a', v)
[1] 2

For finding all occurances as vector of indices:

which()

> which('a' == v)
[1] 2 4

For finding all occurances as logical vector:

==

> 'a' == v
[1] FALSE  TRUE FALSE  TRUE FALSE

Edit: Removing grep() and grepl() from the list for reason mentioned in comments

Oracle PL/SQL : remove "space characters" from a string

Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class

REGEXP_REPLACE( my_value, '[[:space:]]', '' )


SQL> ed
Wrote file afiedt.buf

  1  select '|' ||
  2         regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
  3         '|'
  4*   from dual
SQL> /

'|'||
-----
|foo|

If you want to leave one space in place for every set of continuous space characters, just add the + to the regular expression and use a space as the replacement character.

with x as (
  select 'abc 123  234     5' str
    from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
  from x

How do I record audio on iPhone with AVAudioRecorder?

Great Thanks to @Massimo Cafaro and Shaybc I was able achieve below tasks

in iOS 8 :

Record audio & Save

Play Saved Recording

1.Add "AVFoundation.framework" to your project

in .h file

2.Add below import statement 'AVFoundation/AVFoundation.h'.

3.Define "AVAudioRecorderDelegate"

4.Create a layout with Record, Play buttons and their action methids

5.Define Recorder and Player etc.

Here is the complete example code which may help you.

ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioRecorderDelegate>

@property(nonatomic,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong) NSMutableDictionary *recorderSettings;
@property(nonatomic,strong) NSString *recorderFilePath;
@property(nonatomic,strong) AVAudioPlayer *audioPlayer;
@property(nonatomic,strong) NSString *audioFileName;

- (IBAction)startRecording:(id)sender;
- (IBAction)stopRecording:(id)sender;

- (IBAction)startPlaying:(id)sender;
- (IBAction)stopPlaying:(id)sender;

@end

Then do the job in

ViewController.m

#import "ViewController.h"

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

@interface ViewController ()
@end

@implementation ViewController

@synthesize recorder,recorderSettings,recorderFilePath;
@synthesize audioPlayer,audioFileName;


#pragma mark - View Controller Life cycle methods
- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


#pragma mark - Audio Recording
- (IBAction)startRecording:(id)sender
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    if(err)
    {
        NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
    if(err)
    {
        NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        return;
    }
    
    recorderSettings = [[NSMutableDictionary alloc] init];
    [recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    [recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    
    // Create a new audio file
    audioFileName = @"recordingTestFile";
    recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName] ;
    
    NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
    err = nil;
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&err];
    if(!recorder){
        NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil
                         cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    
    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"message: @"Audio input hardware not available"
                                  delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [cantRecordAlert show];
        return;
    }
    
    // start recording
    [recorder recordForDuration:(NSTimeInterval) 60];//Maximum recording time : 60 seconds default
    NSLog(@"Recroding Started");
}

- (IBAction)stopRecording:(id)sender
{
    [recorder stop];
    NSLog(@"Recording Stopped");
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
}


#pragma mark - Audio Playing
- (IBAction)startPlaying:(id)sender
{
    NSLog(@"playRecording");
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
     NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName]];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;
    [audioPlayer play];
    NSLog(@"playing");
}
- (IBAction)stopPlaying:(id)sender
{
    [audioPlayer stop];
    NSLog(@"stopped");
}

@end

enter image description here

How to ping ubuntu guest on VirtualBox

Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.

For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:

For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.

In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

How to write multiple conditions of if-statement in Robot Framework

You should use small caps "or" and "and" instead of OR and AND.

And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).

Here is a code sample with your three keywords working fine:

Here is the file ts.txt:

  *** test cases ***
  mytest
    ${color} =  set variable  Red
    Run Keyword If  '${color}' == 'Red'  log to console  \nexecuted with single condition
    Run Keyword If  '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'  log to console  \nexecuted with multiple or

    ${color} =  set variable  Blue
    ${Size} =  set variable  Small
    ${Simple} =  set variable  Simple
    ${Design} =  set variable  Simple
    Run Keyword If  '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}'  log to console  \nexecuted with multiple and

    ${Size} =  set variable  XL
    ${Design} =  set variable  Complicated
    Run Keyword Unless  '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple'  log to console  \nexecuted with unless and multiple or

and here is what I get when I execute it:

$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest                                                                .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest                                                                | PASS |
------------------------------------------------------------------------------

How to get index using LINQ?

myCars.TakeWhile(car => !myCondition(car)).Count();

It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.

Story time

I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:

public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
    int index = 0;
    foreach (var item in items) {
        if (predicate(item)) break;
        index++;
    }
    return index;
}

Note that it will return the number of items instead of -1 when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.

What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.

Analysis

Pros

  • Concise
  • Combinable with other LINQ
  • Avoids newing anonymous objects
  • Only evaluates the enumerable until the predicate matches for the first time

Therefore I consider it optimal in time and space while remaining readable.

Cons

  • Not quite obvious at first
  • Does not return -1 when there is no match

Of course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.

Global variables in header file

Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf

This type of code create problem while porting.

SQL Server Operating system error 5: "5(Access is denied.)"

For some reason, setting all the correct permissions did not help in my case. I had a file db.bak that I was not able to restore due to the 5(Access is denied.) error. The file was placed in the same folder as several other backup files and all the permissions were identical to other files. I was able to restore all the other files except this db.bak file. I even tried to change the SQL Server service log on user — still the same result. I've tried copying the file with no effect.

Then I attempted to just create an identical file by executing

type db.bak > db2.bak

instead of copying the file. And voila it worked! db2.bak restored successfully.

I suspect that some other problems with reading the backup file may be erroniously reported as 5(Access is denied.) by MS SQL.

Sending files using POST with HttpURLConnection

based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :

ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
        byte[] pixels = bos.toByteArray();

How to filter (key, value) with ng-repeat in AngularJs?

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Try this:

To accept theirs changes: git merge --strategy-option theirs

To accept yours: git merge --strategy-option ours

Listing available com ports with Python

Please, try this code:

import serial
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
    print(port.device)

first of all, you need to import package for serial port communication, so:

import serial

then you create the list of all the serial ports currently available:

ports = serial.tools.list_ports.comports(include_links=False)

and then, walking along whole list, you can for example print port names:

for port in ports :
    print(port.device)

This is just an example how to get the list of ports and print their names, but there some other options you can do with this data. Just try print different variants after

port.

Chosen Jquery Plugin - getting selected values

I believe the problem occurs when targeting by ID, because Chosen will copy the ID from the original select onto it's newly created div, leaving you with 2 elements of the same (now not-unique) ID on the current page.

When targeting Chosen by ID, use a selector specific to the select:

$( 'select#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

...instead of...

$( '#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

This works because Chosen mirrors its selected items back to the original (now hidden) select element, even in multi-mode.

(It also continues to work with or without Chosen, say... if you decide to go a different direction in your application.)

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

Getting list of files in documents folder

Swift 2.0 Compability

func listWithFilter () {

    let fileManager = NSFileManager.defaultManager()
           // We need just to get the documents folder url
    let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

    do {
    // if you want to filter the directory contents you can do like this:
    if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {
        print(directoryUrls)
       ........
        }

    }

}

OR

 func listFiles() -> [String] {

    var theError = NSErrorPointer()
    let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if dirs != nil {
        let dir = dirs![0]
        do {
        let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
        return fileList as [String]
        }catch {

        }

    }else{
        let fileList = [""]
        return fileList
    }
    let fileList = [""]
    return fileList

}

Align Bootstrap Navigation to Center

Try this css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;
}

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;
}

How to open a specific port such as 9090 in Google Compute Engine

I had the same problem as you do and I could solve it by following @CarlosRojas instructions with a little difference. Instead of create a new firewall rule I edited the default-allow-internal one to accept traffic from anywhere since creating new rules didn't make any difference.

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

Removing black dots from li and ul

CSS :

ul{
list-style-type:none;
}

You can take a look at W3School

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

jQuery form input select by id

You can do that using the descendant selectors:

 $("#a #b")

However, id values are supposed to be unique on a page.

Get specific line from text file using just shell script

You could use sed -n 5p file.

You can also get a range, e.g., sed -n 5,10p file.

How do I get a HttpServletRequest in my spring beans?

The @Context annotation (see answers in this question :What does context annotation do in Spring?) will cause it to be injected for you.

I had to use

@Context
private HttpServletRequest request;

How to know function return type and argument types?

I attended a coursera course, there was lesson in which, we were taught about design recipe.

Below docstring format I found preety useful.

def area(base, height):
    '''(number, number ) -> number    #**TypeContract**
    Return the area of a tring with dimensions base   #**Description**
    and height

    >>>area(10,5)          #**Example **
    25.0
    >>area(2.5,3)
    3.75
    '''
    return (base * height) /2 

I think if docstrings are written in this way, it might help a lot to developers.

Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI

Combine two data frames by rows (rbind) when they have different sets of columns

rbind.fill from the package plyr might be what you are looking for.

JUnit Testing Exceptions

An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.

And using Matchers, you can test the part of message you are interested:

exception.expectMessage(containsString("income: -1000.0"));

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:

$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...

As an alias:

$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...

Please note that I control my Python version via conda environments, because of that I can use python instead of python3 for using Python 3.

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Chrome not rendering SVG referenced via <img> tag

I was having the same issue with an SVG image included via the IMG tag. It turned out for me that Chrome didn't like there being a blank line directly at the top of the file.

I removed the blank line and my SVG immediately started rendering.

How to print a certain line of a file with PowerShell?

To reduce memory consumption and to speed up the search you may use -ReadCount option of Get-Content cmdlet (https://technet.microsoft.com/ru-ru/library/hh849787.aspx).

This may save hours when you working with large files.

Here is an example:

$n = 60699010
$src = 'hugefile.csv'
$batch = 100
$timer = [Diagnostics.Stopwatch]::StartNew()

$count = 0
Get-Content $src -ReadCount $batch -TotalCount $n | %  { 
    $count += $_.Length
    if ($count -ge $n ) {
        $_[($n - $count + $_.Length - 1)]
    }
}

$timer.Stop()
$timer.Elapsed

This prints $n'th line and elapsed time.

Update Git branches from master

git rebase master is the proper way to do this. Merging would mean a commit would be created for the merge, while rebasing would not.

pass array to method Java

There is an important point of arrays that is often not taught or missed in java classes. When arrays are passed to a function, then another pointer is created to the same array ( the same pointer is never passed ). You can manipulate the array using both the pointers, but once you assign the second pointer to a new array in the called method and return back by void to calling function, then the original pointer still remains unchanged.

You can directly run the code here : https://www.compilejava.net/

import java.util.Arrays;

public class HelloWorld
{
    public static void main(String[] args)
    {
        int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
        Demo1.Demo1(Main_Array);
        // THE POINTER Main_Array IS NOT PASSED TO Demo1
        // A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1

        System.out.println("Main_Array = "+Arrays.toString(Main_Array));
        // outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
        // Since Main_Array points to the original location,
        // I cannot access the results of Demo1 , Demo2 when they are void.
        // I can use array clone method in Demo1 to get the required result,
        // but it would be faster if Demo1 returned the result to main
    }
}

public class Demo1
{
    public static void Demo1(int A[])
    {
        int B[] = new int[A.length];
        System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        Demo2.Demo2(A,B);
        System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]

        A = B;
        // A was pointing to location of Main_Array, now it points to location of B
        // Main_Array pointer still keeps pointing to the original location in void main

        System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // Hence to access this result from main, I have to return it to main
    }
}
public class Demo2
{
    public static void Demo2(int AAA[],int BBB[])
    {
        BBB[0] = 9999;
        // BBB points to the same location as B in Demo1, so whatever I do
        // with BBB, I am manipulating the location. Since B points to the
        // same location, I can access the results from B
    }
}

how to change color of TextinputLayout's label and edittext underline android

Based on Fedor Kazakov and others answers, I created a default config.

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Widget.Design.TextInputLayout" parent="AppTheme">
        <item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
        <item name="errorTextAppearance">@style/AppTheme.TextErrorAppearance</item>
        <item name="counterTextAppearance">@style/TextAppearance.Design.Counter</item>
        <item name="counterOverflowTextAppearance">@style/TextAppearance.Design.Counter.Overflow</item>
    </style>

    <style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
        <!-- Floating label appearance here -->
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:textSize">20sp</item>
    </style>

    <style name="AppTheme.TextErrorAppearance" parent="TextAppearance.Design.Error">
        <!-- Error message appearance here -->
        <item name="android:textColor">#ff0000</item>
        <item name="android:textSize">20sp</item>
    </style>

</resources>

activity_layout.xml

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text hint here"
        android:text="5,2" />

</android.support.design.widget.TextInputLayout>

Focused:

Focused

Without focus:

Without focus

Error message:

enter image description here

Change bootstrap navbar background color and font color

I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #000; /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
        a:hover, .navbar-default .navbar-nav > .active > a:focus {
    color: white; /*BACKGROUND color for active*/
    background-color: #030033;
}

.navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
    color: #262626;
    text-decoration: none;
    background-color: #66CCFF; /*change color of links in drop down here*/
}

.nav > li > a:hover,
.nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
}

.navbar-default .navbar-nav > li > a {
    color: white; /*Change active text color here*/
}

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

No library, one line, properly padded

const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

Local time instead of UTC

const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

pip install failing with: OSError: [Errno 13] Permission denied on directory

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.

Disable resizing of a Windows Forms form

Another way is to change properties "AutoSize" (set to True) and "AutosizeMode" (set to GrowAndShrink).

This has the effect of the form autosizing to the elements on it and never allowing the user to change its size.

Why should C++ programmers minimize use of 'new'?

  • C++ doesn't employ any memory manager by its own. Other languages like C#, Java has garbage collector to handle the memory
  • C++ implementations typically use operating system routines to allocate the memory and too much new/delete could fragment the available memory
  • With any application, if the memory is frequently being used it's advisable to pre-allocate it and release when not required.
  • Improper memory management could lead memory leaks and it's really hard to track. So using stack objects within the scope of function is a proven technique
  • The downside of using stack objects are, it creates multiple copies of objects on returning, passing to functions etc. However smart compilers are well aware of these situations and they've been optimized well for performance
  • It's really tedious in C++ if the memory being allocated and released in two different places. The responsibility for release is always a question and mostly we rely on some commonly accessible pointers, stack objects (maximum possible) and techniques like auto_ptr (RAII objects)
  • The best thing is that, you've control over the memory and the worst thing is that you will not have any control over the memory if we employ an improper memory management for the application. The crashes caused due to memory corruptions are the nastiest and hard to trace.

Detect application heap size in Android

Do you mean programatically, or just while you're developing and debugging? If the latter, you can see that info from the DDMS perspective in Eclipse. When your emulator (possibly even physical phone that is plugged in) is running, it will list the active processes in a window on the left. You can select it and there's an option to track the heap allocations.

How to delete multiple files at once in Bash on Linux?

Just use multiline selection in sublime to combine all of the files into a single line and add a space between each file name and then add rm at the beginning of the list. This is mostly useful when there isn't a pattern in the filenames you want to delete.

[$]> rm abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28 abc.log.2012-03-29 abc.log.2012-03-30 abc.log.2012-04-02 abc.log.2012-04-04 abc.log.2012-04-05 abc.log.2012-04-09 abc.log.2012-04-10

How to change the Push and Pop animations in a navigation based app

I am not aware of any way you can change the transition animation publicly.

If the "back" button is not necessary you should use modal view controllers to have the "push from bottom" / "flip" / "fade" / (=3.2)"page curl" transitions.


On the private side, the method -pushViewController:animated: calls the undocumented method -pushViewController:transition:forceImmediate:, so e.g. if you want a flip-from-left-to-right transition, you can use

[navCtrler pushViewController:ctrler transition:10 forceImmediate:NO];

You can't change the "pop" transition this way, however.

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

How does the JPA @SequenceGenerator annotation work

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

Usage:

@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO)

Imitating a blink tag with CSS3 animations

Let me show you a little trick.

As Arkanciscan said, you can use CSS3 transitions. But his solution looks different from the original tag.

What you really need to do is this:

_x000D_
_x000D_
@keyframes blink {_x000D_
  50% {_x000D_
    opacity: 0.0;_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes blink {_x000D_
  50% {_x000D_
    opacity: 0.0;_x000D_
  }_x000D_
}_x000D_
.blink {_x000D_
  animation: blink 1s step-start 0s infinite;_x000D_
  -webkit-animation: blink 1s step-start 0s infinite;_x000D_
}
_x000D_
<span class="blink">Blink</span>
_x000D_
_x000D_
_x000D_

JSfiddle Demo

UITableViewCell Selected Background Color on Multiple Selection

All the above answers are fine but a bit to complex to my liking. The simplest way to do it is to put some code in the cellForRowAtIndexPath. That way you never have to worry about changing the color when the cell is deselected.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    /* this is where the magic happens, create a UIView and set its
       backgroundColor to what ever color you like then set the cell's
       selectedBackgroundView to your created View */

    let backgroundView = UIView()
    backgroundView.backgroundColor = YOUR_COLOR_HERE
    cell.selectedBackgroundView = backgroundView
    return cell
}

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

For a correct implementation, you need to change a series of things.

Database (immediately after the connection):

mysql_query("SET NAMES utf8");

// Meta tag HTML (probably it's already set): 
meta charset="utf-8"
header php (before any output of the HTML):
header('Content-Type: text/html; charset=utf-8')
table-rows-charset (for each row):
utf8_unicode_ci

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

My issue was Mysql connector net 6.4.4, Nuget, xamarin, VSPackage, EditorPackage and etc.. package did not load correctly.

My solution is below for vs2015

  1. Open AppData location // all the configurations are updating on it.
  2. Backup and Remove the folder in which configuration error is thrown in the visual studio.

forex. If you have Nuget package did not load correctly error - Remove Nuget folder in Local and Roaming directories.

  1. And also clear the data on AppData/Microsoft/visual Studio/14.0 for vs2015

that's it and it worked for me!...

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

window.open with target "_blank" in Chrome

window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);

Java substring: 'string index out of range'

if (itemdescription != null && itemdescription.length() > 0) {
    pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38))); 
} else { 
    pstmt2.setString(3, "_"); 
}

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

This occurred when trying to connect to the WCF Service using only host name e.g. https://host/MyService.svc while using a certificate tied to a name e.g. host.mysite.com.

Switching to the https://host.mysite.com/MyService.svc and this resolved it.

Laravel check if collection is empty

To determine if there are any results you can do any of the following:

if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }

Notes / References

->first()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty() https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors) works because the Collection implements Countable and an internal count() method:

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

isNotEmpty()

https://laravel.com/docs/5.7/collections#method-isnotempty

So what you can do is :

if (!$mentors->intern->employee->isEmpty()) { }

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

How to highlight cell if value duplicate in same column for google spreadsheet?

Highlight duplicates (in column C):

=COUNTIF(C:C, C1) > 1

Explanation: The C1 here doesn't refer to the first row in C. Because this formula is evaluated by a conditional format rule, instead, when the formula is checked to see if it applies, the C1 effectively refers to whichever row is currently being evaluated to see if the highlight should be applied. (So it's more like INDIRECT(C &ROW()), if that means anything to you!). Essentially, when evaluating a conditional format formula, anything which refers to row 1 is evaluated against the row that the formula is being run against. (And yes, if you use C2 then you asking the rule to check the status of the row immediately below the one currently being evaluated.)

So this says, count up occurences of whatever is in C1 (the current cell being evaluated) that are in the whole of column C and if there is more than 1 of them (i.e. the value has duplicates) then: apply the highlight (because the formula, overall, evaluates to TRUE).

Highlight the first duplicate only:

=AND(COUNTIF(C:C, C1) > 1, COUNTIF(C$1:C1, C1) = 1)

Explanation: This only highlights if both of the COUNTIFs are TRUE (they appear inside an AND()).

The first term to be evaluated (the COUNTIF(C:C, C1) > 1) is the exact same as in the first example; it's TRUE only if whatever is in C1 has a duplicate. (Remember that C1 effectively refers to the current row being checked to see if it should be highlighted).

The second term (COUNTIF(C$1:C1, C1) = 1) looks similar but it has three crucial differences:

It doesn't search the whole of column C (like the first one does: C:C) but instead it starts the search from the first row: C$1 (the $ forces it to look literally at row 1, not at whichever row is being evaluated).

And then it stops the search at the current row being evaluated C1.

Finally it says = 1.

So, it will only be TRUE if there are no duplicates above the row currently being evaluated (meaning it must be the first of the duplicates).

Combined with that first term (which will only be TRUE if this row has duplicates) this means only the first occurrence will be highlighted.

Highlight the second and onwards duplicates:

=AND(COUNTIF(C:C, C1) > 1, NOT(COUNTIF(C$1:C1, C1) = 1), COUNTIF(C1:C, C1) >= 1)

Explanation: The first expression is the same as always (TRUE if the currently evaluated row is a duplicate at all).

The second term is exactly the same as the last one except it's negated: It has a NOT() around it. So it ignores the first occurence.

Finally the third term picks up duplicates 2, 3 etc. COUNTIF(C1:C, C1) >= 1 starts the search range at the currently evaluated row (the C1 in the C1:C). Then it only evaluates to TRUE (apply highlight) if there is one or more duplicates below this one (and including this one): >= 1 (it must be >= not just > otherwise the last duplicate is ignored).

Disable same origin policy in Chrome

For OSX, run the following command from the terminal:

open -na Google\ Chrome --args --disable-web-security --user-data-dir=$HOME/profile-folder-name

This will start a new instance of Google Chrome with a warning on top.

jQuery remove all list items from an unordered list

this worked for me with minimal code

$(my_list).remove('li');

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

Resize svg when window is resized in d3.js

If you want to bind custom logic to resize event, nowadays you may start using ResizeObserver browser API for the bounding box of an SVGElement.
This will also handle the case when container is resized because of the nearby elements size change.
There is a polyfill for broader browser support.

This is how it may work in UI component:

_x000D_
_x000D_
function redrawGraph(container, { width, height }) {_x000D_
  d3_x000D_
    .select(container)_x000D_
    .select('svg')_x000D_
    .attr('height', height)_x000D_
    .attr('width', width)_x000D_
    .select('rect')_x000D_
    .attr('height', height)_x000D_
    .attr('width', width);_x000D_
}_x000D_
_x000D_
// Setup observer in constructor_x000D_
const resizeObserver = new ResizeObserver((entries, observer) => {_x000D_
  for (const entry of entries) {_x000D_
    // on resize logic specific to this component_x000D_
    redrawGraph(entry.target, entry.contentRect);_x000D_
  }_x000D_
})_x000D_
_x000D_
// Observe the container_x000D_
const container = document.querySelector('.graph-container');_x000D_
resizeObserver.observe(container)
_x000D_
.graph-container {_x000D_
  height: 75vh;_x000D_
  width: 75vw;_x000D_
}_x000D_
_x000D_
.graph-container svg rect {_x000D_
  fill: gold;_x000D_
  stroke: steelblue;_x000D_
  stroke-width: 3px;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/ResizeObserver.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<figure class="graph-container">_x000D_
  <svg width="100" height="100">_x000D_
    <rect x="0" y="0" width="100" height="100" />_x000D_
  </svg>_x000D_
</figure>
_x000D_
_x000D_
_x000D_

// unobserve in component destroy method
this.resizeObserver.disconnect()

Jenkins / Hudson environment variables

Couldn't you just add it as an environment variable in Jenkins settings:

Manage Jenkins -> Global properties > Environment variables: And then click "Add" to add a property PATH and its value to what you need.

How can I reset eclipse to default settings?

You can reset settings for eclipse by deleting .metadata folder from your current workspace.

This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.

You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".

import Have a look here : import project in eclipse

What is event bubbling and capturing?

There's also the Event.eventPhase property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.

Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase property

_x000D_
_x000D_
var logElement = document.getElementById('log');

function log(msg) {
  if (logElement.innerHTML == "<p>No logs</p>")
    logElement.innerHTML = "";
  logElement.innerHTML += ('<p>' + msg + '</p>');
}

function humanizeEvent(eventPhase){
  switch(eventPhase){
    case 1: //Event.CAPTURING_PHASE
      return "Event is being propagated through the target's ancestor objects";
    case 2: //Event.AT_TARGET
      return "The event has arrived at the event's target";
    case 3: //Event.BUBBLING_PHASE
      return "The event is propagating back up through the target's ancestors in reverse order";
  }
}
function capture(e) {
  log('capture: ' + this.firstChild.nodeValue.trim() + "; " + 
  humanizeEvent(e.eventPhase));
}

function bubble(e) {
  log('bubble: ' + this.firstChild.nodeValue.trim() + "; " + 
  humanizeEvent(e.eventPhase));
}

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', capture, true);
  divs[i].addEventListener('click', bubble, false);
}
_x000D_
p {
  line-height: 0;
}

div {
  display:inline-block;
  padding: 5px;

  background: #fff;
  border: 1px solid #aaa;
  cursor: pointer;
}

div:hover {
  border: 1px solid #faa;
  background: #fdd;
}
_x000D_
<div>1
  <div>2
    <div>3
      <div>4
        <div>5</div>
      </div>
    </div>
  </div>
</div>
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>
_x000D_
_x000D_
_x000D_

Reverting to a previous revision using TortoiseSVN

There are several ways to do that. But do not just update to the earlier revision as suggested here.

The easiest way to revert the changes from a single revision, or from a range of revisions, is to use the revision log dialog. This is also the method to use of you want to discard recent changes and make an earlier revision the new HEAD.

  1. Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.
  2. Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.
  3. Select the revision you wish to revert. If you want to undo a range of revisions, select the first one and hold Shift while selecting the last one. Note that for multiple revisions, the range must be unbroken with no gaps. Right click on the selected revision(s), then select Context Menu ? Revert changes from this revision.
  4. Or if you want to make an earlier revision the new HEAD revision, right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.

You have reverted the changes within your working copy. Check the results, then commit the changes.

All solutions are explained in the "How Do I..." part of the TortoiseSVN docs.

Appending pandas dataframes generated in a for loop

Use pd.concat to merge a list of DataFrame into a single big DataFrame.

appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    # store DataFrame in list
    appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet 
appended_data.to_excel('appended.xlsx')

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

Works fine for me in 5.0.27

I just get a warning (not an error) that the table exists;

Proper MIME type for OTF fonts

The following can be used in the eBook space:

application/vnd.ms-opentype

I would imagine that it is the same for the web.

Difference between window.location.href and top.location.href

window.location.href returns the location of the current page.

top.location.href (which is an alias of window.top.location.href) returns the location of the topmost window in the window hierarchy. If a window has no parent, top is a reference to itself (in other words, window === window.top).

top is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html with the following script:

var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');

The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href would return.

To answer your question about redirecting, go with window.location.assign(url);

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

How to get my activity context?

You can create a constructor using parameter Context of class A then you can use this context.

Context c;

A(Context context){ this.c=context }

From B activity you create a object of class A using this constructor and passing getApplicationContext().

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Well, there are many solutions already given above. If there are none of them works, maybe you should just try to reset your password again to 'root' as described here, and then reopen http://localhost/phpMyAdmin/ in other browser. At least this solution works for me.

Find element's index in pandas Series

Another way to do it that hasn't been mentioned yet is the tolist method:

myseries.tolist().index(7)

should return the correct index, assuming the value exists in the Series.

Are arrays passed by value or passed by reference in Java?

No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.

Getting the ID of the element that fired an event

You can try to use:

$('*').live('click', function() {
 console.log(this.id);
 return false;
});

How to redirect back to form with input - Laravel 5

this will work definately !!!

  $v = Validator::make($request->all(),[
  'name' => ['Required','alpha']
  ]);

   if($v->passes()){
     print_r($request->name);
   }
   else{
     //this will return the errors & to check put "dd($errors);" in your blade(view)
     return back()->withErrors($v)->withInput();
   }

make an ID in a mysql table auto_increment (after the fact)

ALTER TABLE `foo` MODIFY COLUMN `bar_id` INT NOT NULL AUTO_INCREMENT;

or

ALTER TABLE `foo` CHANGE `bar_id` `bar_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;

But none of these will work if your bar_id is a foreign key in another table: you'll be getting

an error 1068: Multiple primary key defined

To solve this, temporary disable foreign key constraint checks by

set foreign_key_checks = 0;

and after running the statements above, enable them back again.

set foreign_key_checks = 1;

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

Dealing with commas in a CSV file

I usually do this in my CSV files parsing routines. Assume that 'line' variable is one line within a CSV file and all of the columns' values are enclosed in double quotes. After the below two lines execute, you will get CSV columns in the 'values' collection.

// The below two lines will split the columns as well as trim the DBOULE QUOTES around values but NOT within them
    string trimmedLine = line.Trim(new char[] { '\"' });
    List<string> values = trimmedLine.Split(new string[] { "\",\"" }, StringSplitOptions.None).ToList();

python save image from url

Python code snippet to download a file from an url and save with its name

import requests

url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)

How can I create a self-signed cert for localhost?

In a LAN (Local Area Network) we have a server computer, here named xhost running Windows 10, IIS is activated as WebServer. We must access this computer via Browser like Google Chrome not only from localhost through https://localhost/ from server itsself, but also from other hosts in the LAN with URL https://xhost/ :


https://localhost/
https://xhost/
https://xhost.local/
...

With this manner of accessing, we have not a fully-qualified domain name, but only local computer name xhost here.

Or from WAN:


https://dev.example.org/
...

You shall replace xhost by your real local computer name.

None of above solutions may satisfy us. After days of try, we have adopted the solution openssl.exe. We use 2 certificates - a CA (self certified Authority certificate) RootCA.crt and xhost.crt certified by the former. We use PowerShell.

1. Create and change to a safe directory:

cd C:\users\so\crt

2. Generate RootCA.pem, RootCA.key & RootCA.crt as self-certified Certification Authority:


openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt

3. make request for certification: xhost.key, xhost.csr:

C: Country
ST: State
L: locality (city)
O: Organization Name
Organization Unit
CN: Common Name

    

openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"

4. get xhost.crt certified by RootCA.pem:


openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt

with extfile domains.ext file defining many secured ways of accessing the server website:

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = xhost
DNS.3 = xhost.local
DNS.4 = dev.example.org
DNS.5 = 192.168.1.2

5. Make xhost.pfx PKCS #12,

combinig both private xhost.key and certificate xhost.crt, permitting to import into iis. This step asks for password, please let it empty by pressing [RETURN] key (without password):


openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt

6. import xhost.pfx in iis10

installed in xhost computer (here localhost). and Restart IIS service.

IIS10 Gestionnaire des services Internet (IIS) (%windir%\system32\inetsrv\InetMgr.exe)

enter image description here

enter image description here

7. Bind ssl with xhost.local certificate on port 443.

enter image description here

Restart IIS Service.

8. Import RootCA.crt into Trusted Root Certification Authorities

via Google Chrome in any computer that will access the website https://xhost/.

\Google Chrome/…/Settings /[Advanced]/Privacy and Security/Security/Manage certificates

Import RootCA.crt

enter image description here

The browser will show this valid certificate tree:


RootCA-CA
  |_____ xhost.local

enter image description here

No Certificate Error will appear through LAN, even through WAN by https://dev.example.org.

enter image description here

Here is the whole Powershell Script socrt.ps1 file to generate all required certificate files from the naught:


#
# Generate:
#   RootCA.pem, RootCA.key RootCA.crt
#
#   xhost.key xhost.csr xhost.crt
#   xhost.pfx
#
# created  15-EEC-2020
# modified 15-DEC-2020
#
#
# change to a safe directory:
#

cd C:\users\so\crt

#
# Generate RootCA.pem, RootCA.key & RootCA.crt as Certification Authority:
#
openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt

#
# get RootCA.pfx: permitting to import into iis10: not required.
#
#openssl pkcs12 -export -out RootCA.pfx -inkey RootCA.key -in RootCA.crt

#
# get xhost.key xhost.csr:
#   C: Country
#   ST: State
#   L: locality (city)
#   O: Organization Name
#   OU: Organization Unit
#   CN: Common Name
#
openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"

#
# get xhost.crt certified by RootCA.pem:
# to show content:
#   openssl x509 -in xhost.crt -noout -text
#
openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt

#
# get xhost.pfx, permitting to import into iis:
#
openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt

#
# import xhost.pfx in iis10 installed in xhost computer (here localhost).
#

To install openSSL for Windows, please visit https://slproweb.com/products/Win32OpenSSL.html

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

Fastest way to check if string contains only digits

Probably the fastest way is:

myString.All(c => char.IsDigit(c))

Note: it will return True in case your string is empty which is incorrect (if you not considering empty as valid number/digit )

How to mount a host directory in a Docker container

Jul 2015 update - boot2docker now supports direct mounting. You can use -v /var/logs/on/host:/var/logs/in/container directly from your Mac prompt, without double mounting

npm check and update package if needed

To really update just one package install NCU and then run it just for that package. This will bump to the real latest.

npm install -g npm-check-updates

ncu -f your-intended-package-name -u

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,

ggplot(data_country)+
  geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")

Get hostname of current request in node.js Express

If you're talking about an HTTP request, you can find the request host in:

request.headers.host

But that relies on an incoming request.

More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest

If you're looking for machine/native information, try the process object.

How to convert java.lang.Object to ArrayList?

Rather Cast It to an Object Array.

Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;

CSS white space at bottom of page despite having both min-height and height tag

The problem is how 100% height is being calculated. Two ways to deal with this.

Add 20px to the body padding-bottom

body {
    padding-bottom: 20px;
}

or add a transparent border to body

body {
    border: 1px solid transparent;
}

Both worked for me in firebug

In defense of this answer

Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.

Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.

Thirtydot's answer is completely legit. The p around the script is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.

But why? Shouldn't the p tag's height, padding and margin be calculated into the height of the body?

And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.

The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.

In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.

Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.

My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.

How to move all files including hidden files into parent directory via *

Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.

$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. ..  .den  .hi .hidden a b c

$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c

$ shopt -s dotglob
$ ls *
.den  .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c

It defaults to "off".

$ shopt dotglob
dotglob         off

It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.

How to stick text to the bottom of the page?

An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:

<style>
   #container {
    position: relative;
    height: 100%;
 }
 #footer {
    position: absolute;
    bottom: 0;
 }
</style>

</HEAD>

<BODY>

 <div id="container">

    <h1>Some heading</h1>

<p>Some text you have</p> 

<br>
<br>

<div id="footer"><p>Rights reserved</p></div>

</div>

</BODY>
</HTML>

The trick is in <br> where you break new line. So, when page is small you'll see footer at bottom of page, as you want.

BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

Open the terminal in visual studio?

In Visual Studio 2019- Tools > Command Line > Developer Command Prompt.enter image description here

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

For me i wanted to implement a 2-way handshake, meaning:
- the parent window will load faster then the iframe
- the iframe should talk to the parent window as soon as its ready
- the parent is ready to receive the iframe message and replay

this code is used to set white label in the iframe using [CSS custom property]
code:
iframe

$(function() {
    window.onload = function() {
        // create listener
        function receiveMessage(e) {
            document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
            document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
            document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
            //alert(e.data.data.header_bg);
        }
        window.addEventListener('message', receiveMessage);
        // call parent
        parent.postMessage("GetWhiteLabel","*");
    }
});

parent

$(function() {
    // create listener
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(messageEvent, function (e) {
        // replay to child (iframe) 
        document.getElementById('wrapper-iframe').contentWindow.postMessage(
            {
                event_id: 'white_label_message',
                wl: {
                    header_bg: $('#Header').css('background-color'),
                    header_text: $('#Header .HoverMenu a').css('color'),
                    button_bg: $('#Header .HoverMenu a').css('background-color')
                }
            },
            '*'
        );
    }, false);
});

naturally you can limit the origins and the text, this is easy-to-work-with code
i found this examlpe to be helpful:
[Cross-Domain Messaging With postMessage]

Using Vim's tabs like buffers

I use buffers like tabs, using the BufExplorer plugin and a few macros:

" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>

" gz in command mode closes the current buffer
map gz :bdelete<cr>

" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>

With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...

CSS table layout: why does table-row not accept a margin?

The closest thing I've seen would be to set border-spacing: 0 30px; to the container div. However, this just leaves me with space on the upper edge of the table, which defeats the purpose, since you wanted margin-bottom.

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

Equivalent of Oracle's RowID in SQL Server

ROWID is a hidden column on Oracle tables, so, for SQL Server, build your own. Add a column called ROWID with a default value of NEWID().

How to do that: Add column, with default value, to existing table in SQL Server