Programs & Examples On #Contentpresenter

0

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

WPF TemplateBinding vs RelativeSource TemplatedParent

One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).

How to add Google Maps Autocomplete search box?

Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.

HTML

<input id="searchInput" class="controls" type="text" placeholder="Enter a location">

JavaScript

<script>
function initMap() {
    var input = document.getElementById('searchInput');
    var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>

Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window

Simulate a button click in Jest

Using Jest, you can do it like this:

test('it calls start logout on button click', () => {
    const mockLogout = jest.fn();
    const wrapper = shallow(<Component startLogout={mockLogout}/>);
    wrapper.find('button').at(0).simulate('click');
    expect(mockLogout).toHaveBeenCalled();
});

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Since you are using the lower version of PS:

What you can do in your case is you first download the module in your local folder.

Then, there will be a .psm1 file under that folder for this module.

You just

import-Module "Path of the file.psm1"

Here is the link to download the Azure Module: Azure Powershell

This will do your work.

Serving static web resources in Spring Boot & Spring Security application

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] resources = new String[]{
                "/", "/home","/pictureCheckCode","/include/**",
                "/css/**","/icons/**","/images/**","/js/**","/layer/**"
        };

        http.authorizeRequests()
                .antMatchers(resources).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout().logoutUrl("/404")
                .permitAll();
        super.configure(http);
    }
}

Read/Write 'Extended' file properties (C#)

For those of not crazy about VB, here it is in c#:

Note, you have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

How to run a program automatically as admin on Windows 7 at startup?

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

How can I get the height and width of an uiimage?

let heightInPoints = image.size.height
let heightInPixels = heightInPoints * image.scale

let widthInPoints = image.size.width
let widthInPixels = widthInPoints * image.scale

Getting Chrome to accept self-signed localhost certificate

For a test environment

You can use --ignore-certificate-errors as a command line parameter when launching chrome (Working on Version 28.0.1500.52 on Ubuntu).

This will cause it to ignore the errors and connect without warning. If you already have a version of chrome running, you will need to close this before relaunching from the command line or it will open a new window but ignore the parameters.

I configure Intellij to launch chrome this way when doing debugging, as the test servers never have valid certificates.

I wouldn't recommend normal browsing like this though, as certificate checks are an important security feature, but this may be helpful to some.

Android Studio: Gradle: error: cannot find symbol variable

make sure that the imported R is not from another module. I had moved a class from a module to the main project, and the R was the one from the module.

How can I set a css border on one side only?

You can specify border separately for all borders, for example:

#testdiv{
  border-left: 1px solid #000;
  border-right: 2px solid #FF0;
}

You can also specify the look of the border, and use separate style for the top, right, bottom and left borders. for example:

#testdiv{
  border: 1px #000;
  border-style: none solid none solid;
}

How do you handle multiple submit buttons in ASP.NET MVC Framework?

My Solution was to use 2 asp panels:

<asp:Panel ID=”..” DefaultButton=”ID_OF_SHIPPING_SUBMIT_BUTTON”….></asp:Panel>

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

For Java 7 you can simply omit the Class.forName() statement as it is not really required.

For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see

Manipulating an Access database from Java without ODBC

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

Why is my element value not getting changed? Am I using the wrong function?

It's document.getElementById, not document.getElementsByID

I'm assuming you have <input id="Tue" ...> somewhere in your markup.

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

How to use XMLReader in PHP?

The accepted answer gave me a good start, but brought in more classes and more processing than I would have liked; so this is my interpretation:

$xml_reader = new XMLReader;
$xml_reader->open($feed_url);

// move the pointer to the first product
while ($xml_reader->read() && $xml_reader->name != 'product');

// loop through the products
while ($xml_reader->name == 'product')
{
    // load the current xml element into simplexml and we’re off and running!
    $xml = simplexml_load_string($xml_reader->readOuterXML());

    // now you can use your simpleXML object ($xml).
    echo $xml->element_1;

    // move the pointer to the next product
    $xml_reader->next('product');
}

// don’t forget to close the file
$xml_reader->close();

How can I plot data with confidence intervals?

Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.

library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3) 
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')

drawing of the prediction interval in polynomial regression

Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.

Sql Query to list all views in an SQL Server 2005 database

To finish the set off (with what has already been suggested):

SELECT * FROM sys.views

This gives extra properties on each view, not available from sys.objects (which contains properties common to all types of object) or INFORMATION_SCHEMA.VIEWS. Though INFORMATION_SCHEMA approach does provide the view definition out-of-the-box.

Converting dictionary to JSON

json.dumps() returns the JSON string representation of the python dict. See the docs

You can't do r['rating'] because r is a string, not a dict anymore

Perhaps you meant something like

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))

How to know if docker is already logged in to a docker registry server

If you want a simple true/false value, you can pipe your docker.json to jq.

is_logged_in() {
  cat ~/.docker/config.json | jq -r --arg url "${REPOSITORY_URL}" '.auths | has($url)'
}

if [[ "$(is_logged_in)" == "false" ]]; then
  # do stuff, log in
fi

PHP, pass array through POST

There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).

XSS

XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:

" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="

This would be written into your form like so:

<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>

The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into &lt;. For example:

<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>

You can read more about XSS here: https://www.owasp.org/index.php/XSS

Form Modification

If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.

I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).

In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.

Angular2 disable button

 <button [disabled]="this.model.IsConnected() == false"
              [ngClass]="setStyles()"
              class="action-button action-button-selected button-send"
              (click)= "this.Send()">
          SEND
        </button>

.ts code

setStyles() 
{
    let styles = {

    'action-button-disabled': this.model.IsConnected() == false  
  };
  return styles;
}

What is a "static" function in C?

The answer to static function depends on the language:

1) In languages without OOPS like C, it means that the function is accessible only within the file where its defined.

2)In languages with OOPS like C++ , it means that the function can be called directly on the class without creating an instance of it.

Turn a string into a valid filename?

Just to further complicate things, you are not guaranteed to get a valid filename just by removing invalid characters. Since allowed characters differ on different filenames, a conservative approach could end up turning a valid name into an invalid one. You may want to add special handling for the cases where:

  • The string is all invalid characters (leaving you with an empty string)

  • You end up with a string with a special meaning, eg "." or ".."

  • On windows, certain device names are reserved. For instance, you can't create a file named "nul", "nul.txt" (or nul.anything in fact) The reserved names are:

    CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9

You can probably work around these issues by prepending some string to the filenames that can never result in one of these cases, and stripping invalid characters.

How are cookies passed in the HTTP protocol?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

Concatenate two NumPy arrays vertically

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

If you have been given a Session Token also, then you need to manually set it after configure:

aws configure set aws_session_token "<<your session token>>"

How to create a backup of a single table in a postgres database?

As an addition to Frank Heiken's answer, if you wish to use INSERT statements instead of copy from stdin, then you should specify the --inserts flag

pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename --inserts dbname

Notice that I left out the --ignore-version flag, because it is deprecated.

How to use ternary operator in razor (specifically on HTML attributes)?

in my problem I want the text of anchor <a>text</a> inside my view to be based on some value and that text is retrieved form App string Resources

so, this @() is the solution

<a href='#'>
      @(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>

if the text is not from App string Resources use this

@(Model.ID == 0 ? "Back" :"Descart Changes")

Hide keyboard in react-native

I just tested this using the latest React Native version (0.4.2), and the keyboard is dismissed when you tap elsewhere.

And FYI: you can set a callback function to be executed when you dismiss the keyboard by assigning it to the "onEndEditing" prop.

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

Repair all tables in one go

No need to type in the password, just use any one of these commands (self explanatory):

mysqlcheck --all-databases -a #analyze
mysqlcheck --all-databases -r #repair
mysqlcheck --all-databases -o #optimize

Batch file to split .csv file

If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).

The way to use mysplit.bat below is

mysplit.bat <mysize> 'myfile'

Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.

Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.

Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.

Script mysplit.bat:

@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell  ^
    $upperBound = 100MB;  ^
    $rootName = %2;  ^
    $from = $rootName;  ^
    $fromFile = [io.file]::OpenRead($from);  ^
    $buff = new-object byte[] $upperBound;  ^
    $count = $idx = 0;  ^
    try {  ^
        do {  ^
            'Reading ' + $upperBound;  ^
            $count = $fromFile.Read($buff, 0, $buff.Length);  ^
            if ($count -gt 0) {  ^
                $to = '{0}.{1}' -f ($rootName, $idx);  ^
                $toFile = [io.file]::OpenWrite($to);  ^
                try {  ^
                    'Writing ' + $count + ' to ' + $to;  ^
                    $tofile.Write($buff, 0, $count);  ^
                } finally {  ^
                    $tofile.Close();  ^
                }  ^
            }  ^
            $idx ++;  ^
        } while ($count -gt 0);  ^
    }  ^
    finally {  ^
        $fromFile.Close();  ^
    }  ^
%End PowerShell%

How to draw a circle with text in the middle?

Setting a line-height the same value as the height of the div will show one line of text vertically centered. In this example the height and line-height are 500px.

Example

JSFiddle

_x000D_
_x000D_
.circle {
  width: 500px;
  height: 500px;
  line-height: 500px;
  border-radius: 50%;
  font-size: 50px;
  color: #fff;
  text-align: center;
  background: #000
}
_x000D_
<div class="circle">Hello I am A Circle</div>
_x000D_
_x000D_
_x000D_

javascript change background color on click

Here you can find solutions for both your problems.

document.body.style.height = '500px';
document.body.addEventListener('click', function(e){
    var self = this,
        old_bg = this.style.background;

    this.style.background = this.style.background=='green'? 'blue':'green';
    setTimeout(function(){
        self.style.background = old_bg;
    }, 1000);
})

http://jsfiddle.net/ea1xf3sx/

Java Delegates?

Java doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates: 1. reflection; 2. inner class

Reflections are slooooow! Inner class does not cover the simplest use-case: sort function. Do not want to go into details, but the solution with inner class basically is to create a wrapper class for an array of integers to be sorted in ascending order and an class for an array of integers to be sorted in descending order.

What version of MongoDB is installed on Ubuntu

In the terminal just enter the traditional command:

mongod --version

How to find event listeners on a DOM node when debugging or from the JavaScript code?

Chrome, Firefox, Vivaldi and Safari support getEventListeners(domElement) in their Developer Tools console.

For majority of the debugging purposes, this could be used.

Below is a very good reference to use it: https://developers.google.com/web/tools/chrome-devtools/console/utilities#geteventlisteners

Android adding simple animations while setvisibility(view.Gone)

The easiest way to animate Visibility changes is use Transition API which available in support (androidx) package. Just call TransitionManager.beginDelayedTransition method then change visibility of the view. There are several default transitions like Fade, Slide.

import androidx.transition.TransitionManager;
import androidx.transition.Transition;
import androidx.transition.Fade;

private void toggle() {
    Transition transition = new Fade();
    transition.setDuration(600);
    transition.addTarget(R.id.image);

    TransitionManager.beginDelayedTransition(parent, transition);
    image.setVisibility(show ? View.VISIBLE : View.GONE);
}

Where parent is parent ViewGroup of animated view. Result:

enter image description here

Here is result with Slide transition:

import androidx.transition.Slide;

Transition transition = new Slide(Gravity.BOTTOM);

enter image description here

It is easy to write custom transition if you need something different. Here is example with CircularRevealTransition which I wrote in another answer. It shows and hide view with CircularReveal animation.

Transition transition = new CircularRevealTransition();

enter image description here

android:animateLayoutChanges="true" option does same thing, it just uses AutoTransition as transition.

How to set a time zone (or a Kind) of a DateTime value?

You can try this as well, it is easy to implement

TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);

Change the text to which standard time you want to change.

Use TimeZone feature of C# to implement.

Spring Boot: Cannot access REST Controller on localhost (404)

Place your springbootapplication class in root package for example if your service,controller is in springBoot.xyz package then your main class should be in springBoot package otherwise it will not scan below packages

How do I read configuration settings from Symfony2 config.yml?

Rather than defining contact_email within app.config, define it in a parameters entry:

parameters:
    contact_email: [email protected]

You should find the call you are making within your controller now works.

Java 8 lambda get and remove element from list

When we want to get multiple elements from a List into a new list (filter using a predicate) and remove them from the existing list, I could not find a proper answer anywhere.

Here is how we can do it using Java Streaming API partitioning.

Map<Boolean, List<ProducerDTO>> classifiedElements = producersProcedureActive
    .stream()
    .collect(Collectors.partitioningBy(producer -> producer.getPod().equals(pod)));

// get two new lists 
List<ProducerDTO> matching = classifiedElements.get(true);
List<ProducerDTO> nonMatching = classifiedElements.get(false);

// OR get non-matching elements to the existing list
producersProcedureActive = classifiedElements.get(false);

This way you effectively remove the filtered elements from the original list and add them to a new list.

Refer the 5.2. Collectors.partitioningBy section of this article.

Get the latest record with filter in Django

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Download and open PDF file using Ajax

This snippet is for angular js users which will face the same problem, Note that the response file is downloaded using a programmed click event. In this case , the headers were sent by server containing filename and content/type.

$http({
    method: 'POST', 
    url: 'DownloadAttachment_URL',
    data: { 'fileRef': 'filename.pdf' }, //I'm sending filename as a param
    headers: { 'Authorization': $localStorage.jwt === undefined ? jwt : $localStorage.jwt },
    responseType: 'arraybuffer',
}).success(function (data, status, headers, config) {
    headers = headers();
    var filename = headers['x-filename'];
    var contentType = headers['content-type'];
    var linkElement = document.createElement('a');
    try {
        var blob = new Blob([data], { type: contentType });
        var url = window.URL.createObjectURL(blob);

        linkElement.setAttribute('href', url);
        linkElement.setAttribute("download", filename);

        var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
        });
        linkElement.dispatchEvent(clickEvent);
    } catch (ex) {
        console.log(ex);
    }
}).error(function (data, status, headers, config) {
}).finally(function () {

});

The equivalent of a GOTO in python

I entirely agree that goto is poor poor coding, but no one has actually answered the question. There is in fact a goto module for Python (though it was released as an April fool joke and is not recommended to be used, it does work).

Display a float with two decimal places in Python

Shortest Python 3 syntax:

n = 5
print(f'{n:.2f}')

Show compose SMS view in Android

In Android , we have the class SmsManager which manages SMS operations such as sending data, text, and pdu SMS messages. Get this object by calling the static method SmsManager.getDefault().

SmsManager Javadoc

Check the following link to get the sample code for sending SMS:

article on sending and receiving SMS messages in Android

Angular cookies

Use NGX Cookie Service

Inastall this package: npm install ngx-cookie-service --save

Add the cookie service to your app.module.ts as a provider:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule, ... ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})

Then call in your component:

import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

ngOnInit(): void {
  this.cookieService.set( 'name', 'Test Cookie' ); // To Set Cookie
  this.cookieValue = this.cookieService.get('name'); // To Get Cookie
}

That's it!

WAMP/XAMPP is responding very slow over localhost

have a look here :

http://forum.wampserver.com/read.php?2,91602,page=3

Basically use 127.0.0.1 instead of localhost when connecting to mysql through php on windows 8

if your finding phpmyadmin slow

in the config.inc.php you can change localhost to 127.0.0.1 also

Dependency Injection vs Factory Pattern

I would suggest to keep the concepts plain and simple. Dependency Injection is more of a architectural pattern for loosely coupling software components. Factory pattern is just one way to separate the responsibility of creating objects of other classes to another entity. Factory pattern can be called as a tool to implement DI. Dependency injection can be implemented in many ways like DI using constructors, using mapping xml files etc.

Launch Minecraft from command line - username and password as prefix

This answer is going to briefly explain how the native files are handled on the latest launcher.

As of 4/29/2017 the Minecraft launcher for Windows extracts all native files and places them info %APPDATA%\Local\Temp{random folder}. That folder is temporary and is deleted once the javaw.exe process finishes (when Minecraft is closed). The location of that temporary folder must be provided in the launch arguments as the value of

-Djava.library.path=

Also, the latest launcher (2.0.847) does not show you the launch arguments so if you need to check them yourself you can do so under the Task Manager (simply enable the Command Line tab and expand it) or by using the WMIC utility as explained here.

Hope this helps some people who are still interested in doing this in 2017.

How can I turn a List of Lists into a List in Java 8?

Just as @Saravana mentioned:

flatmap is better but there are other ways to achieve the same

 listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
 });

To sum up, there are several ways to achieve the same as follows:

private <T> List<T> mergeOne(Stream<List<T>> listStream) {
    return listStream.flatMap(List::stream).collect(toList());
}

private <T> List<T> mergeTwo(Stream<List<T>> listStream) {
    List<T> result = new ArrayList<>();
    listStream.forEach(result::addAll);
    return result;
}

private <T> List<T> mergeThree(Stream<List<T>> listStream) {
    return listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
    });
}

private <T> List<T> mergeFour(Stream<List<T>> listStream) {
    return listStream.reduce((l1, l2) -> {
        List<T> l = new ArrayList<>(l1);
        l.addAll(l2);
        return l;
    }).orElse(new ArrayList<>());
}

private <T> List<T> mergeFive(Stream<List<T>> listStream) {
    return listStream.collect(ArrayList::new, List::addAll, List::addAll);
}

How to name variables on the fly?

FAQ says:

If you have

varname <- c("a", "b", "d")

you can do

get(varname[1]) + 2

for

a + 2

or

assign(varname[1], 2 + 2)

for

a <- 2 + 2

So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.

Syntax for assign: assign(x, value)

x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.

value: value to be assigned to x.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

If you want the sum of all bars to be equal unity, weight each bin by the total number of values:

weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)

Hope that helps, although the thread is quite old...

Note for Python 2.x: add casting to float() for one of the operators of the division as otherwise you would end up with zeros due to integer division

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

How do I display todays date on SSRS report?

  1. Inset Test box in the design area of the SSRS report.
  2. Right-click on the Textbox and scroll down and click on the Expression tab
  3. just type the given expression in the expression area: =format(Today,"dd/MM/yyyy")

Java: Detect duplicates in ArrayList?

Simply put: 1) make sure all items are comparable 2) sort the array 2) iterate over the array and find duplicates

GROUP BY having MAX date

Another way that doesn't use group by:

SELECT * FROM tblpm n 
  WHERE date_updated=(SELECT date_updated FROM tblpm n 
                        ORDER BY date_updated desc LIMIT 1)

bundle install fails with SSL certificate verification error

On windows7 you can download the cacert.pem file from here and set the environementvariable SSL_CERT_FILE to the path where you store the certificate eg

SET SSL_CERT_FILE="C:\users\<username>\cacert.pem"

or you can set the variable in your script like this ENV['SSL_CERT_FILE']="C:/users/<username>/cacert.pem"

Replace <username> with you own username.

Remove duplicates from a List<T> in C#

As a helper method (without Linq):

public static List<T> Distinct<T>(this List<T> list)
{
    return (new HashSet<T>(list)).ToList();
}

How do I delete NuGet packages that are not referenced by any project in my solution?

Solution 1

Use the powershell pipeline to get packages and remove in single statement like this

Get-Package | Uninstall-Package

Solution 2

if you want to uninstall selected packages follow these steps

  1. Use GetPackages to get the list of packages
  2. Download Nimble text software
  3. Copy the output of GetPackages in NimbleText(For each row in the list window)
  4. Set Column Seperator to ( if required
  5. Type Uninstall-Package $0 (Substitute using pattern window)
  6. Copy the results and paste them in Package Manage Console

That be all folks.

Adding values to a C# array

You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.

Command to get nth line of STDOUT

Is Perl easily available to you?

$ perl -n -e 'if ($. == 7) { print; exit(0); }'

Obviously substitute whatever number you want for 7.

How to scroll to top of page with JavaScript/jQuery?

Seeint the hash should do the job. If you have a header, you can use

window.location.href = "#headerid";

otherwise, the # alone will work

window.location.href = "#";

And as it get written into the url, it'll stay if you refresh.

In fact, you don't event need JavaScript for that if you want to do it on an onclick event, you should just put a link arround you element and give it # as href.

Rails: How to run `rails generate scaffold` when the model already exists?

I had this challenge when working on a Rails 6 API application in Ubuntu 20.04.

I had already existing models, and I needed to generate corresponding controllers for the models and also add their allowed attributes in the controller params.

Here's how I did it:

I used the rails generate scaffold_controller to get it done.

I simply ran the following commands:

rails generate scaffold_controller School name:string logo:json motto:text address:text

rails generate scaffold_controller Program name:string logo:json school:references

This generated the corresponding controllers for the models and also added their allowed attributes in the controller params, including the foreign key attributes.

create  app/controllers/schools_controller.rb
invoke  test_unit
create    test/controllers/schools_controller_test.rb

create  app/controllers/programs_controller.rb
invoke  test_unit
create    test/controllers/programs_controller_test.rb

That's all.

I hope this helps

C# "No suitable method found to override." -- but there is one

You need to inherit from the base class.

Emulator in Android Studio doesn't start

In Android Studio click on wipe data.

android stduio click wipe data

C# Generics and Type Checking

And, because C# has evolved, you can (now) use pattern matching.

private static string BuildClause<T>(IList<T> clause)
{
    if (clause.Count > 0)
    {
        switch (clause[0])
        {
            case int x: // do something with x, which is an int here...
            case decimal x: // do something with x, which is a decimal here...
            case string x: // do something with x, which is a string here...
            ...
            default: throw new ApplicationException("Invalid type");
        }
    }
}

And again with switch expressions in C# 8.0, the syntax gets even more succinct.

private static string BuildClause<T>(IList<T> clause)
{
    if (clause.Count > 0)
    {
        return clause[0] switch
        {
            int x => "some string related to this int",
            decimal x => "some string related to this decimal",
            string x => x,
            ...,
            _ => throw new ApplicationException("Invalid type")
        }
    }
}

How to get a Static property with Reflection

The below seems to work for me.

using System;
using System.Reflection;

public class ReflectStatic
{
    private static int SomeNumber {get; set;}
    public static object SomeReference {get; set;}
    static ReflectStatic()
    {
        SomeReference = new object();
        Console.WriteLine(SomeReference.GetHashCode());
    }
}

public class Program
{
    public static void Main()
    {
        var rs = new ReflectStatic();
        var pi = rs.GetType().GetProperty("SomeReference",  BindingFlags.Static | BindingFlags.Public);
        if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
        Console.WriteLine(pi.GetValue(rs, null).GetHashCode());


    }
}

Example of a strong and weak entity types

After browsing search engines for a few hours I came across a site with a great ERD example here: http://www.exploredatabase.com/2016/07/description-about-weak-entity-sets-in-DBMS.html

I've recreated the ERD. Unfortunately they did not specify the primary key of the weak entity.

enter image description here

If the building could only have one and only one apartment, then it seems the partial discriminator room number would not be created (i.e. discarded).

Email and phone Number Validation in android

//validation class

public class EditTextValidation {

public static boolean isValidText(CharSequence target) {
    return target != null && target.length() != 0;
}

public static boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

public static boolean isValidPhoneNumber(CharSequence target) {
    if (target.length() != 10) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}

//activity or fragment

    val userName = registerNameET.text?.trim().toString()
    val mobileNo = registerMobileET.text?.trim().toString()
    val emailID = registerEmailIDET.text?.trim().toString()

    when {
        !EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
        !EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
            "Please provide email"
        !EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
            "Please provide mobile number"
        else -> {
            showToast("Hello World")
        }
    }

**Hope it will work for you... It is a working example.

JAX-WS and BASIC authentication, when user names and passwords are in a database

If you put the username and password at clientside into the request this way:

URL url = new URL("http://localhost:8080/myapplication?wsdl");
MyWebService webservice = new MyWebServiceImplService(url).getMyWebServiceImplPort();
Map<String, Object> requestContext = ((BindingProvider) webservice).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "myusername");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "mypassword");

and call your webservice

String response = webservice.someMethodAtMyWebservice("test");

Then you can read the Basic Authentication string like this at the server side (you have to add some checks and do some exceptionhandling):

@Resource
WebServiceContext webserviceContext;

public void someMethodAtMyWebservice(String parameter) {
    MessageContext messageContext = webserviceContext.getMessageContext();
    Map<String, ?> httpRequestHeaders = (Map<String, ?>) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
    List<?> authorizationList = (List<?>) httpRequestHeaders.get("Authorization");
    if (authorizationList != null && !authorizationList.isEmpty()) {
        String basicString = (String) authorizationList.get(0);
        String encodedBasicString = basicString.substring("Basic ".length());
        String decoded = new String(Base64.getDecoder().decode(encodedBasicString), StandardCharsets.UTF_8);
        String[] splitter = decoded.split(":");
        String usernameFromBasicAuth = splitter[0];
        String passwordFromBasicAuth = splitter[1];
    }

How to get the parent dir location

os.path.dirname(os.path.abspath(__file__))

Should give you the path to a.

But if b.py is the file that is currently executed, then you can achieve the same by just doing

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))

How to run ssh-add on windows?

If you are trying to setup a key for using git with ssh, there's always an option to add a configuration for the identity file.

vi ~/.ssh/config

Host example.com
IdentityFile ~/.ssh/example_key

Illegal access: this web application instance has been stopped already

Restarting Your Server Can Resolve this problem.

I was getting the same error while Using Dynamic Jasper Reporting , When i deploy my Application for first use to Create Reports, the Report creation works fine, But Once I Do Hot Deployment of some code changes To the Server, I was getting This Error.

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

Laravel 4: how to "order by" using Eloquent ORM

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

Select by partial string from a pandas DataFrame

Say you have the following DataFrame:

>>> df = pd.DataFrame([['hello', 'hello world'], ['abcd', 'defg']], columns=['a','b'])
>>> df
       a            b
0  hello  hello world
1   abcd         defg

You can always use the in operator in a lambda expression to create your filter.

>>> df.apply(lambda x: x['a'] in x['b'], axis=1)
0     True
1    False
dtype: bool

The trick here is to use the axis=1 option in the apply to pass elements to the lambda function row by row, as opposed to column by column.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

I know that we are (n-1) * (n times), but why the division by 2?

It's only (n - 1) * n if you use a naive bubblesort. You can get a significant savings if you notice the following:

  • After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.

  • After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.

Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + .... This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.

Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.

Android WebView Cookie Problem

Couple of comments (at least for APIs >= 21) which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won't have to face the same problems like I did.

Redirect to new Page in AngularJS using $location

$location won't help you with external URLs, use the $window service instead:

$window.location.href = 'http://www.google.com';

Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.

Change MySQL default character set to UTF-8 in my.cnf?

MySQL 5.5, all you need is:

[mysqld]
character_set_client=utf8
character_set_server=utf8
collation_server=utf8_unicode_ci

collation_server is optional.

mysql> show variables like 'char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

How to access PHP session variables from jQuery function in a .js file?

You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:

<script src='javascript.php'></script>

Then your script file:

<?php header("Content-type: application/javascript"); ?>

$(function() {
    $( "#progressbar" ).progressbar({
        value: <?php echo $_SESSION['value'] ?>
    });

    // ... more javascript ...

If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.

Copy a file in a sane, safe and efficient way

I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.

Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.

Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.

As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.

I suppose you could slightly improve performances in specific cases. Off the top of my head:

  • If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
  • If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
  • If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).

But all that is outside the scope of a general purpose file copy function.

So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.

How to find my Subversion server version number?

For Subversion 1.7 and above, the server doesn't provide a footer that indicates the server version. But you can run the following command to gain the version from the response headers

$ curl -s -D - http://svn.server.net/svn/repository
HTTP/1.1 401 Authorization Required
Date: Wed, 09 Jan 2013 03:01:43 GMT
Server: Apache/2.2.9 (Unix) DAV/2 SVN/1.7.4

Note that this also works on Subversion servers where you don't have authorization to access.

How to terminate a python subprocess launched with shell=True

what i feel like we could use:

import os
import signal
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

os.killpg(os.getpgid(pro.pid), signal.SIGINT)

this will not kill all your task but the process with the p.pid

Converting file size in bytes to human-readable string

My answer might be late, but I guess it will help someone.

Metric prefix:

/**
 * Format file size in metric prefix
 * @param fileSize
 * @returns {string}
 */
const formatFileSizeMetric = (fileSize) => {
  let size = Math.abs(fileSize);

  if (Number.isNaN(size)) {
    return 'Invalid file size';
  }

  if (size === 0) {
    return '0 bytes';
  }

  const units = ['bytes', 'kB', 'MB', 'GB', 'TB'];
  let quotient = Math.floor(Math.log10(size) / 3);
  quotient = quotient < units.length ? quotient : units.length - 1;
  size /= (1000 ** quotient);

  return `${+size.toFixed(2)} ${units[quotient]}`;
};

Binary prefix:

/**
 * Format file size in binary prefix
 * @param fileSize
 * @returns {string}
 */
const formatFileSizeBinary = (fileSize) => {
  let size = Math.abs(fileSize);

  if (Number.isNaN(size)) {
    return 'Invalid file size';
  }

  if (size === 0) {
    return '0 bytes';
  }

  const units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB'];
  let quotient = Math.floor(Math.log2(size) / 10);
  quotient = quotient < units.length ? quotient : units.length - 1;
  size /= (1024 ** quotient);

  return `${+size.toFixed(2)} ${units[quotient]}`;
};

Examples:

// Metrics prefix
formatFileSizeMetric(0)      // 0 bytes
formatFileSizeMetric(-1)     // 1 bytes
formatFileSizeMetric(100)    // 100 bytes
formatFileSizeMetric(1000)   // 1 kB
formatFileSizeMetric(10**5)  // 10 kB
formatFileSizeMetric(10**6)  // 1 MB
formatFileSizeMetric(10**9)  // 1GB
formatFileSizeMetric(10**12) // 1 TB
formatFileSizeMetric(10**15) // 1000 TB

// Binary prefix
formatFileSizeBinary(0)     // 0 bytes
formatFileSizeBinary(-1)    // 1 bytes
formatFileSizeBinary(1024)  // 1 kiB
formatFileSizeBinary(2048)  // 2 kiB
formatFileSizeBinary(2**20) // 1 MiB
formatFileSizeBinary(2**30) // 1 GiB
formatFileSizeBinary(2**40) // 1 TiB
formatFileSizeBinary(2**50) // 1024 TiB

Change key pair for ec2 instance

Yegor256's answer worked for me, but I thought I would just add some comments to help out those who are not so good at mounting drives(like me!):

Amazon gives you a choice of what you want to name the volume when you attach it. You have use a name in the range from /dev/sda - /dev/sdp The newer versions of Ubuntu will then rename what you put in there to /dev/xvd(x) or something to that effect.

So for me, I chose /dev/sdp as name the mount name in AWS, then I logged into the server, and discovered that Ubuntu had renamed my volume to /dev/xvdp1). I then had to mount the drive - for me I had to do it like this:

mount -t ext4 xvdp1 /mnt/tmp

After jumping through all those hoops I could access my files at /mnt/tmp

Changing nav-bar color after scrolling?

Here is simplest way how to change navbar color after window scroll:

Add follow JS to head:

$(function () {
  $(document).scroll(function () {
    var $nav = $(".navbar-fixed-top");
    $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
  });
});

and this CSS code

.navbar-fixed-top.scrolled {
  background-color: #fff !important;
  transition: background-color 200ms linear;
}

Background color of fixed navbar will be change to white when scroll exceeds height of navbar.

See follow JsFiddle

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

C# switch statement limitations - why?

Mostly, those restrictions are in place because of language designers. The underlying justification may be compatibility with languange history, ideals, or simplification of compiler design.

The compiler may (and does) choose to:

  • create a big if-else statement
  • use a MSIL switch instruction (jump table)
  • build a Generic.Dictionary<string,int32>, populate it on first use, and call Generic.Dictionary<>::TryGetValue() for a index to pass to a MSIL switch instruction (jump table)
  • use a combination of if-elses & MSIL "switch" jumps

The switch statement IS NOT a constant time branch. The compiler may find short-cuts (using hash buckets, etc), but more complicated cases will generate more complicated MSIL code with some cases branching out earlier than others.

To handle the String case, the compiler will end up (at some point) using a.Equals(b) (and possibly a.GetHashCode() ). I think it would be trival for the compiler to use any object that satisfies these constraints.

As for the need for static case expressions... some of those optimisations (hashing, caching, etc) would not be available if the case expressions weren't deterministic. But we've already seen that sometimes the compiler just picks the simplistic if-else-if-else road anyway...

Edit: lomaxx - Your understanding of the "typeof" operator is not correct. The "typeof" operator is used to obtain the System.Type object for a type (nothing to do with its supertypes or interfaces). Checking run-time compatibility of an object with a given type is the "is" operator's job. The use of "typeof" here to express an object is irrelevant.

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

How to install an apk on the emulator in Android Studio?

In android studio emulator to run an apk file just drag the apk into the emulator.The emulator will install the apk

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

I was able to get the full text (99,208 chars) out of a NVARCHAR(MAX) column by selecting (Results To Grid) just that column and then right-clicking on it and then saving the result as a CSV file. To view the result open the CSV file with a text editor (NOT Excel). Funny enough, when I tried to run the same query, but having Results to File enabled, the output was truncated using the Results to Text limit.

The work-around that @MartinSmith described as a comment to the (currently) accepted answer didn't work for me (got an error when trying to view the full XML result complaining about "The '[' character, hexadecimal value 0x5B, cannot be included in a name").

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

BACKUP LOG cannot be performed because there is no current database backup

Another cause for this is if you have the same database restored under a different name. Delete the existing one and then restoring solved it for me.

eval command in Bash and its typical uses

eval takes a string as its argument, and evaluates it as if you'd typed that string on a command line. (If you pass several arguments, they are first joined with spaces between them.)

${$n} is a syntax error in bash. Inside the braces, you can only have a variable name, with some possible prefix and suffixes, but you can't have arbitrary bash syntax and in particular you can't use variable expansion. There is a way of saying “the value of the variable whose name is in this variable”, though:

echo ${!n}
one

$(…) runs the command specified inside the parentheses in a subshell (i.e. in a separate process that inherits all settings such as variable values from the current shell), and gathers its output. So echo $($n) runs $n as a shell command, and displays its output. Since $n evaluates to 1, $($n) attempts to run the command 1, which does not exist.

eval echo \${$n} runs the parameters passed to eval. After expansion, the parameters are echo and ${1}. So eval echo \${$n} runs the command echo ${1}.

Note that most of the time, you must use double quotes around variable substitutions and command substitutions (i.e. anytime there's a $): "$foo", "$(foo)". Always put double quotes around variable and command substitutions, unless you know you need to leave them off. Without the double quotes, the shell performs field splitting (i.e. it splits value of the variable or the output from the command into separate words) and then treats each word as a wildcard pattern. For example:

$ ls
file1 file2 otherfile
$ set -- 'f* *'
$ echo "$1"
f* *
$ echo $1
file1 file2 file1 file2 otherfile
$ n=1
$ eval echo \${$n}
file1 file2 file1 file2 otherfile
$eval echo \"\${$n}\"
f* *
$ echo "${!n}"
f* *

eval is not used very often. In some shells, the most common use is to obtain the value of a variable whose name is not known until runtime. In bash, this is not necessary thanks to the ${!VAR} syntax. eval is still useful when you need to construct a longer command containing operators, reserved words, etc.

Configuring angularjs with eclipse IDE

Now you can see the Angularjs tags available as shown below.

AngularJS Tags are available.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

using sinon :

const mockAction = sinon.stub(MyService.prototype,'actionBeingCalled')
                     .returns(httpPromise(200));

Known that, httpPromise can be :

const httpPromise = (code) => new Promise((resolve, reject) =>
  (code >= 200 && code <= 299) ? resolve({ code }) : reject({ code, error:true })
);

fatal: 'origin' does not appear to be a git repository

Try to create remote origin first, maybe is missing because you change name of the remote repo

git remote add origin URL_TO_YOUR_REPO

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

I know this is an old post, but for anyone upgrading to Mountain Lion (10.8) and experiencing similar issues, adding FollowSymLinks to your {username}.conf file (in /etc/apache2/users/) did the trick for me. So the file looks like this:

<Directory "/Users/username/Sites/">
  Options Indexes MultiViews FollowSymLinks
  AllowOverride All
  Order allow,deny
  Allow from all
</Directory>

How can I convert a string to upper- or lower-case with XSLT?

For ANSI character encoding:

 translate(//variable, 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ', 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ')

Static constant string (class member)

possible just do:

static const std::string RECTANGLE() const {
    return "rectangle";
} 

or

#define RECTANGLE "rectangle"

How to have a transparent ImageButton: Android

Don't use null or transparent if you need a click animation. Better:

//Rectangular click animation
android:background="?attr/selectableItemBackground"

//Rounded click animation
android:background="?attr/selectableItemBackgroundBorderless"

Recursive file search using PowerShell

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat

Will also work

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

Twitter bootstrap scrollable modal

Your modal is being hidden in firefox, and that is because of the negative margin declaration you have inside your general stylesheet:

.modal {
    margin-top: -45%; /* remove this */
    max-height: 90%;
    overflow-y: auto;
}

Remove the negative margin and everything works just fine.

New Array from Index Range Swift

Array functional way:

   array.enumerated().filter { $0.offset < limit }.map { $0.element }

ranged:

 array.enumerated().filter { $0.offset >= minLimit && $0.offset < maxLimit }.map { $0.element }

The advantage of this method is such implementation is safe.

How can I read the client's machine/computer name from the browser?

Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.

EDIT: Not possible across all browser at least.

how to create inline style with :before and :after

The key is to use background-color: inherit; on the pseudo element.
See: http://jsfiddle.net/EdUmc/

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Java Date - Insert into database

Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.

To answer your question, as others have mentioned, look into java.sql.PreparedStatement, and use java.sql.Date or java.sql.Timestamp. Something like (to use your original code as much as possible, you probably want to change it even more):

java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");

Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);

stmt.executeUpdate(); // optionally check the return value of this call

One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).

What to do with commit made in a detached head

Alternatively, you could cherry-pick the commit-id onto your branch.

<commit-id> made in detached head state

git checkout master

git cherry-pick <commit-id>

No temporary branches, no merging.

How to select all textareas and textboxes using jQuery?

$("**:**input[type=text], :input[type='textarea']").css({width: '90%'});

How to identify server IP address in PHP

The previous answers all give $_SERVER['SERVER_ADDR']. This will not work on some IIS installations. If you want this to work on IIS, then use the following:

$server_ip = gethostbyname($_SERVER['SERVER_NAME']);

How to get the name of the current method from code

You can also use MethodBase.GetCurrentMethod() which will inhibit the JIT compiler from inlining the method where it's used.


Update:

This method contains a special enumeration StackCrawlMark that from my understanding will specify to the JIT compiler that the current method should not be inlined.

This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

Javascript: How to pass a function with string parameters as a parameter to another function

Me, I'd do it something like this:

HTML:

onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"

JS:

function myfunction(params)
{
  var path = params.path;

  /* do stuff */

  // on ok condition 
  params.ok(params.okArgs);

  // on cancel condition
  params.cancel(params.cancelArgs);  
}

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

How to find sitemap.xml path on websites?

The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

How do I simulate placeholder functionality on input date field?

I'm using the following CSS only trick:

_x000D_
_x000D_
  input[type="date"]:before {_x000D_
    content: attr(placeholder) !important;_x000D_
    color: #aaa;_x000D_
    margin-right: 0.5em;_x000D_
  }_x000D_
  input[type="date"]:focus:before,_x000D_
  input[type="date"]:valid:before {_x000D_
    content: "";_x000D_
  }
_x000D_
<input type="date" placeholder="Choose a Date" />
_x000D_
_x000D_
_x000D_

How to have click event ONLY fire on parent DIV, not children?

You can use event.currentTarget. It will do click event only elemnt who got event.

_x000D_
_x000D_
target = e => {_x000D_
    console.log(e.currentTarget);_x000D_
  };
_x000D_
<ul onClick={target} className="folder">_x000D_
      <li>_x000D_
        <p>_x000D_
          <i className="fas fa-folder" />_x000D_
        </p>_x000D_
      </li>_x000D_
    </ul>
_x000D_
_x000D_
_x000D_

How to convert a negative number to positive?

If you are working with numpy you can use

import numpy as np
np.abs(-1.23)
>> 1.23

It will provide absolute values.

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

RegEx pattern any two letters followed by six numbers

I depends on what is the regexp language you use, but informally, it would be:

[:alpha:][:alpha:][:digit:][:digit:][:digit:][:digit:][:digit:][:digit:]

where [:alpha:] = [a-zA-Z] and [:digit:] = [0-9]

If you use a regexp language that allows finite repetitions, that would look like:

[:alpha:]{2}[:digit:]{6}

The correct syntax depends on the particular language you're using, but that is the idea.

How do I get extra data from intent on Android?

We can do it by simple means:

In FirstActivity:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

In SecondActivity:

    try {
        Intent intent = getIntent();

        String uid = intent.getStringExtra("uid");
        String pwd = intent.getStringExtra("pwd");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("getStringExtra_EX", e + "");
    }

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

jQuery .each() index?

$('#list option').each(function(intIndex){
//do stuff
});

Run MySQLDump without Locking Tables

If you use the Percona XtraDB Cluster - I found that adding --skip-add-locks
to the mysqldump command Allows the Percona XtraDB Cluster to run the dump file without an issue about LOCK TABLES commands in the dump file.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

None of the above worked out for me until I changed the Action as [HttpPost]. and made the ajax type as POST.

    [HttpPost]
    public JsonResult GetSelectedSignalData(string signal1,...)
    {
         JsonResult result = new JsonResult();
         var signalData = GetTheData();
         try
         {
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

            result.Data = serializer.Serialize(signalData);
            return Json(result, JsonRequestBehavior.AllowGet);
            ..
            ..
            ...

    }

And the ajax call as

$.ajax({
    type: "POST",
    url: some_url,
    data: JSON.stringify({  signal1: signal1,.. }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data !== null) {
            setValue();
        }

    },
    failure: function (data) {
        $('#errMessage').text("Error...");
    },
    error: function (data) {
        $('#errMessage').text("Error...");
    }
});

How do I find out what License has been applied to my SQL Server installation?

SQL Server does not track licensing. Customers are responsible for tracking the assignment of licenses to servers, following the rules in the Licensing Guide.

Why does git status show branch is up-to-date when changes exist upstream?

Trivial answer yet accurate in some cases, such as the one that brought me here. I was working in a repo which was new for me and I added a file which was not seen as new by the status.

It ends up that the file matched a pattern in the .gitignore file.

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

How to put a UserControl into Visual Studio toolBox

I'm assuming you're using VS2010 (that's what you've tagged the question as) I had problems getting them to add automatically to the toolbox as in VS2008/2005. There's actually an option to stop the toolbox auto populating!

Go to Tools > Options > Windows Forms Designer > General

At the bottom of the list you'll find Toolbox > AutoToolboxPopulate which on a fresh install defaults to False. Set it true and then rebuild your solution.

Hey presto they user controls in you solution should be automatically added to the toolbox. You might have to reload the solution as well.

jQuery pass more parameters into callback

If someone still comes here, this is my take:

$('.selector').click(myCallbackFunction.bind({var1: 'hello', var2: 'world'}));

function myCallbackFunction(event) {
    var passedArg1 = this.var1,
        passedArg2 = this.var2
}

What happens here, after binding to the callback function, it will be available within the function as this.

This idea comes from how React uses the bind functionality.

How do you rename a Git tag?

This wiki page has this interesting one-liner, which reminds us that we can push several refs:

git push origin refs/tags/<old-tag>:refs/tags/<new-tag> :refs/tags/<old-tag> && git tag -d <old-tag>

and ask other cloners to do git pull --prune --tags

So the idea is to push:

  • <new-tag> for every commits referenced by <old-tag>: refs/tags/<old-tag>:refs/tags/<new-tag>,
  • the deletion of <old-tag>: :refs/tags/<old-tag>

See as an example "Change naming convention of tags inside a git repository?".

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

To replace nan in different columns with different ways:

   replacement= {'column_A': 0, 'column_B': -999, 'column_C': -99999}
   df.fillna(value=replacement)

Spring security CORS Filter

This solution unlock me after couple of hours of research :

In the configuration initialize the core() option

@Override
public void configure(HttpSecurity http) throws Exception {
http
    .cors()
    .and()
    .etc
}

Initialize your Credential, Origin, Header and Method as your wish in the corsFilter.

@Bean
public CorsFilter corsFilter() {
  UrlBasedCorsConfigurationSource source = new 
  UrlBasedCorsConfigurationSource();
  CorsConfiguration config = new CorsConfiguration();
  config.setAllowCredentials(true);
  config.addAllowedOrigin("*");
  config.addAllowedHeader("*");
  config.addAllowedMethod("*");
  source.registerCorsConfiguration("/**", config);
  return new CorsFilter(source);
}

I didn't need to use this class:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
}

deleting rows in numpy array

This is similar to your original approach, and will use less space than unutbu's answer, but I suspect it will be slower.

>>> import numpy as np
>>> p = np.array([[1.5, 0], [1.4,1.5], [1.6, 0], [1.7, 1.8]])
>>> p
array([[ 1.5,  0. ],
       [ 1.4,  1.5],
       [ 1.6,  0. ],
       [ 1.7,  1.8]])
>>> nz = (p == 0).sum(1)
>>> q = p[nz == 0, :]
>>> q
array([[ 1.4,  1.5],
       [ 1.7,  1.8]])

By the way, your line p.delete() doesn't work for me - ndarrays don't have a .delete attribute.

Java: Best way to iterate through a Collection (here ArrayList)

The first one is useful when you need the index of the element as well. This is basically equivalent to the other two variants for ArrayLists, but will be really slow if you use a LinkedList.

The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate. But this has the disadvantage of being a little too verbose IMO.

The third version is my preferred choice as well. It is short and works for all cases where you do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the Collection in any way - which is the most common case).

Pass Javascript variable to PHP via ajax

Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId

I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.

sql query with multiple where statements

Can we see the structure of your table? If I am understanding this, then the assumption made by the query is that a record can be only meta_key - 'lat' or meta_key = 'long' not both because each row only has one meta_key column and can only contain 1 corresponding value, not 2. That would explain why you don't get results when you connect the with an AND; it's impossible.

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

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

I found another solution for new Sonar versions where JaCoCo's binary report format (*.exec) was deprecated and the preferred format is XML (SonarJava 5.12 and higher). The solution is very simple and similar to the previous solution with *.exec reports in parent directory from this topic: https://stackoverflow.com/a/15535970/4448263.

Assuming that our project structure is:

moduleC - aggregate project's pom
  |- moduleA - some classes without tests
  |- moduleB - some classes depending from moduleA and tests for classes in both modules: moduleA and moduleB

You need following maven build plugin configuration in aggregate project's pom:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.5</version>
    <executions>
        <execution>
            <id>prepare-and-report</id>
            <goals>
                <goal>prepare-agent</goal>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>report-aggregate</id>
            <phase>verify</phase>
            <goals>
                <goal>report-aggregate</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.basedir}/../target/site/jacoco-aggregate</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Then build project with maven:

mvn clean verify

And for Sonar you should set property in administration GUI:

sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml,../target/site/jacoco-aggregate/jacoco.xml

or using command line:

mvn sonar:sonar -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml,../target/site/jacoco-aggregate/jacoco.xml

Description

This creates binary reports for each module in default directories: target/jacoco.exec. Then creates XML reports for each module in default directories: target/site/jacoco/jacoco.xml. Then creates an aggregate report for each module in custom directory ${project.basedir}/../target/site/jacoco-aggregate/ that is relative to parent directory for each module. For moduleA and moduleB this will be common path moduleC/target/site/jacoco-aggregate/.

As moduleB depends on moduleA, moduleB will be built last and its report will be used as an aggregate coverage report in Sonar for both modules A and B.

In addition to the aggregate report, we need a normal module report as JaCoCo aggregate reports contain coverage data only for dependencies.

Together, these two types of reports providing full coverage data for Sonar.

There is one little restriction: you should be able to write a report in the project's parent directory (should have permission). Or you can set property jacoco.skip=true in root project's pom.xml (moduleC) and jacoco.skip=false in modules with classes and tests (moduleA and moduleB).

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

Passing an Array as Arguments, not an Array, in PHP

As has been mentioned, as of PHP 5.6+ you can (should!) use the ... token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:

<?php
function variadic($arg1, $arg2)
{
    // Do stuff
    echo $arg1.' '.$arg2;
}

$array = ['Hello', 'World'];

// 'Splat' the $array in the function call
variadic(...$array);

// 'Hello World'

Note: array items are mapped to arguments by their position in the array, not their keys.

As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array.

Aside

Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.

(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)

This is great for making sure an array contains items of a specific type:

<?php

// Define the function...

function variadic($var, SomeClass ...$items)
{
    // $items will be an array of objects of type `SomeClass`
}

// Then you can call...

variadic('Hello', new SomeClass, new SomeClass);

// or even splat both ways

$items = [
    new SomeClass,
    new SomeClass,
];

variadic('Hello', ...$items);

How to get the type of T from a member of a generic class or method?

If you dont need the whole Type variable and just want to check the type you can easily create a temp variable and use is operator.

T checkType = default(T);

if (checkType is MyClass)
{}

Android - styling seek bar

Just replace color atributtes with your color

background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">

    <stroke android:width="1dp" android:color="#D9D9D9"/>
    <corners android:radius="1dp" />

</shape>

progress.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="line">

    <stroke android:width="1dp" android:color="#2EA5DE"/>
    <corners android:radius="1dp" />

</shape>

style.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar_background"/>
    <item android:id="@android:id/progress">
        <clip android:drawable="@drawable/seekbar_progress" />
    </item>

</layer-list>

thumb.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size android:height="30dp" android:width="30dp"/>
    <stroke android:width="18dp" android:color="#882EA5DE"/>
    <solid android:color="#2EA5DE" />
    <corners android:radius="1dp" />

</shape>

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

Stack smashing detected

Stack Smashing here is actually caused due to a protection mechanism used by gcc to detect buffer overflow errors. For example in the following snippet:

#include <stdio.h>

void func()
{
    char array[10];
    gets(array);
}

int main(int argc, char **argv)
{
    func();
}

The compiler, (in this case gcc) adds protection variables (called canaries) which have known values. An input string of size greater than 10 causes corruption of this variable resulting in SIGABRT to terminate the program.

To get some insight, you can try disabling this protection of gcc using option -fno-stack-protector while compiling. In that case you will get a different error, most likely a segmentation fault as you are trying to access an illegal memory location. Note that -fstack-protector should always be turned on for release builds as it is a security feature.

You can get some information about the point of overflow by running the program with a debugger. Valgrind doesn't work well with stack-related errors, but like a debugger, it may help you pin-point the location and reason for the crash.

How to edit default.aspx on SharePoint site without SharePoint Designer

Go to view all content of the site (http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx). Select the document library "Pages" (the "Pages" library are named based on the language you created the site in. I.E. in norwegian the library is named "Sider"). Download the default.aspx to you computer and fix it (remove the web part and the <%Register tag). Save it and upload it back to the library (remember to check in the file).

EDIT:

ahh.. you are not using a publishing site template. Go to site action -> site settings. Under "site administration" select the menu "content and structure" you should now see your default.aspx page. But you cant do much with it...(delete, copy or move)

workaround: Enable publishing feature to the root web. Add the fixed default.aspx file to the Pages library and change the welcome page to this. Disable the publishing feature (this will delete all other list create from this feature but not the Pages library since one page is in use.). You will now have a new default.aspx page for the root web but the url is changed from sitename/default.aspx to sitename/Pages/default.aspx.

workaround II Use a feature to change the default.aspx file. The solution is explained here: http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx

Return JSON response from Flask view

Flask 1.1.x supports returning a JSON dict without calling jsonify. If you want to return something besides a dict, you still need to call jsonify.

@app.route("/")
def index():
    return {
        "api_stuff": "values",
    }

is equivalent to

@app.route("/")
def index():
    return jsonify({
        "api_stuff": "values",
    })

See the pull request that added this: https://github.com/pallets/flask/pull/3111

Importing a csv into mysql via command line

Most answers missing an important point like if you have created csv file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.

the correct syntax would be

load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'

here the difference is '\r\n' as against simply '\n

Maven project version inheritance - do I have to specify the parent version?

<parent>
    <groupId>com.dummy.bla</groupId>
    <artifactId>parent</artifactId>
    <version>0.1-SNAPSHOT</version>     
 </parent>

 <groupId>com.dummy.bla.sub</groupId>
 <artifactId>kid</artifactId>

You mean you want to remove the version from parent block of B's pom, I think you can not do it, the groupId, artifactId, and version specified the parent's pom coordinate's, what you can omit is child's version.

Outputting data from unit test in Python

We use the logging module for this.

For example:

import logging
class SomeTest( unittest.TestCase ):
    def testSomething( self ):
        log= logging.getLogger( "SomeTest.testSomething" )
        log.debug( "this= %r", self.this )
        log.debug( "that= %r", self.that )
        # etc.
        self.assertEquals( 3.14, pi )

if __name__ == "__main__":
    logging.basicConfig( stream=sys.stderr )
    logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
    unittest.main()

That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.

My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

I wrote a little bash onliner that you can write to a script to get a friendly output:

mysql_references_to:

mysql -uUSER -pPASS -A DB_NAME -se "USE information_schema; SELECT * FROM KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = '$1' AND REFERENCED_COLUMN_NAME = 'id'\G" | sed 's/^[ \t]*//;s/[ \t]*$//' |egrep "\<TABLE_NAME|\<COLUMN_NAME" |sed 's/TABLE_NAME: /./g' |sed 's/COLUMN_NAME: //g' | paste -sd "," -| tr '.' '\n' |sed 's/,$//' |sed 's/,/./'

So the execution: mysql_references_to transaccion (where transaccion is a random table name) gives an output like this:

carrito_transaccion.transaccion_id
comanda_detalle.transaccion_id
comanda_detalle_devolucion.transaccion_positiva_id
comanda_detalle_devolucion.transaccion_negativa_id
comanda_transaccion.transaccion_id
cuenta_operacion.transaccion_id
...

Oracle SqlDeveloper JDK path

another thing you could try is to rename your old jdk folder, lets say its:

C:\Program Files\Java\jdk1.7.0_04

change it to saomething like:

C:\Program Files\Java\xxxjdk1.7.0_04

Now, you should once again asked to set your jdk folder location on Oracle SqlDeveloper launch, and you can chose the right path.

Not the most elegant solution, but it worked for me.

Milos

Take screenshots in the iOS simulator

It's just as simple as command+s or File > Save Screen Shot in iOS Simulator. It will appear on your desktop by default.

How to retrieve all keys (or values) from a std::map and put them into a vector?

Also, if you have Boost, use transform_iterator to avoid making a temporary copy of the keys.

Escape quote in web.config connection string

if &quot; isn't working then try &#34; instead.

Environment variable substitution in sed

In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).

So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.

sed 's/foo/$BAR/g'
sed "s/foo/$BAR/g"

In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.

How do I convert a float number to a whole number in JavaScript?

Bit shift by 0 which is equivalent to division by 1

// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

Multiprocessing a for loop?

Alternatively

with Pool() as pool: 
    pool.map(fits.open, [name + '.fits' for name in datainput])

How to change MenuItem icon in ActionBar programmatically

You can't use findViewById() on menu items in onCreate() because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu() and then use it in your onClick().

private Menu menu;

In your onCreateOptionsMenu()

this.menu = menu;

In your button's onClick() method

menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));

jQuery send string as POST parameters

I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.

var bar = 'xyz';
var calibri = 'no$libri';

$.ajax({
   type: "POST",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   url: "http://nakolesah.ru/",
   data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
   success: function(msg){
       alert('wow'+msg);
   },
});

Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

While not contesting the other answers, I think the following is worthy of mentioning.

  1. The “long” (http-equiv) notation and the “short” one are equal, whichever comes first wins;
  2. Web server headers will override all the <meta> tags;
  3. BOM (Byte order mark) will override everything, and in many cases it will affect html 4 (and probably other stuff, too);
  4. If you don't declare any encoding, you will probably get your text in “fallback text encoding” that is defined your browser. Neither in Firefox nor in Chrome it's utf-8;
  5. In absence of other clues the browser will attempt to read your document as if it was in ASCII to get the encoding, so you can't use any weird encodings (utf-16 with BOM should do, though);
  6. While the specs say that the encoding declaration must be within the first 512 bytes of the document, most browsers will try reading more than that.

You can test by running echo 'HTTP/1.1 200 OK\r\nContent-type: text/html; charset=windows-1251\r\n\r\n\xef\xbb\xbf<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta charset="windows-1251"><title>??????</title></head><body>??????</body></html>' | nc -lp 4500 and pointing your browser at localhost:4500. (Of course you will want to change or remove parts. The BOM part is \xef\xbb\xbf. Be wary of the encoding of your shell.)

Please mind that it's very important that you explicitly declare the encoding. Letting browsers guess can lead to security issues.

Official way to ask jQuery wait for all images to load before executing something

With jQuery i come with this...

$(function() {
    var $img = $('img'),
        totalImg = $img.length;

    var waitImgDone = function() {
        totalImg--;
        if (!totalImg) alert("Images loaded!");
    };

    $('img').each(function() {
        $(this)
            .load(waitImgDone)
            .error(waitImgDone);
    });
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

How do you uninstall all dependencies listed in package.json (NPM)?

Actually there is no option to do that, if you want to uninstall packages from package.json simply do npm ls on the same directory that package.json relies and use npm uninstall <name> or npm rm <name> for the package you want to remove.

Difference between Destroy and Delete

Yes there is a major difference between the two methods Use delete_all if you want records to be deleted quickly without model callbacks being called

If you care about your models callbacks then use destroy_all

From the official docs

http://apidock.com/rails/ActiveRecord/Base/destroy_all/class

destroy_all(conditions = nil) public

Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).

Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.

How to compile LEX/YACC files on Windows?

Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:

choco install winflexbison

...which at the time of writing contains Bison 2.7 & Flex 2.6.3.

There is also winflexbison3 which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

What exactly is nullptr?

It is a keyword because the standard will specify it as such. ;-) According to the latest public draft (n2914)

2.14.7 Pointer literals [lex.nullptr]

pointer-literal:
nullptr

The pointer literal is the keyword nullptr. It is an rvalue of type std::nullptr_t.

It's useful because it does not implicitly convert to an integral value.

How to round a floating point number up to a certain decimal place?

The easiest way to do this is by using the below function, which is built in:

format()

For example:

format(1.242563,".2f")

The output would be:

1.24

Similarly:

format(9.165654,".1f")

would give:

9.2

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How to find out if you're using HTTPS without $_SERVER['HTTPS']

My solution (because the standard conditions [$_SERVER['HTTPS'] == 'on'] do not work on servers behind a load balancer) is:

$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    $isSecure = true;
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
    $isSecure = true;
}
$REQUEST_PROTOCOL = $isSecure ? 'https' : 'http';

HTTP_X_FORWARDED_PROTO: a de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (load balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Common_non-standard_request_headers

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

if you are using nvm node version manager, use this command to create a symlink:

sudo ln -s "$(which node)" /usr/bin/node
sudo ln -s "$(which npm)" /usr/bin/npm
  • The first command creates a symlink for node
  • The second command creates a symlink for npm

How can I close a dropdown on click outside?

THE MOST ELEGANT METHOD :D

There is one easiest way to do that, no need any directives for that.

"element-that-toggle-your-dropdown" should be button tag. Use any method in (blur) attribute. That's all.

<button class="element-that-toggle-your-dropdown"
               (blur)="isDropdownOpen = false"
               (click)="isDropdownOpen = !isDropdownOpen">
</button>

How to watch for form changes in Angular

UPD. The answer and demo are updated to align with latest Angular.


You can subscribe to entire form changes due to the fact that FormGroup representing a form provides valueChanges property which is an Observerable instance:

this.form.valueChanges.subscribe(data => console.log('Form changes', data));

In this case you would need to construct form manually using FormBuilder. Something like this:

export class App {
  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })

    this.form.valueChanges.subscribe(data => {
      console.log('Form changes', data)
      this.output = data
    })
  }
}

Check out valueChanges in action in this demo: http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview

How do I debug Windows services in Visual Studio?

Either that as suggested by Lasse V. Karlsen, or set up a loop in your service that will wait for a debugger to attach. The simplest is

while (!Debugger.IsAttached)
{
    Thread.Sleep(1000);
}

... continue with code

That way you can start the service and inside Visual Studio you choose "Attach to Process..." and attach to your service which then will resume normal exution.

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Centering floating divs within another div

With Flexbox you can easily horizontally (and vertically) center floated children inside a div.

So if you have simple markup like so:

<div class="wpr">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

with CSS:

.wpr
{
    width: 400px;
    height: 100px;
    background: pink;
    padding: 10px 30px;
}

.wpr span
{
    width: 50px;
    height: 50px;
    background: green;
    float: left; /* **children floated left** */
    margin: 0 5px;
}

(This is the (expected - and undesirable) RESULT)

Now add the following rules to the wrapper:

display: flex;
justify-content: center; /* align horizontal */

and the floated children get aligned center (DEMO)

Just for fun, to get vertical alignment as well just add:

align-items: center; /* align vertical */

DEMO

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How to change PHP version used by composer

Old question I know, but just to add some additional information:

  • WAMP is used only on Microsoft Windows Operating Systems.
  • Changing the version of PHP used through the left-click -> PHP -> Version menu changes the version used by Apache to server your site.
  • Changing the version of PHP used through the right-click -> Tools -> Change PHP CLI Version menu changes the version used by WAMP's PHP CLI.

Note: It is important to understand that the "PHP CLI Version" is used by WAMP's own internal PHP scripts. This "PHP CLI Version" has nothing to do with the version you wish to use for your scripts, Composer or anything else.

For your scripts to work with the version you require, you need to add it's path to the Users Environmental Path. You could add it to the Systems environmental Path but the Users Path is the recommended option.

From WAMP v3.1.2, it would display an error when it detect reference to a PHP path in the System or User Environmental Path. This was to stop confusion such as you were experiencing. Since v3.1.7 the display of this error can now be optionally displayed through a selection in the WampSettings menu.

As indicated in previous answers, adding an installed PHP path (such as "C:\wamp64\bin\php\php7.2.30") to the Users Environmental Path is the correct approach. PS: As the value of the Users Environmental Path is a string, all paths added must be separated with a semi-colon (;)

After experiencing the exact same problem (IE: Choosing which version of PHP I wanted Composer to use), I created a script which could easily and rapidly switch between PHP CLI Versions depending on what project I was working on.

The Windows batch script "WampServer-PHP-CLI-Version-Changer" can be found at https://github.com/custom-dev-tools/WampServer-PHP-CLI-Version-Changer

I hope this helps others.

Good luck.

How to list all properties of a PowerShell object

The most succinct way to do this is:

Get-WmiObject -Class win32_computersystem -Property *

Web scraping with Java

HTMLUnit can be used to do web scraping, it supports invoking pages, filling & submitting forms. I have used this in my project. It is good java library for web scraping. read here for more

how to do bitwise exclusive or of two strings in python?

Below illustrates XORing string s with m, and then again to reverse the process:

>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>

How to get arguments with flags in Bash

getopt is your friend.. a simple example:

function f () {
TEMP=`getopt --long -o "u:h:" "$@"`
eval set -- "$TEMP"
while true ; do
    case "$1" in
        -u )
            user=$2
            shift 2
        ;;
        -h )
            host=$2
            shift 2
        ;;
        *)
            break
        ;;
    esac 
done;

echo "user = $user, host = $host"
}

f -u myself -h some_host

There should be various examples in your /usr/bin directory.

How do I format a string using a dictionary in python-3.x?

Is this good for you?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

How to handle errors with boto3?

In case you have to deal with the arguably unfriendly logs client (CloudWatch Logs put-log-events), this is what I had to do to properly catch Boto3 client exceptions:

try:
    ### Boto3 client code here...

except boto_exceptions.ClientError as error:
    Log.warning("Catched client error code %s",
                error.response['Error']['Code'])

    if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
                                           "InvalidSequenceTokenException"]:
        Log.debug(
            "Fetching sequence_token from boto error response['Error']['Message'] %s",
            error.response["Error"]["Message"])
        # NOTE: apparently there's no sequenceToken attribute in the response so we have
        # to parse response["Error"]["Message"] string
        sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
        Log.debug("Setting sequence_token to %s", sequence_token)

This works both at first attempt (with empty LogStream) and subsequent ones.

Why is Ant giving me a Unsupported major.minor version error

The runtime jre was set to jre 6 instead of jre 7 in the build configuration window.