Programs & Examples On #Ttreenodes

How to parse a CSV in a Bash script?

CSV isn't quite that simple. Depending on the limits of the data you have, you might have to worry about quoted values (which may contain commas and newlines) and escaping quotes.

So if your data are restricted enough can get away with simple comma-splitting fine, shell script can do that easily. If, on the other hand, you need to parse CSV ‘properly’, bash would not be my first choice. Instead I'd look at a higher-level scripting language, for example Python with a csv.reader.

Is there any use for unique_ptr with array?

  • You need your structure to contain just a pointer for binary-compatibility reasons.
  • You need to interface with an API that returns memory allocated with new[]
  • Your firm or project has a general rule against using std::vector, for example, to prevent careless programmers from accidentally introducing copies
  • You want to prevent careless programmers from accidentally introducing copies in this instance.

There is a general rule that C++ containers are to be preferred over rolling-your-own with pointers. It is a general rule; it has exceptions. There's more; these are just examples.

Pull all images from a specified directory and then display them

In case anyone is looking for recursive.

<?php

echo scanDirectoryImages("images");

/**
 * Recursively search through directory for images and display them
 * 
 * @param  array  $exts
 * @param  string $directory
 * @return string
 */
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
    if (substr($directory, -1) == '/') {
        $directory = substr($directory, 0, -1);
    }
    $html = '';
    if (
        is_readable($directory)
        && (file_exists($directory) || is_dir($directory))
    ) {
        $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;
                if (is_readable($path)) {
                    if (is_dir($path)) {
                        return scanDirectoryImages($path, $exts);
                    }
                    if (
                        is_file($path)
                        && in_array(end(explode('.', end(explode('/', $path)))), $exts)
                    ) {
                        $html .= '<a href="' . $path . '"><img src="' . $path
                            . '" style="max-height:100px;max-width:100px" /></a>';
                    }
                }
            }
        }
        closedir($directoryList);
    }
    return $html;
}

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

How to get the top position of an element?

var top = event.target.offsetTop + 'px';

Parent element top position like we are adding elemnt inside div

var rect = event.target.offsetParent;
         rect.offsetTop;

Ansible: deploy on multiple hosts in the same time

In my case I needed the configuration stage to be blocking as a whole, but execute each role in parallel. I've tackled this issue using the following code:

echo webserver loadbalancer database | tr ' ' '\n' \
| xargs -I % -P 3 bash -c 'ansible-playbook $1.yml' -- %

the -P 3 argument in xargs makes sure that all the commands are ran in parallel, each command executes the respective playbook and the command as a whole blocks until all parts are finished.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

For me the solution was to set the version of the maven compiler plugin to 3.8.0 and specify the release (9 for in your case, 11 in mine)

    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.0</version>
      <configuration>
        <release>11</release>
      </configuration>
    </plugin>

Should I use 'border: none' or 'border: 0'?

As others have said both are valid and will do the trick. I'm not 100% convinced that they are identical though. If you have some style cascading going on then they could in theory produce different results since they are effectively overriding different values.

For example. If you set "border: none;" and then later on have two different styles that override the border width and style then one will do something and the other will not.

In the following example on both IE and firefox the first two test divs come out with no border. The second two however are different with the first div in the second block being plain and the second div in the second block having a medium width dashed border.

So though they are both valid you may need to keep an eye on your styles if they do much cascading and such like I think.

<html>
<head>
<style>
div {border: 1px solid black; margin: 1em;}
.zerotest div {border: 0;}
.nonetest div {border: none;}

div.setwidth {border-width: 3px;}
div.setstyle {border-style: dashed;}

</style>
</head>
<body>

<div class="zerotest">
<div class="setwidth">
"Border: 0" and "border-width: 3px"
</div>
<div class="setstyle">
"Border: 0" and "border-style: dashed"
</div>
</div>

<div class="nonetest">
<div class="setwidth">
"Border: none" and "border-width: 3px"
</div>
<div class="setstyle">
"Border: none" and "border-style: dashed"
</div>
</div>

</body>
</html>

How to set the custom border color of UIView programmatically?

Swift 5*

I, always use view extension to make view corners round, set border color and width and it has been the most convenient way for me. just copy and paste this code and controlle these properties in attribute inspector.

extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.borderColor = color.cgColor
            } else {
                layer.borderColor = nil
            }
        }
    }
}

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

C library function to perform sort

try qsort in stdlib.h.

How to extract the year from a Python datetime object?

It's in fact almost the same in Python.. :-)

import datetime
year = datetime.date.today().year

Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:

import datetime
year = datetime.datetime.today().year

(Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).

One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.

Why maven? What are the benefits?

Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

How to split a string and assign it to variables

**In this function you can able to split the function by golang using array of strings**

func SplitCmdArguments(args []string) map[string]string {
    m := make(map[string]string)
    for _, v := range args {
        strs := strings.Split(v, "=")
        if len(strs) == 2 {
            m[strs[0]] = strs[1]
        } else {
            log.Println("not proper arguments", strs)
        }
    }
    return m
}

Java replace all square brackets in a string

String str, str1;
Scanner sc = new Scanner(System.in);

System.out.print("Enter a String : ");
str = sc.nextLine();


str1 = str.replaceAll("[aeiouAEIOU]", "");



System.out.print(str1);

How to use vertical align in bootstrap

You mean you want 1b and 1b to be side by side?

 <div class="col-lg-6 col-md-6 col-12 child1">
      <div class="col-6 child1a">Child content 1a</div>
      <div class="col-6 child1b">Child content 1b</div>
 </div>

Best GUI designer for eclipse?

Old question, but have you checked out JFormDesigner?

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

offsetting an html anchor to adjust for fixed header

Solutions with changing position property are not always possible (it can destroy layout) therefore I suggest this:

HTML:

<a id="top">Anchor</a>

CSS:

#top {
    margin-top: -250px;
    padding-top: 250px;
}

Use this:

<a id="top">&nbsp;</a>

to minimize overlapping, and set font-size to 1px. Empty anchor will not work in some browsers.

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

Populate XDocument from String

How about this...?

TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);

This was taken from the MSDN docs for XDocument.Load, found here...

http://msdn.microsoft.com/en-us/library/bb299692.aspx

How do you get the current project directory from C# code when creating a custom MSBuild task?

Try this, its simple

HttpContext.Current.Server.MapPath("~/FolderName/");

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

AngularJS. How to call controller function from outside of controller component

It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.

But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.

Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)

What is a serialVersionUID and why should I use it?

To tell the long story short this field is used to check if serialized data can be deserialized correctly. Serialization and deserialization are often made by different copies of program - for example server converts object to string and client converts received string to object. This field tells that both operates with same idea about what this object is. This field helps when:

  • you have many different copies of your program in different places (like 1 server and 100 clients). If you will change your object, alter your version number and forget to update one this clients, it will know that he is not capable of deserialization

  • you have stored your data in some file and later on you try to open it with updated version of your program with modified object - you will know that this file is not compatible if you keep your version right

When is it important?

Most obvious - if you add some fields to your object, older versions will not be able to use them because they do not have these fields in their object structure.

Less obvious - When you deserialize object, fields that where not present in string will be kept as NULL. If you have removed field from your object, older versions will keep this field as allways-NULL that can lead to misbehavior if older versions rely on data in this field (anyway you have created it for something, not just for fun :-) )

Least obvious - Sometimes you change the idea you put in some field's meaning. For example when you are 12 years old you mean "bicycle" under "bike", but when you are 18 you mean "motorcycle" - if your friends will invite you to "bike ride across city" and you will be the only one who came on bicycle, you will undestand how important it is to keep same meaning across fields :-)

Extract filename and extension in Bash

You can also use a for loop and tr to extract the filename from the path...

for x in `echo $path | tr "/" " "`; do filename=$x; done

The tr replaces all "/" delimiters in path with spaces so making a list of strings, and the for loop scans through them leaving the last one in the filename variable.

Remove ListView items in Android

Remove it from the adapter and then notify the arrayadapter that data set has changed.

m_adapter.remove(o);
m_adapter.notifyDataSetChanged();

Typescript sleep

With RxJS:

import { timer } from 'rxjs';

// ...

timer(your_delay_in_ms).subscribe(x => { your_action_code_here })

x is 0.

If you give a second argument period to timer, a new number will be emitted each period milliseconds (x = 0 then x = 1, x = 2, ...).

See the official doc for more details.

Call javascript from MVC controller action

If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt) So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:

void webBrowser1_DocumentCompleted(object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
    if(search != null)
    {
        search.SetAttribute("value", "Superman");
        foreach(HtmlElement ele in search.Parent.Children)
        {
            if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
            {
                ele.InvokeMember("click");
                break;
            }
        }
    }
}

So probably nowadays, that would not be the easiest solution.

The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.

Some related questions on this topic or possible duplicates:

Embedding JavaScript engine into .NET

Load a DOM and Execute javascript, server side, with .Net

Hope this helps.

Notify ObservableCollection when Item changes

I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection.

public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
    private void Handle(object sender, PropertyChangedEventArgs args)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null) {
            foreach (object t in e.NewItems) {
                ((T) t).PropertyChanged += Handle;
            }
        }
        if (e.OldItems != null) {
            foreach (object t in e.OldItems) {
                ((T) t).PropertyChanged -= Handle;
            }
        }
        base.OnCollectionChanged(e);
    }

While Items are added or removed the class forwards the items PropertyChanged event to the collections PropertyChanged event.

usage:

public abstract class ParameterBase : INotifyPropertyChanged
{
    protected readonly CultureInfo Ci = new CultureInfo("en-US");
    private string _value;

    public string Value {
        get { return _value; }
        set {
            if (value == _value) return;
            _value = value;
            OnPropertyChanged();
        }
    }
}

public class AItem {
    public NotifyObservableCollection<ParameterBase> Parameters {
        get { return _parameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_parameters != null) _parameters.CollectionChanged -= cceh;
            _parameters = value;
            //needed for Binding to AItem at xaml directly
            _parameters.CollectionChanged += cceh; 
        }
    }

    public NotifyObservableCollection<ParameterBase> DefaultParameters {
        get { return _defaultParameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
            _defaultParameters = value;
            //needed for Binding to AItem at xaml directly
            _defaultParameters.CollectionChanged += cceh;
        }
    }


public class MyViewModel {
    public NotifyObservableCollection<AItem> DataItems { get; set; }
}

If now a property of an item in DataItems changes, the following xaml will get a notification, though it binds to Parameters[0] or to the item itself except to the changing property Value of the item (Converters at Triggers are called reliable on every change).

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="Background" Value="Aqua" />
                    <Style.Triggers>
                        <DataTrigger Value="False">
                            <!-- Bind to Items with changing properties -->
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource ParameterCompareConverter}">
                                    <Binding Path="DefaultParameters[0]" />
                                    <Binding Path="Parameters[0]" />
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <Setter Property="Background" Value="DeepPink" />
                        </DataTrigger>
                        <!-- Binds to AItem directly -->
                        <DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
                            <Setter Property="FontWeight" Value="ExtraBold" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>

Switch statement equivalent in Windows batch file

It might be a bit late, but this does it:

set "case1=operation1"
set "case2=operation2"
set "case3=operation3"

setlocal EnableDelayedExpansion
!%switch%!
endlocal

%switch% gets replaced before line execution. Serious downsides:

  • You override the case variables
  • It needs DelayedExpansion

Might eventually be usefull in some cases.

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar problem but it had to do with the structure and class of the object. I would check how dih_y2$MemberID is formatted.

jQuery UI Slider (setting programmatically)

For me this perfectly triggers slide event on UI Slider :

hs=$('#height_slider').slider();
hs.slider('option', 'value',h);
hs.slider('option','slide')
       .call(hs,null,{ handle: $('.ui-slider-handle', hs), value: h });

Don't forget to set value by hs.slider('option', 'value',h); before the trigger. Else slider handler will not be in sync with value.

One thing to note here is that h is index/position (not value) in case you are using html select.

invalid conversion from 'const char*' to 'char*'

string::c.str() returns a string of type const char * as seen here

A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

While the above may work, it is undefined behaviour, and unsafe.

Here's a nicer solution using templates:

char * my_argument = const_cast<char*> ( ...c_str() );

Http Get using Android HttpURLConnection

Here is a complete AsyncTask class

public class GetMethodDemo extends AsyncTask<String , Void ,String> {
    String server_response;

    @Override
    protected String doInBackground(String... strings) {

        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            int responseCode = urlConnection.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

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

        Log.e("Response", "" + server_response);


    }
}

// Converting InputStream to String

private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

To Call this AsyncTask class

new GetMethodDemo().execute("your web-service url");

JSON and XML comparison

Before answering when to use which one, a little background:

edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.

JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.

In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:

myJSON = {"age" : 12,
          "name" : "Danielle"}

The parser doesn't need to be intelligent enough to realise that 12 represents a number, (and Danielle is a string like any other). So in javascript we can do:

anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False

In XML we'd have to do something like the following:

<person>
    <age>12</age>
    <name>Danielle</name>
</person>

(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:

myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True

Actually, a good parser might well type the age for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name. It might be more intuitive to form the XML like this:

<person name="Danielle" age="12" />

But we'd still have to do map lookups to access our data:

myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");

EDIT: Original:

In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).

This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.

If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.

As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.

Best practices for circular shift (rotate) operations in C++

See also an earlier version of this answer on another rotate question with some more details about what asm gcc/clang produce for x86.

The most compiler-friendly way to express a rotate in C and C++ that avoids any Undefined Behaviour seems to be John Regehr's implementation. I've adapted it to rotate by the width of the type (using fixed-width types like uint32_t).

#include <stdint.h>   // for uint32_t
#include <limits.h>   // for CHAR_BIT
// #define NDEBUG
#include <assert.h>

static inline uint32_t rotl32 (uint32_t n, unsigned int c)
{
  const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);  // assumes width is a power of 2.

  // assert ( (c<=mask) &&"rotate by type width or more");
  c &= mask;
  return (n<<c) | (n>>( (-c)&mask ));
}

static inline uint32_t rotr32 (uint32_t n, unsigned int c)
{
  const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);

  // assert ( (c<=mask) &&"rotate by type width or more");
  c &= mask;
  return (n>>c) | (n<<( (-c)&mask ));
}

Works for any unsigned integer type, not just uint32_t, so you could make versions for other sizes.

See also a C++11 template version with lots of safety checks (including a static_assert that the type width is a power of 2), which isn't the case on some 24-bit DSPs or 36-bit mainframes, for example.

I'd recommend only using the template as a back-end for wrappers with names that include the rotate width explicitly. Integer-promotion rules mean that rotl_template(u16 & 0x11UL, 7) would do a 32 or 64-bit rotate, not 16 (depending on the width of unsigned long). Even uint16_t & uint16_t is promoted to signed int by C++'s integer-promotion rules, except on platforms where int is no wider than uint16_t.


On x86, this version inlines to a single rol r32, cl (or rol r32, imm8) with compilers that grok it, because the compiler knows that x86 rotate and shift instructions mask the shift-count the same way the C source does.

Compiler support for this UB-avoiding idiom on x86, for uint32_t x and unsigned int n for variable-count shifts:

  • clang: recognized for variable-count rotates since clang3.5, multiple shifts+or insns before that.
  • gcc: recognized for variable-count rotates since gcc4.9, multiple shifts+or insns before that. gcc5 and later optimize away the branch and mask in the wikipedia version, too, using just a ror or rol instruction for variable counts.
  • icc: supported for variable-count rotates since ICC13 or earlier. Constant-count rotates use shld edi,edi,7 which is slower and takes more bytes than rol edi,7 on some CPUs (especially AMD, but also some Intel), when BMI2 isn't available for rorx eax,edi,25 to save a MOV.
  • MSVC: x86-64 CL19: Only recognized for constant-count rotates. (The wikipedia idiom is recognized, but the branch and AND aren't optimized away). Use the _rotl / _rotr intrinsics from <intrin.h> on x86 (including x86-64).

gcc for ARM uses an and r1, r1, #31 for variable-count rotates, but still does the actual rotate with a single instruction: ror r0, r0, r1. So gcc doesn't realize that rotate-counts are inherently modular. As the ARM docs say, "ROR with shift length, n, more than 32 is the same as ROR with shift length n-32". I think gcc gets confused here because left/right shifts on ARM saturate the count, so a shift by 32 or more will clear the register. (Unlike x86, where shifts mask the count the same as rotates). It probably decides it needs an AND instruction before recognizing the rotate idiom, because of how non-circular shifts work on that target.

Current x86 compilers still use an extra instruction to mask a variable count for 8 and 16-bit rotates, probably for the same reason they don't avoid the AND on ARM. This is a missed optimization, because performance doesn't depend on the rotate count on any x86-64 CPU. (Masking of counts was introduced with 286 for performance reasons because it handled shifts iteratively, not with constant-latency like modern CPUs.)

BTW, prefer rotate-right for variable-count rotates, to avoid making the compiler do 32-n to implement a left rotate on architectures like ARM and MIPS that only provide a rotate-right. (This optimizes away with compile-time-constant counts.)

Fun fact: ARM doesn't really have dedicated shift/rotate instructions, it's just MOV with the source operand going through the barrel-shifter in ROR mode: mov r0, r0, ror r1. So a rotate can fold into a register-source operand for an EOR instruction or something.


Make sure you use unsigned types for n and the return value, or else it won't be a rotate. (gcc for x86 targets does arithmetic right shifts, shifting in copies of the sign-bit rather than zeroes, leading to a problem when you OR the two shifted values together. Right-shifts of negative signed integers is implementation-defined behaviour in C.)

Also, make sure the shift count is an unsigned type, because (-n)&31 with a signed type could be one's complement or sign/magnitude, and not the same as the modular 2^n you get with unsigned or two's complement. (See comments on Regehr's blog post). unsigned int does well on every compiler I've looked at, for every width of x. Some other types actually defeat the idiom-recognition for some compilers, so don't just use the same type as x.


Some compilers provide intrinsics for rotates, which is far better than inline-asm if the portable version doesn't generate good code on the compiler you're targeting. There aren't cross-platform intrinsics for any compilers that I know of. These are some of the x86 options:

  • Intel documents that <immintrin.h> provides _rotl and _rotl64 intrinsics, and same for right shift. MSVC requires <intrin.h>, while gcc require <x86intrin.h>. An #ifdef takes care of gcc vs. icc, but clang doesn't seem to provide them anywhere, except in MSVC compatibility mode with -fms-extensions -fms-compatibility -fms-compatibility-version=17.00. And the asm it emits for them sucks (extra masking and a CMOV).
  • MSVC: _rotr8 and _rotr16.
  • gcc and icc (not clang): <x86intrin.h> also provides __rolb/__rorb for 8-bit rotate left/right, __rolw/__rorw (16-bit), __rold/__rord (32-bit), __rolq/__rorq (64-bit, only defined for 64-bit targets). For narrow rotates, the implementation uses __builtin_ia32_rolhi or ...qi, but the 32 and 64-bit rotates are defined using shift/or (with no protection against UB, because the code in ia32intrin.h only has to work on gcc for x86). GNU C appears not to have any cross-platform __builtin_rotate functions the way it does for __builtin_popcount (which expands to whatever's optimal on the target platform, even if it's not a single instruction). Most of the time you get good code from idiom-recognition.

// For real use, probably use a rotate intrinsic for MSVC, or this idiom for other compilers.  This pattern of #ifdefs may be helpful
#if defined(__x86_64__) || defined(__i386__)

#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>  // Not just <immintrin.h> for compilers other than icc
#endif

uint32_t rotl32_x86_intrinsic(rotwidth_t x, unsigned n) {
  //return __builtin_ia32_rorhi(x, 7);  // 16-bit rotate, GNU C
  return _rotl(x, n);  // gcc, icc, msvc.  Intel-defined.
  //return __rold(x, n);  // gcc, icc.
  // can't find anything for clang
}
#endif

Presumably some non-x86 compilers have intrinsics, too, but let's not expand this community-wiki answer to include them all. (Maybe do that in the existing answer about intrinsics).


(The old version of this answer suggested MSVC-specific inline asm (which only works for 32bit x86 code), or http://www.devx.com/tips/Tip/14043 for a C version. The comments are replying to that.)

Inline asm defeats many optimizations, especially MSVC-style because it forces inputs to be stored/reloaded. A carefully-written GNU C inline-asm rotate would allow the count to be an immediate operand for compile-time-constant shift counts, but it still couldn't optimize away entirely if the value to be shifted is also a compile-time constant after inlining. https://gcc.gnu.org/wiki/DontUseInlineAsm.

How do I create a copy of an object in PHP?

This code help clone methods

class Foo{

    private $run=10;
    public $foo=array(2,array(2,8));
    public function hoo(){return 5;}


    public function __clone(){

        $this->boo=function(){$this->hoo();};

    }
}
$obj=new Foo;

$news=  clone $obj;
var_dump($news->hoo());

Creating an Instance of a Class with a variable in Python

If you just want to pass a class to a function, so that this function can create new instances of that class, just treat the class like any other value you would give as a parameter:

def printinstance(someclass):
  print someclass()

Result:

>>> printinstance(list)
[]
>>> printinstance(dict)
{}

AngularJs - ng-model in a SELECT

Select's default value should be one of its value in the list. In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.

View this plunker for any references:

http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

Static variables in JavaScript

Try this one:

If we define a property and override its getters and setters to use the Function Object property then in theory you can have an static variable in javascript

for example:

_x000D_
_x000D_
function Animal() {_x000D_
    if (isNaN(this.totalAnimalCount)) {_x000D_
        this.totalAnimalCount = 0;_x000D_
    }_x000D_
    this.totalAnimalCount++;_x000D_
};_x000D_
Object.defineProperty(Animal.prototype, 'totalAnimalCount', {_x000D_
    get: function() {_x000D_
        return Animal['totalAnimalCount'];_x000D_
    },_x000D_
   set: function(val) {_x000D_
       Animal['totalAnimalCount'] = val;_x000D_
   }_x000D_
});_x000D_
var cat = new Animal(); _x000D_
console.log(cat.totalAnimalCount); //Will produce 1_x000D_
var dog = new Animal();_x000D_
console.log(cat.totalAnimalCount); //Will produce 2 and so on.
_x000D_
_x000D_
_x000D_

Check if key exists in JSON object using jQuery

No need of JQuery simply you can do

if(yourObject['email']){
 // what if this property exists.
}

as with any value for email will return you true, if there is no such property or that property value is null or undefined will result to false

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

If any intent was previously working fine when the app is in the background, it won't be the case any more from Android 8 and above. Only referring to intent which has to do some processing when app is in the background.

The below steps have to be followed:

  1. Above mentioned intent should be using JobIntentService instead of IntentService.
  2. The class which extends JobIntentService should implement the - onHandleWork(@NonNull Intent intent) method and should have below the method, which will invoke the onHandleWork method:

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, xyz.class, 123, work);
    }
    
  3. Call enqueueWork(Context, intent) from the class where your intent is defined.

    Sample code:

    Public class A {
    ...
    ...
        Intent intent = new Intent(Context, B.class);
        //startService(intent); 
        B.enqueueWork(Context, intent);
    }
    

The below class was previously extending the Service class

Public Class B extends JobIntentService{
...

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, B.class, JobId, work);
    }

    protected void onHandleWork(@NonNull Intent intent) {
        ...
        ...
    }
}
  1. com.android.support:support-compat is needed for JobIntentService - I use 26.1.0 V.

  2. Most important is to ensure the Firebase libraries version is on at least 10.2.1, I had issues with 10.2.0 - if you have any!

  3. Your manifest should have the below permission for the Service class:

    service android:name=".B"
    android:exported="false"
    android:permission="android.permission.BIND_JOB_SERVICE"
    

Hope this helps.

How to disable JavaScript in Chrome Developer Tools?

This is the latest setting for the windows

Settings > Advanced > Privacy and security > Site Settings > Javascript > Blocked then get switch on and off

Get string character by index - Java

It is as simple as:

String charIs = string.charAt(index) + "";

Static vs class functions/variables in Swift classes?

I tried mipadi's answer and comments on playground. And thought of sharing it. Here you go. I think mipadi's answer should be mark as accepted.

class A{
    class func classFunction(){
    }
    static func staticFunction(){
    }
    class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
}

class B: A {
    override class func classFunction(){

    }

    //Compile Error. Class method overrides a 'final' class method
    override static func staticFunction(){

    }

    //Lets avoid the function called 'classFunctionToBeMakeFinalInImmediateSubclass' being overriden by subclasses

    /* First way of doing it
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
    */

    // Second way of doing the same
    override final class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }

    //To use static or final class is choice of style.
    //As mipadi suggests I would use. static at super class. and final class to cut off further overrides by a subclass
}

class C: B{
    //Compile Error. Class method overrides a 'final' class method
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){

    }
}

How to stop default link click behavior with jQuery

This code strip all event listeners

var old_element=document.getElementsByClassName(".update-cart");    
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);  

CSS: On hover show and hide different div's at the same time?

Have you tried somethig like this?

.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}

<div class="showhim">HOVER ME
  <div class="showme">hai</div>
  <div class="hideme">bye</div>
</div>

I dont know any reason why it shouldn't be possible.

How to create an infinite loop in Windows batch file?

Here is an example of using the loop:

echo off
cls

:begin

set /P M=Input text to encode md5, press ENTER to exit: 
if %M%==%M1% goto end

echo.|set /p ="%M%" | openssl md5

set M1=%M%
Goto begin

This is the simple batch i use when i need to encrypt any message into md5 hash on Windows(openssl required), and the program would loyally repeat itself except given Ctrl+C or empty input.

How should I multiple insert multiple records?

Following up @Tim Mahy - There's two possible ways to feed SqlBulkCopy: a DataReader or via DataTable. Here the code for DataTable:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
foreach (Entry entry in entries)
    dt.Rows.Add(new string[] { entry.Id, entry.Name });

using (SqlBulkCopy bc = new SqlBulkCopy(connection))
{   // the following 3 lines might not be neccessary
    bc.DestinationTableName = "Entries";
    bc.ColumnMappings.Add("Id", "Id");
    bc.ColumnMappings.Add("Name", "Name");

    bc.WriteToServer(dt);
}

Cross-reference (named anchor) in markdown

There's no readily available syntax to do this in the original Markdown syntax, but Markdown Extra provides a means to at least assign IDs to headers — which you can then link to easily. Note also that you can use regular HTML in both Markdown and Markdown Extra, and that the name attribute has been superseded by the id attribute in more recent versions of HTML.

c# .net change label text

When I had this problem I could see only a part of my text and this is the solution for that:

Be sure to set the AutoSize property to true.

output.AutoSize = true;

Comparing strings by their alphabetical order

As others suggested, you can use String.compareTo(String).

But if you are sorting a list of Strings and you need a Comparator, you don't have to implement it, you can use Comparator.naturalOrder() or Comparator.reverseOrder().

Adding class to element using Angular JS

AngularJS has some methods called JQlite so we can use it. see link

Select the element in DOM is

angular.element( document.querySelector( '#div1' ) );

add the class like .addClass('alpha');

So finally

var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');

Compare one String with multiple values in one expression

!string.matches("a|b|c|d") 

works fine for me.

How to import other Python files?

importlib was added to Python 3 to programmatically import a module.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

In python 2.x:

  • Just import file without the .py extension
  • A folder can be marked as a package, by adding an empty __init__.py file
  • You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

Type help(__import__) for more details.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Google's (bad) approach, from HN thread. Store RLE-style counts.

Your initial data structure is '99999999:0' (all zeros, haven't seen any numbers) and then lets say you see the number 3,866,344 so your data structure becomes '3866343:0,1:1,96133654:0' as you can see the numbers will always alternate between number of zero bits and number of '1' bits so you can just assume the odd numbers represent 0 bits and the even numbers 1 bits. This becomes (3866343,1,96133654)

Their problem doesn't seem to cover duplicates, but let's say they use "0:1" for duplicates.

Big problem #1: insertions for 1M integers would take ages.

Big problem #2: like all plain delta encoding solutions, some distributions can't be covered this way. For example, 1m integers with distances 0:99 (e.g. +99 each one). Now think the same but with random distance in the range of 0:99. (Note: 99999999/1000000 = 99.99)

Google's approach is both unworthy (slow) and incorrect. But to their defense, their problem might have been slightly different.

How to convert Set to Array?

Perhaps to late to the party, but you could just do the following:

const set = new Set(['a', 'b']);
const values = set.values();
const array = Array.from(values);

This should work without problems in browsers that have support for ES6 or if you have a shim that correctly polyfills the above functionality.

Edit: Today you can just use what @c69 suggests:

const set = new Set(['a', 'b']);
const array = [...set]; // or Array.from(set)

How to export and import a .sql file from command line with options?

Type the following command to import sql data file:

$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql

In this example, import 'data.sql' file into 'blog' database using vivek as username:

$ mysql -u vivek -p -h localhost blog < data.sql

If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:

$ mysql -u username -p -h 202.54.1.10 databasename < data.sql

To export a database, use the following:

mysqldump -u username -p databasename > filename.sql

Note the < and > symbols in each case.

subtract time from date - moment js

I might be missing something in your question here... but from what I can gather, by using the subtract method this should be what you're looking to do:

var timeStr = "00:03:15";
    timeStr = timeStr.split(':');

var h = timeStr[1],
    m = timeStr[2];

var newTime = moment("01:20:00 06-26-2014")
    .subtract({'hours': h, 'minutes': m})
    .format('hh:mm');

var str = h + " hours and " + m + " minutes earlier: " + newTime;

console.log(str); // 3 hours and 15 minutes earlier: 10:05

_x000D_
_x000D_
$(document).ready(function(){    _x000D_
     var timeStr = "00:03:15";_x000D_
        timeStr = timeStr.split(':');_x000D_
_x000D_
    var h = timeStr[1],_x000D_
        m = timeStr[2];_x000D_
_x000D_
    var newTime = moment("01:20:00 06-26-2014")_x000D_
        .subtract({'hours': h, 'minutes': m})_x000D_
        .format('hh:mm');_x000D_
_x000D_
    var str = h + " hours and " + m + " minutes earlier: " + newTime;_x000D_
_x000D_
    $('#new-time').html(str);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="new-time"></p>
_x000D_
_x000D_
_x000D_

How to set up devices for VS Code for a Flutter emulator

For me, when I was running "flutter doctor" command from Ubuntu Command line - It showed me below error.

[?] Android toolchain - develop for Android devices ? Unable to locate Android SDK.

From this error, it is obvious that "flutter doctor" was not able to find the "android sdk" and the reason for that was my android sdk was downloaded in a custom location on my Ubuntu machine.

So we must need to tell "flutter doctor" about this custom android location, using below command,

flutter config --android-sdk /home/myhome/Downloads/softwares/android-sdk/

Need to replace /home/myhome/Downloads/softwares/android-sdk/ with path to your custom location/place where android sdk is available.

Once this is done, and re-run "flutter doctor" and now it has detected the android sdk location and hence I could run avd/emulator by typing "flutter run"

Removing carriage return and new-line from the end of a string in c#

For us VBers:

TrimEnd(New Char() {ControlChars.Cr, ControlChars.Lf})

django templates: include and extends

More info about why it wasn't working for me in case it helps future people:

The reason why it wasn't working is that {% include %} in django doesn't like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters and then it included successfully.

Regex to get the words after matching string

The following should work for you:

[\n\r].*Object Name:\s*([^\n\r]*)

Working example

Your desired match will be in capture group 1.


[\n\r][ \t]*Object Name:[ \t]*([^\n\r]*)

Would be similar but not allow for things such as " blah Object Name: blah" and also make sure that not to capture the next line if there is no actual content after "Object Name:"

How to set opacity to the background color of a div?

CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.

How do I get the height and width of the Android Navigation Bar programmatically?

In case of Samsung S8 none of the above provided methods were giving proper height of navigation bar so I used the KeyboardHeightProvider keyboard height provider android. And it gave me height in negative values and for my layout positioning I adjusted that value in calculations.

Here is KeyboardHeightProvider.java :

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager.LayoutParams;
import android.widget.PopupWindow;


/**
 * The keyboard height provider, this class uses a PopupWindow
 * to calculate the window height when the floating keyboard is opened and closed. 
 */
public class KeyboardHeightProvider extends PopupWindow {

    /** The tag for logging purposes */
    private final static String TAG = "sample_KeyboardHeightProvider";

    /** The keyboard height observer */
    private KeyboardHeightObserver observer;

    /** The cached landscape height of the keyboard */
    private int keyboardLandscapeHeight;

    /** The cached portrait height of the keyboard */
    private int keyboardPortraitHeight;

    /** The view that is used to calculate the keyboard height */
    private View popupView;

    /** The parent view */
    private View parentView;

    /** The root activity that uses this KeyboardHeightProvider */
    private Activity activity;

    /** 
     * Construct a new KeyboardHeightProvider
     * 
     * @param activity The parent activity
     */
    public KeyboardHeightProvider(Activity activity) {
        super(activity);
        this.activity = activity;

        LayoutInflater inflator = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        this.popupView = inflator.inflate(R.layout.popupwindow, null, false);
        setContentView(popupView);

        setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_RESIZE | LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

        parentView = activity.findViewById(android.R.id.content);

        setWidth(0);
        setHeight(LayoutParams.MATCH_PARENT);

        popupView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    if (popupView != null) {
                        handleOnGlobalLayout();
                    }
                }
            });
    }

    /**
     * Start the KeyboardHeightProvider, this must be called after the onResume of the Activity.
     * PopupWindows are not allowed to be registered before the onResume has finished
     * of the Activity.
     */
    public void start() {

        if (!isShowing() && parentView.getWindowToken() != null) {
            setBackgroundDrawable(new ColorDrawable(0));
            showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    /**
     * Close the keyboard height provider, 
     * this provider will not be used anymore.
     */
    public void close() {
        this.observer = null;
        dismiss();
    }

    /** 
     * Set the keyboard height observer to this provider. The 
     * observer will be notified when the keyboard height has changed. 
     * For example when the keyboard is opened or closed.
     * 
     * @param observer The observer to be added to this provider.
     */
    public void setKeyboardHeightObserver(KeyboardHeightObserver observer) {
        this.observer = observer;
    }

    /**
     * Get the screen orientation
     *
     * @return the screen orientation
     */
    private int getScreenOrientation() {
        return activity.getResources().getConfiguration().orientation;
    }

    /**
     * Popup window itself is as big as the window of the Activity. 
     * The keyboard can then be calculated by extracting the popup view bottom 
     * from the activity window height. 
     */
    private void handleOnGlobalLayout() {

        Point screenSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(screenSize);

        Rect rect = new Rect();
        popupView.getWindowVisibleDisplayFrame(rect);

        // REMIND, you may like to change this using the fullscreen size of the phone
        // and also using the status bar and navigation bar heights of the phone to calculate
        // the keyboard height. But this worked fine on a Nexus.
        int orientation = getScreenOrientation();
        int keyboardHeight = screenSize.y - rect.bottom;

        if (keyboardHeight == 0) {
            notifyKeyboardHeightChanged(0, orientation);
        }
        else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.keyboardPortraitHeight = keyboardHeight; 
            notifyKeyboardHeightChanged(keyboardPortraitHeight, orientation);
        } 
        else {
            this.keyboardLandscapeHeight = keyboardHeight; 
            notifyKeyboardHeightChanged(keyboardLandscapeHeight, orientation);
        }
    }

    /**
     *
     */
    private void notifyKeyboardHeightChanged(int height, int orientation) {
        if (observer != null) {
            observer.onKeyboardHeightChanged(height, orientation);
        }
    }

    public interface KeyboardHeightObserver {
        void onKeyboardHeightChanged(int height, int orientation);
    }
}

popupwindow.xml :

<?xml version="1.0" encoding="utf-8"?>
<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popuplayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="horizontal"/>

Usage in MainActivity

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

/**
 * Created by nileshdeokar on 22/02/2018.
 */
class MainActivity : AppCompatActivity() , KeyboardHeightProvider.KeyboardHeightObserver  {

    private lateinit var keyboardHeightProvider : KeyboardHeightProvider


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        keyboardHeightProvider = KeyboardHeightProvider(this)
        parentActivityView.post { keyboardHeightProvider?.start() }
    }

    override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
        // In case of 18:9 - e.g. Samsung S8
        // here you get the height of the navigation bar as negative value when keyboard is closed.
        // and some positive integer when keyboard is opened.
    }

    public override fun onPause() {
        super.onPause()
        keyboardHeightProvider?.setKeyboardHeightObserver(null)
    }

    public override fun onResume() {
        super.onResume()
        keyboardHeightProvider?.setKeyboardHeightObserver(this)
    }

    public override fun onDestroy() {
        super.onDestroy()
        keyboardHeightProvider?.close()
    }
}

For any further help you can have a look at advanced usage of this here.

IntelliJ shortcut to show a popup of methods in a class that can be searched

I prefer to use the Structure view. To open it, use the menu: View/Tools Window/Structure. The hotkey on Windows is Alt+7

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

it worked for me by neutralizing the '\' by f = open('F:\\file.csv')

Print an integer in binary format in Java

Old school:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

How to hide Bootstrap modal with javascript?

(Referring to Bootstrap 3), To hide the modal use: $('#modal').modal('hide'). But the reason the backdrop hung around (for me) was because I was destroying the DOM for the modal before 'hide' finished.

To resolve this, I chained the hidden event with the DOM removal. In my case: this.render()

var $modal = $('#modal');

//when hidden
$modal.on('hidden.bs.modal', function(e) { 
  return this.render(); //DOM destroyer
});

$modal.modal('hide'); //start hiding

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

Easily measure elapsed time

Windows only: (The Linux tag was added after I posted this answer)

You can use GetTickCount() to get the number of milliseconds that have elapsed since the system was started.

long int before = GetTickCount();

// Perform time-consuming operation

long int after = GetTickCount();

Check if an apt-get package is installed and then install it if it's not on Linux

This command is the most memorable:

dpkg --get-selections <package-name>

If it's installed it prints:

<package-name> install

Otherwise it prints

No packages found matching <package-name>.

This was tested on Ubuntu 12.04.1 (Precise Pangolin).

Best way to iterate through a Perl array

IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.

Can I store images in MySQL

You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:

  • The images can be harder to manipulate: you must first retrieve them from the database before bulk operations can be performed.
  • Except in very rare cases where the entire database is stored in RAM, MySQL databases are ultimately stored on disk. This means that your DB images are converted to blobs, inserted into a database, and then stored on disk; you can save a lot of overhead by simply storing them on disk.

Instead, consider updating your table to add an image_path field. For example:

ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)

Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.

An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.

Search for value in DataGridView in a column

Why don't you build a DataTable first then assign it to the DataGridView as DataSource:

DataTable table4DataSource=new DataTable();

table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");

...

(add your rows, manually, in a circle or via a DataReader from a database table) (assign the datasource)

dtGrdViewGrid.DataSource = table4DataSource;

and then use:

(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();

You can even put this piece of code within your textbox_textchange event and your filtered values will be showing as you write.

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/

However, if you want to see the mongo's admin web page, you could do it, with this command:

mongod --rest --httpinterface

browsing this url: http://localhost:28017/

the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require

@Autowired and static method

You can do this by following one of the solutions:

Using constructor @Autowired

This approach will construct the bean requiring some beans as constructor parameters. Within the constructor code you set the static field with the value got as parameter for constructor execution. Sample:

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

Using @PostConstruct to hand value over to static field

The idea here is to hand over a bean to a static field after bean is configured by spring.

@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

How to add border radius on table row

I think collapsing your borders is the wrong thing to do in this case. Collapsing them basically means that the border between two neighboring cells becomes shared. This means it's unclear as to which direction it should curve given a radius.

Instead, you can give a border radius to the two lefthand corners of the first TD and the two righthand corners of the last one. You can use first-child and last-child selectors as suggested by theazureshadow, but these may be poorly supported by older versions of IE. It might be easier to just define classes, such as .first-column and .last-column to serve this purpose.

Simple excel find and replace for formulas

It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way

=((E9-E8)/E8) 

became

=((R[-1]C-R[-2]C)/R[-2]C)

and

(EXP((LN(E9/E8)/14.32))-1)

became

=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)

In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

Detect page change on DataTable

I got it working using:

$('#id-of-table').on('draw.dt', function() {
    // do action here
});

Getting Hour and Minute in PHP

You can use the following solution to solve your problem:

echo date('H:i');

How to use jQuery in chrome extension?

In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.

manifest.json

{
  "name": "JQuery Light",
  "version": "1",
  "manifest_version": 2,

  "browser_action": {
    "default_icon": "icon.png"
  },

  "content_scripts": [
    {
      "matches": [
        "https://*.google.com/*"
      ],
      "js": [
        "jquery-3.3.1.min.js",
        "myscript.js"
      ]
    }
  ],

  "background": {
    "scripts": [
      "background.js"
    ]
  }

}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

myscript.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "clicked_browser_action") {
        console.log('Hello world!')
        }
    }
);

Before and After Suite execution hook in jUnit 4.x

As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding the run() method with a version that does provide hooks.

How to get Domain name from URL using jquery..?

This worked for me.

http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery

$(location).attr('host');                        www.test.com:8082
$(location).attr('hostname');                    www.test.com
$(location).attr('port');                        8082
$(location).attr('protocol');                    http:
$(location).attr('pathname');                    index.php
$(location).attr('href');                        http://www.test.com:8082/index.php#tab2
$(location).attr('hash');                       #tab2
$(location).attr('search');                     ?foo=123

Viewing PDF in Windows forms using C#

you can use System.Diagnostics.Process.Start as well as WIN32 ShellExecute function by means of interop, for opening PDF files using the default viewer:

System.Diagnostics.Process.Start("SOMEAPP.EXE","Path/SomeFile.Ext");

[System.Runtime.InteropServices.DllImport("shell32. dll")]
private static extern long ShellExecute(Int32 hWnd, string lpOperation, 
                                    string lpFile, string lpParameters, 
                                        string lpDirectory, long nShowCmd);

Another approach is to place a WebBrowser Control into your Form and then use the Navigate method for opening the PDF file:

ThewebBrowserControl.Navigate(@"c:\the_file.pdf");

Adding devices to team provisioning profile

All answers I've seen above assumed that the developer owns an iPhone. No one knows the right answer. As far as I know, you need:

  • a physical iPhone that you own
  • or UDID of someone else's iPhone. But it is a must to have an iPhone before you publish your app. Correct me if I am wrong.

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

For quick reference of anyone who wants to go to the end of line or start of line in iTerm2, the above link http://hackaddict.blogspot.com/2007/07/skip-to-next-or-previous-word-in-iterm.html notes that in iTerm2:

  • Ctrl+A, jumps to the start of the line, while
  • Ctrl+E, jumps to the end of the line.

How to change an Android app's name?

The change in Manifest file did not change the App name,

<application android:icon="@drawable/ic__logo" android:theme="@style/AppTheme" android:largeHeap="true" android:label="@string/app_name">

but changing the Label attribute in the MainLauncher did the trick for me .

[Activity(Label = "@string/app_name", MainLauncher = true, Theme = "@style/MainActivityNoActionBarTheme", ScreenOrientation = ScreenOrientation.Portrait)]

Load dimension value from res/values/dimension.xml from source code

For those who just need to save some int value in the resources, you can do the following.

integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="default_value">100</integer>
</resources> 

Code

int defaultValue = getResources().getInteger(R.integer.default_value);

Change placeholder text

For JavaScript use:

document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";

For jQuery use:

$('.select-holder')[0].placeholder = "This is my new text";

Checking letter case (Upper/Lower) within a string in Java

A loop like this one:

else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                   ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                       {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                       }
                     // end if
                } //end for
            }

Has an obvious logical flaw: You enter it if the first character is not lowercase, then test if the second character is not lower case. At that point you throw an error.

Instead, you should do something like this (not full code, just an example):

boolean hasLower = false, hasUpper = false, hasNumber = false, hasSpecial = false; // etc - all the rules
for ( ii = 0; ii < password.length(); ii++ ) {
  ch = password.charAt(ii);
  // check each rule in turn, with code like this:
  if Character.isLowerCase(ch) hasLower = true;
  if Character.isUpperCase(ch) hasUpper = true;
  // ... etc for all the tests you want to do
}

if(hasLower && hasUpper && ...) {
  // password is good
} 
else {
  // password is bad
}

Of course the code snippet you provided, besides the faulty logic, did not have code to test for the other conditions that your "help" option printed out. As was pointed out in one of the other answers, you could consider using regular expressions to help you speed up the process of finding each of these things. For example,

hasNumber  : use regex pattern "\d+" for "find at least one digit"
hasSpecial : use regex pattern "[!@#$%^&*]+" for "find at least one of these characters"

In code:

hasNumber  = password.matches(".*\\d.*");  // "a digit with anything before or after"
hasSpecial = password.matches(".*[!@#$%^&*].*");
hasNoNOT   = !password.matches(".*NOT.*");
hasNoAND   = !password.matches(".*AND.*");

It is possible to combine these things in clever ways - but especially when you are a novice regex user, it is much better to be a little bit "slow and tedious", and get code that works first time (plus you will be able to figure out what you did six months from now).

Calling a javascript function recursively

I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)

  var fn = (function() {
    var innerFn = function(counter) {
      console.log(counter);

      if(counter > 0) {
        innerFn(counter-1);
      }
    };

    return innerFn;
  })();

  console.log("running fn");
  fn(3);

  var copyFn = fn;

  console.log("running copyFn");
  copyFn(3);

  fn = function() { console.log("done"); };

  console.log("fn after reassignment");
  fn(3);

  console.log("copyFn after reassignment of fn");
  copyFn(3);

ValueError: invalid literal for int () with base 10

You've got a problem with this line:

while file_to_read != " ":

This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.

Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.

How to make a great R reproducible example

Often you need some data for an example, however, you don't want to post your exact data. To use some existing data.frame in established library, use data command to import it.

e.g.,

data(mtcars)

and then do the problem

names(mtcars)
your problem demostrated on the mtcars data set

Visual Studio 2015 installer hangs during install?

The old thread with many answers. but for me, these commands solved the problem.

regsvr32.exe /u "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"

regsvr32.exe "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
{
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    }
    temp_buf = (char *) malloc(5 * 1024);

    ....
    ....
    ....

}

Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

Delete files older than 10 days using shell script in Unix

Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time

#!/bin/bash

path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)    
filename=log_$timestamp.txt    
log=$path$filename
days=7

START_TIME=$(date +%s)

find $path -maxdepth 1 -name "*.txt"  -type f -mtime +$days  -print -delete >> $log

echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log


... code for backup ...or any other operation .... >> $log


END_TIME=$(date +%s)

ELAPSED_TIME=$(( $END_TIME - $START_TIME ))


echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $log

The code adds a few things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • type f ensures you only deletes files
  • maxdepth 1 ensures you dont enter subfolders
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time for the backup operation...

Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.

Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'

Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days

-mtime +$days  --->  -mmin  +$((60*24*$days))

Java output formatting for Strings

If you want a minimum of 4 characters, for instance,

System.out.println(String.format("%4d", 5));
// Results in "   5", minimum of 4 characters

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

UNION with WHERE clause

NOTE: While my advice was true many years ago, Oracle's optimizer has improved so that the location of the where definitely no longer matters here. However preferring UNION ALL vs UNION will always be true, and portable SQL should avoid depending on optimizations that may not be in all databases.

Short answer, you want the WHERE before the UNION and you want to use UNION ALL if at all possible. If you are using UNION ALL then check the EXPLAIN output, Oracle might be smart enough to optimize the WHERE condition if it is left after.

The reason is the following. The definition of a UNION says that if there are duplicates in the two data sets, they have to be removed. Therefore there is an implicit GROUP BY in that operation, which tends to be slow. Worse yet, Oracle's optimizer (at least as of 3 years ago, and I don't think it has changed) doesn't try to push conditions through a GROUP BY (implicit or explicit). Therefore Oracle has to construct larger data sets than necessary, group them, and only then gets to filter. Thus prefiltering wherever possible is officially a Good Idea. (This is, incidentally, why it is important to put conditions in the WHERE whenever possible instead of leaving them in a HAVING clause.)

Furthermore if you happen to know that there won't be duplicates between the two data sets, then use UNION ALL. That is like UNION in that it concatenates datasets, but it doesn't try to deduplicate data. This saves an expensive grouping operation. In my experience it is quite common to be able to take advantage of this operation.

Since UNION ALL does not have an implicit GROUP BY in it, it is possible that Oracle's optimizer knows how to push conditions through it. I don't have Oracle sitting around to test, so you will need to test that yourself.

PNG transparency issue in IE8

My scenario:

  • I had a background image that had a 24bit alpha png that was set to an anchor link.
  • The anchor was being faded in on hover using Jquery.

eg.

a.button { background-image: url(this.png; }

I found that applying the mark-up provided by Dan Tello didn't work.

However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.

eg.

a.button span { background-image: url(this.png; }

How to create localhost database using mysql?

Consider using the MySQL Installer for Windows as it installs and updates the various MySQL products on your system, including MySQL Server, MySQL Workbench, and MySQL Notifier. The Notifier monitors your MySQL instances so you'll know if MySQL is running, and it can also be used to start/stop MySQL.

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx

Correct way to write line to file?

You should use the print() function which is available since Python 2.6+

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

For Python 3 you don't need the import, since the print() function is the default.

The alternative would be to use:

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

Quoting from Python documentation regarding newlines:

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

How to manually update datatables table with new JSON data

In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).

My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).

Then I instantiate my table in the on load method

$(function () {
            //.... some code here
            table = $("#detailReportTable").DataTable();
            .... more code here
        });

and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:

function getOrderDetail() {
            table.clear();
            table.destroy();
            ...
            $.ajax({
             //.....api call here
            });
            ....
            table = $("#detailReportTable").DataTable();
   }

I hope someone finds this useful!

java.text.ParseException: Unparseable date

Update your format to:

SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

If you are getting this message from a Maven built war change the scope of the JDBC driver to provided, and put a copy of it in the lib directory. Like this:

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.18</version>
  <!-- put a copy in /usr/share/tomcat7/lib -->
  <scope>provided</scope>
</dependency>

How do I use shell variables in an awk script?

It seems that the good-old ENVIRON built-in hash is not mentioned at all. An example of its usage:

$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Python: Find a substring in a string and returning the index of the substring

There's a builtin method find on string objects.

s = "Happy Birthday"
s2 = "py"

print(s.find(s2))

Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)

find returns -1 if the string cannot be found.

adb shell su works but adb root does not

adbd has a compilation flag/option to enable root access: ALLOW_ADBD_ROOT=1.

Up to Android 9: If adbd on your device is compiled without that flag, it will always drop privileges when starting up and thus "adb root" will not help at all. I had to patch the calls to setuid(), setgid(), setgroups() and the capability drops out of the binary myself to get a permanently rooted adbd on my ebook reader.

With Android 10 this changed; when the phone/tablet is unlocked (ro.boot.verifiedbootstate == "orange"), then adb root mode is possible in any case.

Laravel password validation rule

This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:

    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }

Would output:

    [
        'The email must be a valid email address.',
        'The password must be at least 10 characters.',
        'The password format is invalid.',
    ]

(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)

How to call a method after bean initialization is complete?

To expand on the @PostConstruct suggestion in other answers, this really is the best solution, in my opinion.

  • It keeps your code decoupled from the Spring API (@PostConstruct is in javax.*)
  • It explicitly annotates your init method as something that needs to be called to initialize the bean
  • You don't need to remember to add the init-method attribute to your spring bean definition, spring will automatically call the method (assuming you register the annotation-config option somewhere else in the context, anyway).

AngularJs: Reload page

window object is made available through $window service for easier testing and mocking, you can go with something like:

$scope.reloadPage = function(){$window.location.reload();}

And :

<a ng-click="reloadPage"  class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

As a side note, i don't think $route.reload() actually reloads the page, but only the route.

HTML <input type='file'> File Selection Event

That's the way I did it with pure JS:

_x000D_
_x000D_
var files = document.getElementById('filePoster');_x000D_
var submit = document.getElementById('submitFiles');_x000D_
var warning = document.getElementById('warning');_x000D_
files.addEventListener("change", function () {_x000D_
  if (files.files.length > 10) {_x000D_
    submit.disabled = true;_x000D_
    warning.classList += "warn"_x000D_
    return;_x000D_
  }_x000D_
  submit.disabled = false;_x000D_
});
_x000D_
#warning {_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
#warning.warn {_x000D_
 color: red;_x000D_
 transform: scale(1.5);_x000D_
 transition: 1s all;_x000D_
}
_x000D_
<section id="shortcode-5" class="shortcode-5 pb-50">_x000D_
    <p id="warning">Please do not upload more than 10 images at once.</p>_x000D_
    <form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">_x000D_
        <div class="input-group">_x000D_
       <input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />_x000D_
     <button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>_x000D_
        </div>_x000D_
    </form>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to combine date from one field with time from another field - MS SQL Server

SELECT CAST(your_date_column AS date) + CAST(your_time_column AS datetime) FROM your_table

Works like a charm

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

Not OP's answer but as this was the first question that popped up for me in google, Id also like to add that users searching for this might need to reseed their table, which was the case for me

DBCC CHECKIDENT(tablename)

Set Encoding of File to UTF8 With BOM in Sublime Text 3

Into Preferences > Settings - Users
File : Preferences.sublime-settings

Write this :

"show_encoding" : true,

It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3

how to end ng serve or firebase serve

With Windows 10 / Powershell ctrl + c did not work; Powershell tried to gracefully stop the app.

Used normal cmd and had no issues stopping the ng serve with ctrl + c.

HTML <select> selected option background-color CSS style

In CSS:

SELECT OPTION:checked { background-color: red; }

Should image size be defined in the img tag height/width attributes or in CSS?

<img id="uxcMyImageId" src"myImage" width="100" height="100" />

specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.

When is layoutSubviews called?

I had a similar question, but wasn't satisfied with the answer (or any I could find on the net), so I tried it in practice and here is what I got:

  • init does not cause layoutSubviews to be called (duh)
  • addSubview: causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target
  • view setFrame intelligently calls layoutSubviews on the view having its frame set only if the size parameter of the frame is different
  • scrolling a UIScrollView causes layoutSubviews to be called on the scrollView, and its superview
  • rotating a device only calls layoutSubview on the parent view (the responding viewControllers primary view)
  • Resizing a view will call layoutSubviews on its superview

My results - http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/

Connecting to SQL Server using windows authentication

This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

Use awk to find average of a column

Try this:

ls -l  | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'

NR is an AWK builtin variable to count the no. of records

Unix - copy contents of one directory to another

Quite simple, with a * wildcard.

cp -r Folder1/* Folder2/

But according to your example recursion is not needed so the following will suffice:

cp Folder1/* Folder2/

EDIT:

Or skip the mkdir Folder2 part and just run:

cp -r Folder1 Folder2

how to download file in react js

I have the exact same problem, and here is the solution I make use of now: (Note, this seems ideal to me because it keeps the files closely tied to the SinglePageApplication React app, that loads from Amazon S3. So, it's like storing on S3, and in an application, that knows where it is in S3, relatively speaking.

Steps

3 steps:

  1. Make use of file saver in project: npmjs/package/file-saver (npm install file-saver or something)
  2. Place the file in your project You say it's in the components folder. Well, chances are if you've got web-pack it's going to try and minify it.(someone please pinpoint what webpack would do with an asset file in components folder), and so I don't think it's what you'd want. So, I suggest to place the asset into the public folder, under a resource or an asset name. Webpack doesn't touch the public folder and index.html and your resources get copied over in production build as is, where you may refer them as shown in next step.
  3. Refer to the file in your project Sample code:
    import FileSaver from 'file-saver';
    FileSaver.saveAs(
        process.env.PUBLIC_URL + "/resource/file.anyType",
        "fileNameYouWishCustomerToDownLoadAs.anyType");
    

Source

Appendix

Open Google Chrome from VBA/Excel

Worked here too:

Sub test544()

  Dim chromePath As String

  chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""

  Shell (chromePath & " -url http:google.ca")

End Sub

How do you test running time of VBA code?

Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is QueryPerformanceCounter. Google it for more info. Try pushing the following into a class, call it CTimer say, then you can make an instance somewhere global and just call .StartCounter and .TimeElapsed

Option Explicit

Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type

Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long

Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double

Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#

Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
    Low = LI.lowpart
    If Low < 0 Then
        Low = Low + TWO_32
    End If
    LI2Double = LI.highpart * TWO_32 + Low
End Function

Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
    QueryPerformanceFrequency PerfFrequency
    m_crFrequency = LI2Double(PerfFrequency)
End Sub

Public Sub StartCounter()
    QueryPerformanceCounter m_CounterStart
End Sub

Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
    QueryPerformanceCounter m_CounterEnd
    crStart = LI2Double(m_CounterStart)
    crStop = LI2Double(m_CounterEnd)
    TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property

Read an Excel file directly from a R script

Let me reiterate what @Chase recommended: Use XLConnect.

The reasons for using XLConnect are, in my opinion:

  1. Cross platform. XLConnect is written in Java and, thus, will run on Win, Linux, Mac with no change of your R code (except possibly path strings)
  2. Nothing else to load. Just install XLConnect and get on with life.
  3. You only mentioned reading Excel files, but XLConnect will also write Excel files, including changing cell formatting. And it will do this from Linux or Mac, not just Win.

XLConnect is somewhat new compared to other solutions so it is less frequently mentioned in blog posts and reference docs. For me it's been very useful.

How to find the largest file in a directory and its subdirectories?

Try the following one-liner (display top-20 biggest files):

ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20

or (human readable sizes):

ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20

Works fine under Linux/BSD/OSX in comparison to other answers, as find's -printf option doesn't exist on OSX/BSD and stat has different parameters depending on OS. However the second command to work on OSX/BSD properly (as sort doesn't have -h), install sort from coreutils or remove -h from ls and use sort -nr instead.

So these aliases are useful to have in your rc files:

alias big='du -ah . | sort -rh | head -20'
alias big-files='ls -1Rhs | sed -e "s/^ *//" | grep "^[0-9]" | sort -hr | head -n20'

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

If you wish to leave content as it, can wrap it with scrollable.

Useful if you have inputs in the children:

enter image description here

    return Stack(
      children: <Widget>[
        Positioned(
          child: SingleChildScrollView(
              child: Column(
                  children: children
                    ..add(Container(
                      height: 56, // button heigh, so could scroll underlapping area
                    )))),
        ),
        Positioned(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: button,
          ),
        )
      ],
    );

Express-js can't GET my static files, why?

I find my css file and add a route to it:

app.get('/css/MyCSS.css', function(req, res){
  res.sendFile(__dirname + '/public/css/MyCSS.css');
});

Then it seems to work.

How to obtain the number of CPUs/cores in Linux from the command line?

If you just want to count physical cores, this command did it for me.

lscpu -e | tail -n +2 | tr -s " " | cut -d " " -f 4 | sort | uniq | wc -w

Pretty basic, but seems to count actual physical cores, ignoring the logical count

Prevent screen rotation on Android

Use AsyncTaskLoader to keep your data safe even if the activity changes, instead of using AsyncTask that is a better way to build apps than preventing screen rotation.

Python: split a list based on a condition?

Use Boolean logic to assign data to two arrays

>>> images, anims = [[i for i in files if t ^ (i[2].lower() in IMAGE_TYPES) ] for t in (0, 1)]
>>> images
[('file1.jpg', 33, '.jpg')]
>>> anims
[('file2.avi', 999, '.avi')]

List of IP addresses/hostnames from local network in Python

If you know the names of your computers you can use:

import socket
IP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer
IP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer

Otherwise you will have to scan for all the IP addresses that follow the same mask as your local computer (IP1), as stated in another answer.

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

Android, How to read QR code in my application?

try {

    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes

    startActivityForResult(intent, 0);

} catch (Exception e) {

    Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
    Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
    startActivity(marketIntent);

}

and in onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {           
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 0) {

        if (resultCode == RESULT_OK) {
            String contents = data.getStringExtra("SCAN_RESULT");
        }
        if(resultCode == RESULT_CANCELED){
            //handle cancel
        }
    }
}

Align items in a stack panel?

You can achieve this with a DockPanel:

<DockPanel Width="300">
    <TextBlock>Left</TextBlock>
    <Button HorizontalAlignment="Right">Right</Button>
</DockPanel>

The difference is that a StackPanel will arrange child elements into single line (either vertical or horizontally) whereas a DockPanel defines an area where you can arrange child elements either horizontally or vertically, relative to each other (the Dock property changes the position of an element relative to other elements within the same container. Alignment properties, such as HorizontalAlignment, change the position of an element relative to its parent element).

Update

As pointed out in the comments you can also use the FlowDirection property of a StackPanel. See @D_Bester's answer.

When to use RabbitMQ over Kafka?

I know it's a bit late and maybe you already, indirectly, said it, but again, Kafka is not a queue at all, it's a log (as someone said above, poll based).

To make it simple, the most obvious use case when you should prefer RabbitMQ (or any queue techno) over Kafka is the following one :

You have multiple consumers consuming from a queue and whenever there is a new message in the queue and an available consumer, you want this message to be processed. If you look closely at how Kafka works, you'll notice it does not know how to do that, because of partition scaling, you'll have a consumer dedicated to a partition and you'll get into starvation issue. Issue that is easily avoided by using simple queue techno. You can think of using a thread that will dispatch the different messages from same partition, but again, Kafka does not have any selective acknowledgment mechanisms.

The most you could do is doing as those guys and try to transform Kafka as a queue : https://github.com/softwaremill/kmq

Yannick

jQuery: serialize() form and other parameters

Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:

// ...

url: "MyUrl",       //  For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,  
data: 
    $('#myForm').serialize() +
    "&param1="xxx" +
    "&param2="33" +
    "&" + $.param({ paramArray: ["1","2","3"]}, true)
,             

// ...

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Removing object from array in Swift 3

The Swift equivalent to NSMutableArray's removeObject is:

var array = ["alpha", "beta", "gamma"]

if let index = array.firstIndex(of: "beta") {
    array.remove(at: index)
}

if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

The API index(of: also works but this causes an unnecessary implicit bridge cast to NSArray.

If there are multiple occurrences of the same object use filter. However in cases like data source arrays where an index is associated with a particular object firstIndex(of is preferable because it's faster than filter.

Update:

In Swift 4.2+ you can remove one or multiple occurrences of beta with removeAll(where:):

array.removeAll{$0 == "beta"}

How to execute XPath one-liners from shell?

clacke’s answer is great but I think only works if your source is well-formed XML, not normal HTML.

So to do the same for normal Web content—HTML docs that aren’t necessarily well-formed XML:

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
from lxml import html; \
print '\n'.join(html.tostring(node) for node in html.parse(stdin).xpath('//p'))"

And to instead use html5lib (to ensure you get the same parsing behavior as Web browsers—because like browser parsers, html5lib conforms to the parsing requirements in the HTML spec).

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
import html5lib; from lxml import html; \
doc = html5lib.parse(stdin, treebuilder='lxml', namespaceHTMLElements=False); \
print '\n'.join(html.tostring(node) for node in doc.xpath('//p'))

Postgres user does not exist?

I get exactly the same errors as kryshah with su - postgres and sudo -u postgres psql. DanielM's answer gives also errors.

Outputs when wrong settings

Answer however from przbabu's comment.

masi$ psql
psql: FATAL:  database "masi" does not exist
masi$ psql -U postgres
psql: FATAL:  role "postgres" does not exist
masi$ psql postgres
psql (9.4.1)
Type "help" for help.

I think the some part of this problem may be in owner settings in OSX

masi$ ls -al /Users/
total 0
drwxr-xr-x   7 root      admin  238 Jul  3 09:50 .
drwxr-xr-x  37 root      wheel 1326 Jul  2 19:02 ..
-rw-r--r--   1 root      wheel    0 Sep 10  2014 .localized
drwxrwxrwt   7 root      wheel  238 Apr  9 19:49 Shared
drwxr-xr-x   2 root      admin   68 Jul  3 09:50 postgres
drwxr-xr-x+ 71 masi      staff 2414 Jul  3 09:50 masi

but doing sudo chown -R postgres:staff /Users/postgres gives chown: invalid user: ‘postgres:staff’.

In short, this is not the solution the problem. Use the tools provided by the postgres installation to create a user and database.

To get right settings and outputs

There are specific commands after postgres installation to add a new user to the database system. After initdb, run the following as described here

createuser --pwprompt postgres
createdb -Opostgres -Eutf8 masi_development
psql -U postgres -W masi_development

To avoid the password request all the time, you have three choices as described here.

How to redirect docker container logs to a single file?

Assuming that you have multiple containers and you want to aggregate the logs into a single file, you need to use some log aggregator like fluentd. fluentd is supported as logging driver for docker containers.

So in docker-compose, you need to define the logging driver

  service1:
    image: webapp:0.0.1
    logging:
      driver: "fluentd"
      options:
        tag: service1 

  service2:
        image: myapp:0.0.1
        logging:
          driver: "fluentd"
          options:
            tag: service2

The second step would be update the fluentd conf to cater the logs for both service 1 and service 2

 <match service1>
   @type copy
   <store>
    @type file
    path /fluentd/log/service/service.*.log
    time_slice_format %Y%m%d
    time_slice_wait 10m
    time_format %Y%m%dT%H%M%S%z
  </store>
 </match> 
 <match service2>
    @type copy
   <store>
    @type file
    path /fluentd/log/service/service.*.log
    time_slice_format %Y%m%d
    time_slice_wait 10m
    time_format %Y%m%dT%H%M%S%
  </store>
 </match> 

In this config, we are asking logs to be written to a single file to this path
/fluentd/log/service/service.*.log

and the third step would be to run the customized fluentd which will start writing the logs to file.

Here is the link for step by step instructions

Bit Long, but correct way since you get more control over log files path etc and it works well in Docker Swarm too .

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Calculate correlation with cor(), only for numerical columns

For numerical data you have the solution. But it is categorical data, you said. Then life gets a bit more complicated...

Well, first : The amount of association between two categorical variables is not measured with a Spearman rank correlation, but with a Chi-square test for example. Which is logic actually. Ranking means there is some order in your data. Now tell me which is larger, yellow or red? I know, sometimes R does perform a spearman rank correlation on categorical data. If I code yellow 1 and red 2, R would consider red larger than yellow.

So, forget about Spearman for categorical data. I'll demonstrate the chisq-test and how to choose columns using combn(). But you would benefit from a bit more time with Agresti's book : http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937

set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)

table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction

#Let's make a matrix with tons of columns

Data <- as.data.frame(
          matrix(
            sample(letters[1:3],2000,replace=T),
            ncol=25
          )
        )

# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]

# say you need to know which ones are associated with each other.
out <-  apply( combn(columns,2),2,function(x){
          chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
        })

out <- cbind(as.data.frame(t(combn(vars,2))),out)

Then you should get :

> out
   V1  V2       out
1  V3  V7 0.8116733
2  V3 V11 0.1096903
3  V3 V24 0.1653670
4  V7 V11 0.3629871
5  V7 V24 0.4947797
6 V11 V24 0.7259321

Where V1 and V2 indicate between which variables it goes, and "out" gives the p-value for association. Here all variables are independent. Which you would expect, as I created the data at random.

Is there a good Valgrind substitute for Windows?

More or less all Profilers include checking for memory leaks and show you the stack when the memory was allocated.

I can recommend Intels Parallel Inspector. Simple to use and no recompilation needed. The trial version runs for 30 days.

GlowCode and AtromatedQA also include such capabilites. They all offer free trials.

Compuware DevPartner (aka BoundsChecker) in Contrast needs a slowed down "instrumentation" recompile and the application also runs slower when checking for errors. And BoundsChecker can not work with 64 Bit evsrions at all. We gave up on that tool.

How to make clang compile to llvm IR

Use

clang -emit-llvm -o foo.bc -c foo.c
clang -o foo foo.bc

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

How can I pass a file argument to my bash script using a Terminal command in Linux?

Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you're dealing with the question of how to pass arguments 2 and on to your external program. Here's a convenient way:

#!/bin/bash
ext_program="$1"
shift
"$ext_program" "$@"

The shift will remove the first argument, renaming the rest ($2 becomes $1, and so on).$@` refers to the arguments, as an array of words (it must be quoted!).

If you must have your --file syntax (for example, if there's a default program to run, so the user doesn't necessarily have to supply one), just replace ext_program="$1" with whatever parsing of $1 you need to do, perhaps using getopt or getopts.

If you want to roll your own, for just the one specific case, you could do something like this:

if [ "$#" -gt 0 -a "${1:0:6}" == "--file" ]; then
    ext_program="${1:7}"
else
    ext_program="default program"
fi

Python: import module from another directory at the same level in project hierarchy

I faced the same issues. To solve this, I used export PYTHONPATH="$PWD". However, in this case, you will need to modify imports in your Scripts dir depending on the below:

Case 1: If you are in the user_management dir, your scripts should use this style from Modules import LDAPManager to import module.

Case 2: If you are out of the user_management 1 level like main, your scripts should use this style from user_management.Modules import LDAPManager to import modules.

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

How to check internet access on Android? InetAddress never times out

Following is the code from my Utils class:

public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

How do I update a Linq to SQL dbml file?

We use a custom written T4 template that dynamically queries the information_schema model for each table in all of our .DBML files, and then overwrites parts of the .DBML file with fresh schema info from the database. I highly recommend implementing a solution like this - it has saved me oodles of time, and unlike deleting and re-adding your tables to your model you get to keep your associations. With this solution, you'll get compile-time errors when your schema changes. You want to make sure that you're using a version control system though, because diffing is really handy. This is a great solution that works well if you're developing with a DB schema first approach. Of course, I can't share my company's code so you're on your own for writing this yourself. But if you know some Linq-to-XML and can go to school on this project, you can get to where you want to be.

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

How to export data from Spark SQL to CSV

With the help of spark-csv we can write to a CSV file.

val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`

How to get line count of a large file cheaply in Python?

One line, probably pretty fast:

num_lines = sum(1 for line in open('myfile.txt'))

Excel - Shading entire row based on change of value

If you are using MS Excel 2007, you could use the conditional formatting on the Home tab as shown in the screenshot below. You could either use the color scales default option as I have done here or you can go ahead and create a new rule based on your data set. Conditional Formatting

Can I invoke an instance method on a Ruby module without including it?

Another way to do it if you "own" the module is to use module_function.

module UsefulThings
  def a
    puts "aaay"
  end
  module_function :a

  def b
    puts "beee"
  end
end

def test
  UsefulThings.a
  UsefulThings.b # Fails!  Not a module method
end

test

What's an object file in C?

There are 3 kind of object files.

Relocatable object files

Contain machine code in a form that can be combined with other relocatable object files at link time, in order to form an executable object file.

If you have an a.c source file, to create its object file with GCC you should run: gcc a.c -c

The full process would be: preprocessor (cpp) would run over a.c. Its output (still source) will feed into the compiler (cc1). Its output (assembly) will feed into the assembler (as), which will produce the relocatable object file. That file contains object code and linking (and debugging if -g was used) metadata, and is not directly executable.

Shared object files

Special type of relocatable object file that can be loaded dynamically, either at load time, or at run time. Shared libraries are an example of these kinds of objects.

Executable object files

Contain machine code that can be directly loaded into memory (by the loader, e.g execve) and subsequently executed.

The result of running the linker over multiple relocatable object files is an executable object file. The linker merges all the input object files from the command line, from left-to-right, by merging all the same-type input sections (e.g. .data) to the same-type output section. It uses symbol resolution and relocation.

Bonus read:

When linking against a static library the functions that are referenced in the input objects are copied to the final executable. With dynamic libraries a symbol table is created instead that will enable a dynamic linking with the library's functions/globals. Thus, the result is a partially executable object file, as it depends on the library. If the library doesn't exist, the file can no longer execute).

The linking process can be done as follows: ld a.o -o myexecutable

The command: gcc a.c -o myexecutable will invoke all the commands mentioned at point 1 and at point 3 (cpp -> cc1 -> as -> ld1)

1: actually is collect2, which is a wrapper over ld.

How to set the JSTL variable value in javascript?

It is not possible because they are executed in different environments (JSP at server side, JavaScript at client side). So they are not executed in the sequence you see in your code.

var val1 = document.getElementById('userName').value; 

<c:set var="user" value=""/>  // how do i set val1 here? 

Here JSTL code is executed at server side and the server sees the JavaScript/Html codes as simple texts. The generated contents from JSTL code (if any) will be rendered in the resulting HTML along with your other JavaScript/HTML codes. Now the browser renders HTML along with executing the Javascript codes. Now remember there is no JSTL code available for the browser.

Now for example,

<script type="text/javascript">
<c:set var="message" value="Hello"/> 
var message = '<c:out value="${message}"/>';
</script>

Now for the browser, this content is rendered,

<script type="text/javascript">
var message = 'Hello';
</script>

Hope this helps.

How to iterate std::set?

You must dereference the iterator in order to retrieve the member of your set.

std::set<unsigned long>::iterator it;
for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) {
    u_long f = *it; // Note the "*" here
}

If you have C++11 features, you can use a range-based for loop:

for(auto f : SERVER_IPS) {
  // use f here
}    

Cannot hide status bar in iOS7

To hide status bar in iOS7 you need 2 lines of code

  1. inapplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions write

    [application setStatusBarHidden:YES];
    
  2. in info.plist add this

    View-Controller Based Status Bar Appearance = NO
    

PHP compare two arrays and get the matched values not the difference

OK.. We needed to compare a dynamic number of product names...

There's probably a better way... but this works for me...

... because....Strings are just Arrays of characters.... :>}

//  Compare Strings ...  Return Matching Text and Differences with Product IDs...

//  From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";   

$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";   

$ProductNames = array(
    $productID1 => $productName1,
    $productID2 => $productName2
);


function compareNames($ProductNames){   

    //  Convert NameStrings to Arrays...    
    foreach($ProductNames as $id => $product_name){
        $Package1[$id] = explode(" ",$product_name);    
    }

    // Get Matching Text...
    $Matching = call_user_func_array('array_intersect', $Package1 );
    $MatchingText = implode(" ",$Matching);

    //  Get Different Text...
    foreach($Package1 as $id => $product_name_chunks){
        $Package2 = array($product_name_chunks,$Matching);
        $diff = call_user_func_array('array_diff', $Package2 );
        $DifferentText[$id] = trim(implode(" ", $diff));
    }

    $results[$MatchingText]  = $DifferentText;              
    return $results;    
}

$Results =  compareNames($ProductNames);

print_r($Results);

// Gives us this...
[EcoPlus Premio Jet] 
        [abc123] => 600
        [xyz789] => 800

How to pass multiple checkboxes using jQuery ajax post

From the jquery docs for POST (3rd example):

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

How to decrypt a password from SQL server?

You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.

Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?

Changing navigation bar color in Swift

If you're using iOS 13 or 14 and large title, and want to change navigation bar color, use following code:

Refer to barTintColor not applied when NavigationBar is Large Titles

    fileprivate func setNavigtionBarItems() {
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithDefaultBackground()
            appearance.backgroundColor = .brown
//            let naviFont = UIFont(name: "Chalkduster", size: 30) ?? .systemFont(ofSize: 30)
//            appearance.titleTextAttributes = [NSAttributedString.Key.font: naviFont]
            
            navigationController?.navigationBar.prefersLargeTitles = true
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
            //navigationController?.navigationBar.compactAppearance = appearance
        } else {
            // Fallback on earlier versions
            navigationController?.navigationBar.barTintColor = .brown
        }
    }

This took me 1 hour to figure out what is wrong in my code:(, since I'm using large title, it is hard to change the tintColor with largeTitle, why apple makes it so complicated, so many lines to just make a tintColor of navigationBar.

Giving graphs a subtitle in matplotlib

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different fontsize arguments). Hope that helps!

Injecting Mockito mocks into a Spring bean

Looking at Springockito pace of development and number of open issues, I would be little bit worried to introduce it into my test suite stack nowadays. Fact that last release was done before Spring 4 release brings up questions like "Is it possible to easily integrate it with Spring 4?". I don't know, because I didn't try it. I prefer pure Spring approach if I need to mock Spring bean in integration test.

There is an option to fake Spring bean with just plain Spring features. You need to use @Primary, @Profile and @ActiveProfiles annotations for it. I wrote a blog post on the topic.

How to permanently remove few commits from remote branch

Just note to use the last_working_commit_id, when reverting a non-working commit

git reset --hard <last_working_commit_id>

So we must not reset to the commit_id that we don't want.

Then sure, we must push to remote branch:

git push --force

document.getElementById replacement in angular4 / typescript?

You can just inject the DOCUMENT token into the constructor and use the same functions on it

import { Inject }  from '@angular/core';
import { DOCUMENT } from '@angular/common'; 

@Component({...})
export class AppCmp {
   constructor(@Inject(DOCUMENT) document) {
      document.getElementById('el');
   }
}

Or if the element you want to get is in that component, you can use template references.

What's the proper way to "go get" a private repository?

That looks like the GitLab issue 5769.

In GitLab, since the repositories always end in .git, I must specify .git at the end of the repository name to make it work, for example:

import "example.org/myuser/mygorepo.git"

And:

$ go get example.org/myuser/mygorepo.git

Looks like GitHub solves this by appending ".git".

It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go: go get cannot discover meta tag in HTML5 documents”.

What does "fatal: bad revision" mean?

git revert doesn't take a filename parameter. Do you want git checkout?

Best JavaScript compressor

Here's the source code of an HttpHandler which does that, maybe it'll help you

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

IIS 7, HttpHandler and HTTP Error 500.21

It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.

You can learn more about modules, handlers and IIS modes in the following blog post:

IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions

For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.

Pass a variable to a PHP script running from the command line

Parameters send by index like other applications:

php myfile.php type=daily

And then you can get them like this:

<?php
    if (count($argv) == 0) 
        exit;

    foreach ($argv as $arg)
        echo $arg;
?>

How do I check for equality using Spark Dataframe without SQL Query?

There is another simple sql like option. With Spark 1.6 below also should work.

df.filter("state = 'TX'")

This is a new way of specifying sql like filters. For a full list of supported operators, check out this class.

add item to dropdown list in html using javascript

Since your script is in <head>, you need to wrap it in window.onload:

window.onload = function () {
    var select = document.getElementById("year");
    for(var i = 2011; i >= 1900; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);
    }
};

You can also do it in this way

<body onload="addList()">

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

Make Font Awesome icons in a circle?

This is the approach you don't need to use padding, just set the height and width for the a and let the flex handle with margin: 0 auto.

_x000D_
_x000D_
.social-links a{_x000D_
  text-align:center;_x000D_
 float: left;_x000D_
 width: 36px;_x000D_
 height: 36px;_x000D_
 border: 2px solid #909090;_x000D_
 border-radius: 100%;_x000D_
 margin-right: 7px; /*space between*/_x000D_
    display: flex;_x000D_
    align-items: flex-start;_x000D_
    transition: all 0.4s;_x000D_
    -webkit-transition: all 0.4s;_x000D_
} _x000D_
.social-links a i{_x000D_
 font-size: 20px;_x000D_
    align-self:center;_x000D_
 color: #909090;_x000D_
    transition: all 0.4s;_x000D_
    -webkit-transition: all 0.4s;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
.social-links a i::before{_x000D_
  display:inline-block;_x000D_
  text-decoration:none;_x000D_
}_x000D_
.social-links a:hover{_x000D_
  background: rgba(0,0,0,0.2);_x000D_
}_x000D_
.social-links a:hover i{_x000D_
  color:#fff;_x000D_
}
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="social-links">_x000D_
    <a href="#"><i class="fa fa-facebook fa-lg"></i></a>_x000D_
    <a href="#"><i class="fa fa-twitter fa-lg"></i></a>_x000D_
    <a href="#"><i class="fa fa-google-plus fa-lg"></i></a>_x000D_
    <a href="#"><i class="fa fa-pinterest fa-lg"></i></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should I use pt or px?

A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.

A px is a pixel, which will map on to a screen pixel in most cases.

CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.

A pixel is great if you need to size something to match an image, or if you want a thin border.

Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.

Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)

… and so on.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

Suppose we have a datetime object and date is represented as: "2017-05-04"

>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59

jquery stop child triggering parent event

Better way by using on() with chaining like,

$(document).ready(function(){
    $(".header").on('click',function(){
        $(this).children(".children").toggle();
    }).on('click','a',function(e) {
        e.stopPropagation();
   });
});

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

What is a mixin, and why are they useful?

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

  1. You want to provide a lot of optional features for a class.
  2. You want to use one particular feature in a lot of different classes.

For an example of number one, consider werkzeug's request and response system. I can make a plain old request object by saying:

from werkzeug import BaseRequest

class Request(BaseRequest):
    pass

If I want to add accept header support, I would make that

from werkzeug import BaseRequest, AcceptMixin

class Request(AcceptMixin, BaseRequest):
    pass

If I wanted to make a request object that supports accept headers, etags, authentication, and user agent support, I could do this:

from werkzeug import BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin

class Request(AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin, BaseRequest):
    pass

The difference is subtle, but in the above examples, the mixin classes weren't made to stand on their own. In more traditional multiple inheritance, the AuthenticationMixin (for example) would probably be something more like Authenticator. That is, the class would probably be designed to stand on its own.