Programs & Examples On #Repeater

The Repeater control is used to display a repeated list of items that are bound to the control.

ASP.net Repeater get current index, pointer, or counter

Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.

ASPX

<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
    <ItemTemplate>
        <div id="width:50%;height:30px;background:#0f0a0f;">
            <asp:Label ID="lblSr" runat="server" 
               style="width:30%;float:left;text-align:right;text-indent:-2px;" />
            <span 
               style="width:65%;float:right;text-align:left;text-indent:-2px;" >
            <%# Eval("Item") %>
            </span>
        </div>
    </ItemTemplate>
</asp:Repeater>

Code Behind:

    protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblSr") as Label;
        if (l != null)
            l.Text = e.Item.ItemIndex + 1+"";
    }

How to find controls in a repeater header or footer

Find control into Repeater (Header, Item, Footer)

public static class FindControlInRepeater
{
    public static Control FindControl(this Repeater repeater, string controlName)
    {
        for (int i = 0; i < repeater.Controls.Count; i++)
            if (repeater.Controls[i].Controls[0].FindControl(controlName) != null)
                return repeater.Controls[i].Controls[0].FindControl(controlName);
        return null;
    }
}

Formatting DataBinder.Eval data

There is an optional overload for DataBinder.Eval to supply formatting:

<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>

The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:

<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>

What is the correct syntax of ng-include?

For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).

For example:

Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">

Incorrect: div ng-include src=" 'add-more.html' ">

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Oracle: How to find out if there is a transaction pending?

This is the query I normally use,

select s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from v$transaction t
inner join v$session s on t.addr = s.taddr;

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

Difference between final and effectively final

However, starting in Java SE 8, a local class can access local variables and parameters of the >enclosing block that are final or effectively final.

This didn't start on Java 8, I use this since long time. This code used (before java 8) to be legal:

String str = ""; //<-- not accesible from anonymous classes implementation
final String strFin = ""; //<-- accesible 
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
         String ann = str; // <---- error, must be final (IDE's gives the hint);
         String ann = strFin; // <---- legal;
         String str = "legal statement on java 7,"
                +"Java 8 doesn't allow this, it thinks that I'm trying to use the str declared before the anonymous impl."; 
         //we are forced to use another name than str
    }
);

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

I was using CakePHP and I was seeing this error:

This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500

I went to see the CakePHP Debug Level defined at app\config\core.php:

/**
 * CakePHP Debug Level:
 *
 * Production Mode:
 *  0: No error messages, errors, or warnings shown. Flash messages redirect.
 *
 * Development Mode:
 *  1: Errors and warnings shown, model caches refreshed, flash messages halted.
 *  2: As in 1, but also with full debug messages and SQL output.
 *  3: As in 2, but also with full controller dump.
 *
 * In production mode, flash messages redirect after a time interval.
 * In development mode, you need to click the flash message to continue.
 */
Configure::write('debug', 0);

I chanted the value from 0 to 1:

Configure::write('debug', 1);

After this change, when trying to reload the page again, I saw the corresponding error:

Fatal error: Uncaught Exception: Facebook needs the CURL PHP extension.

Conclusion: The solution in my case to see the errors was to change the CakePHP Debug Level from 0 to 1 in order to show errors and warnings.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

psycopg2: insert multiple rows with one query

New execute_values method in Psycopg 2.7:

data = [(1,'x'), (2,'y')]
insert_query = 'insert into t (a, b) values %s'
psycopg2.extras.execute_values (
    cursor, insert_query, data, template=None, page_size=100
)

The pythonic way of doing it in Psycopg 2.6:

data = [(1,'x'), (2,'y')]
records_list_template = ','.join(['%s'] * len(data))
insert_query = 'insert into t (a, b) values {}'.format(records_list_template)
cursor.execute(insert_query, data)

Explanation: If the data to be inserted is given as a list of tuples like in

data = [(1,'x'), (2,'y')]

then it is already in the exact required format as

  1. the values syntax of the insert clause expects a list of records as in

    insert into t (a, b) values (1, 'x'),(2, 'y')

  2. Psycopg adapts a Python tuple to a Postgresql record.

The only necessary work is to provide a records list template to be filled by psycopg

# We use the data list to be sure of the template length
records_list_template = ','.join(['%s'] * len(data))

and place it in the insert query

insert_query = 'insert into t (a, b) values {}'.format(records_list_template)

Printing the insert_query outputs

insert into t (a, b) values %s,%s

Now to the usual Psycopg arguments substitution

cursor.execute(insert_query, data)

Or just testing what will be sent to the server

print (cursor.mogrify(insert_query, data).decode('utf8'))

Output:

insert into t (a, b) values (1, 'x'),(2, 'y')

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

Android JSONObject - How can I loop through a flat JSON object to get each key and value

You shold use the keys() or names() method. keys() will give you an iterator containing all the String property names in the object while names() will give you an array of all key String names.

You can get the JSONObject documentation here

http://developer.android.com/reference/org/json/JSONObject.html

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

Just for other's reference, I just received this and found it was due to AngularJS. It's for backwards compatibility:

if (!event.preventDefault) {
    event.preventDefault = function() {
        event.returnValue = false; //ie
    };
}

vb.net get file names in directory?

Try this:

Dim text As String = ""
Dim files() As String = IO.Directory.GetFiles(sFolder)

For Each sFile As String In files
    text &= IO.File.ReadAllText(sFile)
Next

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

Add a column with a default value to an existing table in SQL Server

Try this

ALTER TABLE Product
ADD ProductID INT NOT NULL DEFAULT(1)
GO

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

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

Our problem was that the gradle-wrapper.jar file kept getting corrupted by git.

We had to add a .gitattributes file with the line:

*.jar binary

Then remove the jar from git and add it again. Weirdly enough that was only required for one of our repos but not the others.

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

We get this error because of build path issue. You should add "Server Runtime" libraries in Build Path.

"java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer"

Please follow below steps to resolve class not found exception.

Right click on project --> Build Path --> Java Build Path --> Add Library --> Server Runtime --> Apache Tomcat v7.0

Convert UTF-8 encoded NSData to NSString

Sometimes, the methods in the other answers don't work. In my case, I'm generating a signature with my RSA private key and the result is NSData. I found that this seems to work:

Objective-C

NSData *signature;
NSString *signatureString = [signature base64EncodedStringWithOptions:0];

Swift

let signatureString = signature.base64EncodedStringWithOptions(nil)

How to convert IPython notebooks to PDF and HTML?

nbconvert is not yet fully replaced by nbconvert2, you can still use it if you wish, otherwise we would have removed the executable. It's just a warning that we do not bugfix nbconvert1 anymore.

The following should work :

./nbconvert.py --format=pdf yourfile.ipynb 

If you are on a IPython recent enough version, do not use print view, just use the the normal print dialog. Graph beeing cut in chrome is a known issue (Chrome does not respect some print css), and works much better with firefox, not all versions still.

As for nbconvert2, it still highly dev and docs need to be written.

Nbviewer use nbconvert2 so it's pretty decent with HTML.

List of current available profiles:

$ ls -l1 profile|cut -d. -f1

base_html
blogger_html
full_html
latex_base
latex_sphinx_base
latex_sphinx_howto
latex_sphinx_manual
markdown
python
reveal
rst

Give you the existing profiles. (You can create your own, cf future doc, ./nbconvert2.py --help-all should give you some option you can use in your profile.)

then

$ ./nbconvert2.py [profilename] --no-stdout --write=True <yourfile.ipynb>

And it should write your (tex) files as long as extracted figures in cwd. Yes I know this is not obvious, and it will probably change hence no doc...

The reason for that is that nbconvert2 will mainly be a python library where in pseudo code you can do :

 MyConverter = NBConverter(config=config)
 ipynb = read(ipynb_file)
 converted_files = MyConverter.convert(ipynb)
 for file in converted_files :
     write(file)

Entry point will come later, once the API is stabilized.

I'll just point out that @jdfreder (github profile) is working on tex/pdf/sphinx export and is the expert to generate PDF from ipynb file at the time of this writing.

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Our issue was simply the port number on the endpoint was incorrectly set to 8080. Changed it to 8443 and it worked.

Is it possible to put a ConstraintLayout inside a ScrollView?

I've spent 2 days attempting to convert layouts to ConstraintLayout in the so-called "stable" release Android Studio 2.2 and I've not got ScrollView to work in the designer. I'm not going to start down the route of adding constraints in XML for Views that are further down the scroll. After all this is supposed to be a visual design tool.

And the number of rendering errors, stack overflows and theme issues I've had has led me to conclude that the whole ConstraintLayout implementation is still riddled with bugs. Unless you are developing simple layouts then I'd leave it well alone until it's had a few more iterations at least.

That's 2 days I'm not going to get back.

Carriage Return\Line feed in Java

Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?

It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/

I've created the boot entry that disables HyperV and it's working

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

Install gcc.

If you're on linux, use the package manager.

If you're on Windows, use MinGW.

How do I add a Maven dependency in Eclipse?

Open the pom.xml file.

under the project tag add <dependencies> as another tag, and google for the Maven dependencies. I used this to search.

So after getting the dependency create another tag dependency inside <dependencies> tag.

So ultimately it will look something like this.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>doc-examples</groupId>
  <artifactId>lambda-java-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lambda-java-example</name>
  <dependencies>
      <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.0.0</version>
    </dependency>
  </dependencies>
</project>

Hope it helps.

Row Offset in SQL Server

Best way to do it without wasting time to order records is like this :

select 0 as tmp,Column1 from Table1 Order by tmp OFFSET 5000000 ROWS FETCH NEXT 50 ROWS ONLY

it takes less than one second!
best solution for large tables.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

I've just solved these exact errors myself. The key it seems is that your project.properties file in your appcompat library project should use whatever the highest version of the API that your particular appcompat project has been written for (in your case it looks like v21). Easiest way I've found to tell is to look for the highest 'values-v**' folder inside the res folder (eg. values-v21).

To clarify, in addition to the instructions at Support Library Setup, your appcompat/project.properties file should have in it: target=android-21 (mine came with 19 instead).

Also ensure that you have the 'SDK Platform' to match that version installed (eg for v21 install Android 5.0 SDK Platform).

See also appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Alternatively if you don't want to use the appcompat at all, (I think) all you need to do is right click your project > Properties > Android > Library > Remove the reference to the appcompat. The errors will still show up for the appcompat project, but shouldn't affect your project after that.

How to avoid warning when introducing NAs by coercion

suppressWarnings() has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.

> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion 
> y <- destring(c("1", "2", "X"))
> y
[1]  1  2 NA
> x
[1]  1  2 NA

How to update nested state properties in React

Although nesting isn't really how you should treat a component state, sometimes for something easy for single tier nesting.

For a state like this

state = {
 contact: {
  phone: '888-888-8888',
  email: '[email protected]'
 }
 address: {
  street:''
 },
 occupation: {
 }
}

A re-useable method ive used would look like this.

handleChange = (obj) => e => {
  let x = this.state[obj];
  x[e.target.name] = e.target.value;
  this.setState({ [obj]: x });
};

then just passing in the obj name for each nesting you want to address...

<TextField
 name="street"
 onChange={handleChange('address')}
 />

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

Detect iPad users using jQuery?

I use this:

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

    return false;
} // End Function fnIsAppleMobile


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

How to disassemble a memory range with GDB?

If all that you want is to see the disassembly with the INTC call, use objdump -d as someone mentioned but use the -static option when compiling. Otherwise the fopen function is not compiled into the elf and is linked at runtime.

How do I prevent and/or handle a StackOverflowException?

By the looks of it, apart from starting another process, there doesn't seem to be any way of handling a StackOverflowException. Before anyone else asks, I tried using AppDomain, but that didn't work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;

namespace StackOverflowExceptionAppDomainTest
{
    class Program
    {
        static void recrusiveAlgorithm()
        {
            recrusiveAlgorithm();
        }
        static void Main(string[] args)
        {
            if(args.Length>0&&args[0]=="--child")
            {
                recrusiveAlgorithm();
            }
            else
            {
                var domain = AppDomain.CreateDomain("Child domain to test StackOverflowException in.");
                domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { "--child" });
                domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
                {
                    Console.WriteLine("Detected unhandled exception: " + e.ExceptionObject.ToString());
                };
                while (true)
                {
                    Console.WriteLine("*");
                    Thread.Sleep(1000);
                }
            }
        }
    }
}

If you do end up using the separate-process solution, however, I would recommend using Process.Exited and Process.StandardOutput and handle the errors yourself, to give your users a better experience.

What is a 'NoneType' object?

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

How to include *.so library in Android Studio?

To use native-library (so files) You need to add some codes in the "build.gradle" file.

This code is for cleaing "armeabi" directory and copying 'so' files into "armeabi" while 'clean project'.

task copyJniLibs(type: Copy) {
    from 'libs/armeabi'
    into 'src/main/jniLibs/armeabi'
}
tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(copyJniLibs)
}
clean.dependsOn 'cleanCopyJniLibs'

I've been referred from the below. https://gist.github.com/pocmo/6461138

How do I convert a String object into a Hash object?

I built a gem hash_parser that first checks if a hash is safe or not using ruby_parser gem. Only then, it applies the eval.

You can use it as

require 'hash_parser'

# this executes successfully
a = "{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, 
       :key_b => { :key_1b => 'value_1b' } }"
p HashParser.new.safe_load(a)

# this throws a HashParser::BadHash exception
a = "{ :key_a => system('ls') }"
p HashParser.new.safe_load(a)

The tests in https://github.com/bibstha/ruby_hash_parser/blob/master/test/test_hash_parser.rb give you more examples of the things I've tested to make sure eval is safe.

Entity Framework Core: A second operation started on this context before a previous operation completed

I have a background service that performs an action for each entry in a table. The problem is, that if I iterate over and modify some data all on the same instance of the DbContext this error occurs.

One solution, as mentioned in this thread is to change the DbContext's lifetime to transient by defining it like

services.AddDbContext<DbContext>(ServiceLifetime.Transient);

but because I do changes in multiple different services and commit them at once using the SaveChanges() method this solution doesnt work in my case.

Because my code runs in a service, I was doing something like

using (var scope = Services.CreateScope())
{
   var entities = scope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = scope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)
   {
       writeService.DoSomething(entity);
   } 
}

to be able to use the service like if it was a simple request. So to solve the issue i just split the single scope into two, one for the query and the other for the write operations like so:

using (var readScope = Services.CreateScope())
using (var writeScope = Services.CreateScope())
{
   var entities = readScope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = writeScope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)
   {
       writeService.DoSomething(entity);
   } 
}

Like that, there are effevtively two different instances of the DbContext being used.

Another possible solution would be to make sure, that the read operation has terminated before starting the iteration. That is not very pratical in my case because there could be a lot of results that would all need to be loaded into memory for the operation which I tried to avoid by using a Queryable in the first place.

Image overlay on responsive sized images bootstrap

Add a class to the containing div, then set the following css on it:

.img-overlay {
    position: relative;
    max-width: 500px; //whatever your max-width should be 
}

position: relative is required on a parent element of children with position: absolute for the children to be positioned in relation to that parent.

DEMO

Finding last occurrence of substring in string, replacing that

a = "A long string with a . in the middle ending with ."

# if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with

index = a.rfind("with") 

# the result will be 44, as index starts from 0.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to center-justify the last line of text in CSS?

You can also split the element into two via HTML + JS.

HTML:

<div class='justificator'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a 
type specimen book.
</div>

JS:

function justify() {
    // Query for elements search
    let arr = document.querySelectorAll('.justificator');
    for (let current of arr) {
        let oldHeight = current.offsetHeight;
        // Stores cut part
        let buffer = '';

        if (current.innerText.lastIndexOf(' ') >= 0) {
            while (current.offsetHeight == oldHeight) {
                let lastIndex = current.innerText.lastIndexOf(' ');
                buffer = current.innerText.substring(lastIndex) + buffer;
                current.innerText = current.innerText.substring(0, lastIndex);
            }
            let sibling = current.cloneNode(true);
            sibling.innerText = buffer;
            sibling.classList.remove('justificator');
            // Center
            sibling.style['text-align'] = 'center';


            current.style['text-align'] = 'justify';
            // For devices that do support text-align-last
            current.style['text-align-last'] = 'justify';
            // Insert new element after current
            current.parentNode.insertBefore(sibling, current.nextSibling);
        }
    }
}
document.addEventListener("DOMContentLoaded", justify);

Here is an example with div and p tags

_x000D_
_x000D_
function justify() {_x000D_
    // Query for elements search_x000D_
    let arr = document.querySelectorAll('.justificator');_x000D_
    for (let current of arr) {_x000D_
        let oldHeight = current.offsetHeight;_x000D_
        // Stores cut part_x000D_
        let buffer = '';_x000D_
_x000D_
        if (current.innerText.lastIndexOf(' ') >= 0) {_x000D_
            while (current.offsetHeight == oldHeight) {_x000D_
                let lastIndex = current.innerText.lastIndexOf(' ');_x000D_
                buffer = current.innerText.substring(lastIndex) + buffer;_x000D_
                current.innerText = current.innerText.substring(0, lastIndex);_x000D_
            }_x000D_
            let sibling = current.cloneNode(true);_x000D_
            sibling.innerText = buffer;_x000D_
            sibling.classList.remove('justificator');_x000D_
            // Center_x000D_
            sibling.style['text-align'] = 'center';_x000D_
            // For devices that do support text-align-last_x000D_
            current.style['text-align-last'] = 'justify';_x000D_
            current.style['text-align'] = 'justify';_x000D_
            // Insert new element after current_x000D_
            current.parentNode.insertBefore(sibling, current.nextSibling);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
justify();
_x000D_
p.justificator {_x000D_
    margin-bottom: 0px;_x000D_
}_x000D_
p.justificator + p {_x000D_
    margin-top: 0px;_x000D_
}
_x000D_
<div class='justificator'>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
<p class='justificator'>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</p><p>Some other text</p>
_x000D_
_x000D_
_x000D_ Disadvantage: doesn't work when page width changes dynamically.

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Convert .pem to .crt and .key

To extract the key and cert from a pem file:

Extract key

openssl pkey -in foo.pem -out foo.key

Another method of extracting the key...

openssl rsa -in foo.pem -out foo.key

Extract all the certs, including the CA Chain

openssl crl2pkcs7 -nocrl -certfile foo.pem | openssl pkcs7 -print_certs -out foo.cert

Extract the textually first cert as DER

openssl x509 -in foo.pem -outform DER -out first-cert.der

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to sum all the values in a dictionary?

You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.

Example:

c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}

sum(list(c.values()))

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Disable color change of anchor tag when visited

You can solve this issue by calling a:link and a:visited selectors together. And follow it with a:hover selector.

a:link, a:visited
{color: gray;}
a:hover
{color: skyblue;}

JDK on OSX 10.7 Lion

I have just ran into the same problem after updating. The JRE that is downloaded by OSX Lion is missing JavaRuntimeSupport.jar which will work but can wreck havoc on a lot of things. If you've updated, and you had a working JDK/JRE installed prior to that, do the following in Eclipse:

1) Project > Properties > Java Build Path > Select broken JRE/JDK > Edit

2) Select "Alternate JRE"

3) Click "Installed JREs..."

4) In the window that opens, click "Search..."

If all goes well, it will find your older JRE/JDK. Mine was in this location:

/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

Parse error: Syntax error, unexpected end of file in my PHP code

You can't divide IF/ELSE instructions into two separate blocks. If you need HTML code to be printed, use echo.

<html>
    <?php
        function login()
        {
            // Login function code
        }
        if (login())
        {
            echo "<h2>Welcome Administrator</h2>
            <a href=\"upload.php\">Upload Files</a>
            <br />
            <a href=\"points.php\">Edit Points Tally</a>";
        }
        else
        {
            echo "Incorrect login details. Please login";
        }
    ?>
    Some more HTML code
</html>

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

iOS Launching Settings -> Restrictions URL Scheme

As of iOS10 you can use

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root")!) 

to open general settings.

also you can add known urls(you can see them in the most upvoted answer) to it to open specific settings. For example the below one opens touchID and passcode.

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=TOUCHID_PASSCODE")!)

How to find rows that have a value that contains a lowercase letter

for search all rows in lowercase

SELECT *
FROM Test
WHERE col1 
LIKE '%[abcdefghijklmnopqrstuvwxyz]%'
collate Latin1_General_CS_AS

Thanks Manesh Joseph

How do you check if a JavaScript Object is a DOM Object?

var isElement = function(e){
    try{
        // if e is an element attached to the DOM, we trace its lineage and use native functions to confirm its pedigree
        var a = [e], t, s, l = 0, h = document.getElementsByTagName('HEAD')[0], ht = document.getElementsByTagName('HTML')[0];
        while(l!=document.body&&l!=h&&l.parentNode) l = a[a.push(l.parentNode)-1];
        t = a[a.length-1];
        s = document.createElement('SCRIPT');   // safe to place anywhere and it won't show up
        while(a.length>1){  // assume the top node is an element for now...
            var p = a.pop(),n = a[a.length-1];
            p.insertBefore(s,n);
        }
        if(s.parentNode)s.parentNode.removeChild(s);
        if(t!=document.body&&t!=h&&t!=ht)
            // the top node is not attached to the document, so we don't have to worry about it resetting any dynamic media
            // test the top node
            document.createElement('DIV').appendChild(t).parentNode.removeChild(t);
        return e;
    }
    catch(e){}
    return null;
}

I tested this on Firefox, Safari, Chrome, Opera and IE9. I couldn't find a way to hack it.
In theory, it tests every ancestor of the proposed element, as well as the element itself, by inserting a script tag before it.
If its first ancestor traces back to a known element, such as <html>, <head> or <body>, and it hasn't thrown an error along the way, we have an element.
If the first ancestor is not attached to the document, we create an element and attempt to place the proposed element inside of it, (and then remove it from the new element).
So it either traces back to a known element, successfully attaches to a known element or fails.
It returns the element or null if it is not an element.

Redis: How to access Redis log file

You can also login to the redis-cli and use the MONITOR command to see what queries are happening against Redis.

Is there a Google Sheets formula to put the name of the sheet into a cell?

An old thread, but a useful one... so here's some additional code.

First, in response to Craig's point about the regex being overly greedy and failing for sheet names containing a single quote, this should do the trick (replace 'SHEETNAME'!A1 with your own sheet & cell reference):

=IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), "")

It uses a lazy match (the ".+?") to find a character string (squotes included) that may or may not be enclosed by squotes but is definitely terminated by bang dollar ("!$") followed by any number of characters. Google Sheets actually protects squotes within a sheet name by appending another squote (as in ''), so the SUBSTITUTE is needed to reduce these back to single squotes.

The formula also allows for sheet names that contain bangs ("!"), but will fail for names using bang dollars ("!$") - if you really need to make your sheet names to look like full absolute cell references then put a separating character between the bang and the dollar (such as a space).

Note that it will only work correctly when pointed at a different sheet from the one that the formula resides! This is because CELL("address" returns just the cell reference (not the sheet name) when used on the same sheet. If you need a sheet to show its own name then put the formula in a cell on another sheet, point it at your target sheet, and then reference the formula cell from the target sheet. I often have a "Meta" sheet in my workbooks to hold settings, common values, database matching criteria, etc so that's also where I put this formula.

As others have said many times above, Google Sheets will only notice changes to the sheet name if you set the workbook's recalculation to "On change and every minute" which you can find on the File|Settings|Calculation menu. It can take up to a whole minute for the change to be picked up.


Secondly, if like me you happen to need an inter-operable formula that works on both Google Sheets and Excel (which for older versions at least doesn't have the REGEXREPLACE function), try:

=IF(IFERROR(INFO("release"), 0)=0, IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), ""), MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255))

This uses INFO("release") to determine which platform we are on... Excel returns a number >0 whereas Google Sheets does not implement the INFO function and generates an error which the formula traps into a 0 and uses for numerical comparison. The Google code branch is as above.

For clarity and completeness, this is the Excel-only version (which does correctly return the name of the sheet it resides on):

=MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255)

It looks for the "]" filename terminator in the output of CELL("filename" and extracts the sheet name from the remaining part of the string using the MID function. Excel doesn't allow sheet names to contain "]" so this works for all possible sheet names. In the inter-operable version, Excel is happy to be fed a call to the non-existent REGEXREPLACE function because it never gets to execute the Google code branch.

Horizontal Scroll Table in Bootstrap/CSS

@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:

css:

.scrollme {
    overflow-x: auto;
}

html:

<div class="scrollme">                        
  <table class="table table-responsive"> ...
  </table>
</div>

Edit: changing scroll-y to scroll-x

Convert Rtf to HTML

I think you can load it in a Word document object by using .NET office programmability support and Visual Studio tools for office.

And then use the document instance to re-save as an HTML document.

I am not sure how but I believe it is possible entirely in .NET without any 3rd party library.

How to do a Jquery Callback after form submit?

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

WPF ListView - detect when selected item is clicked

You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.

XAML:

<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...

Code behind:

private void listView_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        ...
    }
}

How do I record audio on iPhone with AVAudioRecorder?

I've been trying to get this code to work for the last 2 hours and though it showed no error on the simulator, there was one on the device.

Turns out, at least in my case that the error came from directory used (bundle) :

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];

It was not writable or something like this... There was no error except the fact that prepareToRecord failed...

I therefore replaced it by :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", recDir]]

It now Works like a Charm.

Hope this helps others.

Could not extract response: no suitable HttpMessageConverter found for response type

As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:

restTemplate.getInterceptors().add((request, body, execution) -> {
            ClientHttpResponse response = execution.execute(request,body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response;
        });

How to disable the back button in the browser using JavaScript

history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

This script will overwrite attempts to navigate back and forth with the state of the current page.


Update:

Some users have reported better success with using document.URL instead of document.title:

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;
}

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

How do I time a method's execution in Java?

Using Instant and Duration from Java 8's new API,

Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));

outputs,

PT5S

Difference between two dates in Python

I tried the code posted by larsmans above but, there are a couple of problems:

1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:

...
    d1 = d1.strftime("%Y-%m-%d")
    d2 = d2.strftime("%Y-%m-%d")
    return abs((d2 - d1).days)

This will convert your datetime objects to strings but, two things

1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings

What I found is that you literally only need the following:

import datetime

end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)

print difference_in_days

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

include antiforgerytoken in ajax post ASP.NET MVC

You have incorrectly specified the contentType to application/json.

Here's an example of how this might work.

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}

View:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="myDiv" data-url="@Url.Action("Index", "Home")">
    Click me to send an AJAX request to a controller action
    decorated with the [ValidateAntiForgeryToken] attribute
</div>

<script type="text/javascript">
    $('#myDiv').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                someValue: 'some value' 
            },
            success: function (result) {
                alert(result.someValue);
            }
        });
        return false;
    });
</script>

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Collection was modified; enumeration operation may not execute

I want to point out other case not reflected in any of the answers. I have a Dictionary<Tkey,TValue> shared in a multi threaded app, which uses a ReaderWriterLockSlim to protect the read and write operations. This is a reading method that throws the exception:

public IEnumerable<Data> GetInfo()
{
    List<Data> info = null;
    _cacheLock.EnterReadLock();
    try
    {
        info = _cache.Values.SelectMany(ce => ce.Data); // Ad .Tolist() to avoid exc.
    }
    finally
    {
        _cacheLock.ExitReadLock();
    }
    return info;
}

In general, it works fine, but from time to time I get the exception. The problem is a subtlety of LINQ: this code returns an IEnumerable<Info>, which is still not enumerated after leaving the section protected by the lock. So, it can be changed by other threads before being enumerated, leading to the exception. The solution is to force the enumeration, for example with .ToList() as shown in the comment. In this way, the enumerable is already enumerated before leaving the protected section.

So, if using LINQ in a multi-threaded application, be aware to always materialize the queries before leaving the protected regions.

What's the difference between SortedList and SortedDictionary?

This is visual representation of how performances compare to each other.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Set width of a "Position: fixed" div relative to parent div

You can also solve it by jQuery:

var new_width = $('#container').width();
$('#fixed').width(new_width); 

This was so helpful to me because my layout was responsive, and the inherit solution wasn't working with me!

Proper use of const for defining functions in JavaScript

It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:

Q: I am interested if there are any limits to what types of values can be set using const in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?

I was motivated to do some research after observing one prolific JavaScript coder who always uses const statement for functions, even when there is no apparent reason/benefit.

In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function statement.

It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:

Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.

I urge everyone to read that article, even if you have already made a decision.

Here's are the main points:

Function statements have two clear advantages over [const] function expressions:

Advantage #1: Clarity of intent

When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible.

Advantage #2: Order of declaration == order of execution

Ideally, I want to declare my code more or less in the order that I expect it will get executed.

This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.

What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.

My brain doesn’t work that way. I want the context before the details.

Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.

Steps to upload an iPhone application to the AppStore

Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.

Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC

String formatting: % vs. .format vs. string literal

As I discovered today, the old way of formatting strings via % doesn't support Decimal, Python's module for decimal fixed point and floating point arithmetic, out of the box.

Example (using Python 3.3.5):

#!/usr/bin/env python3

from decimal import *

getcontext().prec = 50
d = Decimal('3.12375239e-24') # no magic number, I rather produced it by banging my head on my keyboard

print('%.50f' % d)
print('{0:.50f}'.format(d))

Output:

0.00000000000000000000000312375239000000009907464850 0.00000000000000000000000312375239000000000000000000

There surely might be work-arounds but you still might consider using the format() method right away.

Change Toolbar color in Appcompat 21

You can change the color of the text in the toolbar with these:

<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

Read data from SqlDataReader

I know this is kind of old but if you are reading the contents of a SqlDataReader into a class, then this will be very handy. the column names of reader and class should be same

public static List<T> Fill<T>(this SqlDataReader reader) where T : new()
        {
            List<T> res = new List<T>();
            while (reader.Read())
            {
                T t = new T();
                for (int inc = 0; inc < reader.FieldCount; inc++)
                {
                    Type type = t.GetType();
                    string name = reader.GetName(inc);
                    PropertyInfo prop = type.GetProperty(name);
                    if (prop != null)
                    {
                        if (name == prop.Name)
                        {
                            var value = reader.GetValue(inc);
                            if (value != DBNull.Value)
                            { 
                                prop.SetValue(t, Convert.ChangeType(value, prop.PropertyType), null);
                            }
                            //prop.SetValue(t, value, null);

                        }
                    }
                }
                res.Add(t);
            }
            reader.Close();

            return res;
        }

Is it possible to open a Windows Explorer window from PowerShell?

Use any of these:

  1. start .
  2. explorer .
  3. start explorer .
  4. ii .
  5. invoke-item .

You may apply any of these commands in PowerShell.

Just in case you want to open the explorer from the command prompt, the last two commands don't work, and the first three work fine.

How do I create an .exe for a Java program?

You could try exe4j. This is effectively what we use through its cousin install4j.

How can I get a value from a map?

map.at("key") throws exception if missing key

If k does not match the key of any element in the container, the function throws an out_of_range exception.

http://www.cplusplus.com/reference/map/map/at/

Convert stdClass object to array in PHP

$wpdb->get_results("SELECT ...", ARRAY_A);

ARRAY_A is a "output_type" argument. It can be one of four pre-defined constants (defaults to OBJECT):

OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first columns values as keys (duplicates will be discarded).
ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys.
ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.  

See: http://codex.wordpress.org/Class_Reference/wpdb

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Difference between sh and bash

sh: http://man.cx/sh
bash: http://man.cx/bash

TL;DR: bash is a superset of sh with a more elegant syntax and more functionality. It is safe to use a bash shebang line in almost all cases as it's quite ubiquitous on modern platforms.

NB: in some environments, sh is bash. Check sh --version.

How to convert int to QString?

If you need locale-aware number formatting, use QLocale::toString instead.

Use dynamic variable names in `dplyr`

You may enjoy package friendlyeval which presents a simplified tidy eval API and documentation for newer/casual dplyr users.

You are creating strings that you wish mutate to treat as column names. So using friendlyeval you could write:

multipetal <- function(df, n) {
  varname <- paste("petal", n , sep=".")
  df <- mutate(df, !!treat_string_as_col(varname) := Petal.Width * n)
  df
}

for(i in 2:5) {
  iris <- multipetal(df=iris, n=i)
}

Which under the hood calls rlang functions that check varname is legal as column name.

friendlyeval code can be converted to equivalent plain tidy eval code at any time with an RStudio addin.

How to pass boolean parameter value in pipeline to downstream jobs?

Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link

And then if you have something like blue ocean, the choices would look something like this:

enter image description here

You define and access your variables like this:

pipeline {
    agent any

    parameters {
    string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
    choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
    }

    stages {
        stage("foo") {
            steps {
                echo "flag: ${params.userFlag}"
                echo "flag: ${params.DEPLOY_ENV}"
            }
        }
    }
}

Automated builds will pick up the default params. But if you do it manually then you get the option to choose.

And then assign values like this:

enter image description here

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

I had the same error and solved the problem by running the program code below:

# install_certifi.py
#
# sample script to install or update a set of default Root Certificates
# for the ssl module.  Uses the certificates provided by the certifi package:
#       https://pypi.python.org/pypi/certifi

import os
import os.path
import ssl
import stat
import subprocess
import sys

STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
             | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
             | stat.S_IROTH |                stat.S_IXOTH )


def main():
    openssl_dir, openssl_cafile = os.path.split(
        ssl.get_default_verify_paths().openssl_cafile)

    print(" -- pip install --upgrade certifi")
    subprocess.check_call([sys.executable,
        "-E", "-s", "-m", "pip", "install", "--upgrade", "certifi"])

    import certifi

    # change working directory to the default SSL directory
    os.chdir(openssl_dir)
    relpath_to_certifi_cafile = os.path.relpath(certifi.where())
    print(" -- removing any existing file or link")
    try:
        os.remove(openssl_cafile)
    except FileNotFoundError:
        pass
    print(" -- creating symlink to certifi certificate bundle")
    os.symlink(relpath_to_certifi_cafile, openssl_cafile)
    print(" -- setting permissions")
    os.chmod(openssl_cafile, STAT_0o775)
    print(" -- update complete")

if __name__ == '__main__':
    main()

how to hide the content of the div in css

Without changing the markup or using JavaScript, you'd pretty much have to alter the text color as knut mentions, or set text-indent: -1000em;

IE6 will not read the :hover selector on anything other than an anchor element, so you will have to use something like Dean Edwards' IE7.

Really though, you're better off putting the text in some kind of element (like p or span or a) and setting that to display: none; on hover.

Converting string to byte array in C#

static byte[] GetBytes(string str)
{
     byte[] bytes = new byte[str.Length * sizeof(char)];
     System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     return bytes;
}

static string GetString(byte[] bytes)
{
     char[] chars = new char[bytes.Length / sizeof(char)];
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     return new string(chars);
}

The create-react-app imports restriction outside of src directory

This restriction makes sure all files or modules (exports) are inside src/ directory, the implementation is in ./node_modules/react-dev-utils/ModuleScopePlugin.js, in following lines of code.

// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
     const relative = path.relative(appSrc, request.context.issuer);
// If it's not in src/ or a subdirectory, not our request!
     if (relative.startsWith('../') || relative.startsWith('..\\')) {
        return callback();
      }

You can remove this restriction by

  1. either changing this piece of code (not recommended)
  2. or do eject then remove ModuleScopePlugin.js from the directory.
  3. or comment/remove const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); from ./node_modules/react-scripts/config/webpack.config.dev.js

PS: beware of the consequences of eject.

use of entityManager.createNativeQuery(query,foo.class)

What you do is called a projection. That's when you return only a scalar value that belongs to one entity. You can do this with JPA. See scalar value.

I think in this case, omitting the entity type altogether is possible:

   Query query = em.createNativeQuery(  "select id from users where username = ?");  
   query.setParameter(1, "lt");  
   BigDecimal val = (BigDecimal) query.getSingleResult(); 

Example taken from here.

How to do SQL Like % in Linq?

Contains is used in Linq ,Just like Like is used in SQL .

string _search="/12/";

. . .

.Where(s => s.Hierarchy.Contains(_search))

You can write your SQL script in Linq as Following :

 var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});

Convert array of integers to comma-separated string

int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

Template not provided using create-react-app

First uninstall create-react-app

npm uninstall -g create-react-app

Then run yarn create react-app my-app or npx create-react-app my-app

then running yarn create react-app my-app or npx create-react-app my-app may still gives the error,

A template was not provided. This is likely because you're using an outdated version of create-react-app.Please note that global installs of create-react-app are no longer supported.

This may happens because of the cashes. So next run

npm cache clean --force 

then run

npm cache verify

Now its all clear. Now run

yarn create react-app my-app or npx create-react-app my-app

Now you will get what you expected!

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

PHP: How to send HTTP response code?

If your version of PHP does not include this function:

<?php

function http_response_code($code = NULL) {
        if ($code !== NULL) {
            switch ($code) {
                case 100: $text = 'Continue';
                    break;
                case 101: $text = 'Switching Protocols';
                    break;
                case 200: $text = 'OK';
                    break;
                case 201: $text = 'Created';
                    break;
                case 202: $text = 'Accepted';
                    break;
                case 203: $text = 'Non-Authoritative Information';
                    break;
                case 204: $text = 'No Content';
                    break;
                case 205: $text = 'Reset Content';
                    break;
                case 206: $text = 'Partial Content';
                    break;
                case 300: $text = 'Multiple Choices';
                    break;
                case 301: $text = 'Moved Permanently';
                    break;
                case 302: $text = 'Moved Temporarily';
                    break;
                case 303: $text = 'See Other';
                    break;
                case 304: $text = 'Not Modified';
                    break;
                case 305: $text = 'Use Proxy';
                    break;
                case 400: $text = 'Bad Request';
                    break;
                case 401: $text = 'Unauthorized';
                    break;
                case 402: $text = 'Payment Required';
                    break;
                case 403: $text = 'Forbidden';
                    break;
                case 404: $text = 'Not Found';
                    break;
                case 405: $text = 'Method Not Allowed';
                    break;
                case 406: $text = 'Not Acceptable';
                    break;
                case 407: $text = 'Proxy Authentication Required';
                    break;
                case 408: $text = 'Request Time-out';
                    break;
                case 409: $text = 'Conflict';
                    break;
                case 410: $text = 'Gone';
                    break;
                case 411: $text = 'Length Required';
                    break;
                case 412: $text = 'Precondition Failed';
                    break;
                case 413: $text = 'Request Entity Too Large';
                    break;
                case 414: $text = 'Request-URI Too Large';
                    break;
                case 415: $text = 'Unsupported Media Type';
                    break;
                case 500: $text = 'Internal Server Error';
                    break;
                case 501: $text = 'Not Implemented';
                    break;
                case 502: $text = 'Bad Gateway';
                    break;
                case 503: $text = 'Service Unavailable';
                    break;
                case 504: $text = 'Gateway Time-out';
                    break;
                case 505: $text = 'HTTP Version not supported';
                    break;
                default:
                    exit('Unknown http status code "' . htmlentities($code) . '"');
                    break;
            }
            $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
            header($protocol . ' ' . $code . ' ' . $text);
            $GLOBALS['http_response_code'] = $code;
        } else {
            $code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
        }
        return $code;
    }

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

Allow user to select camera or gallery for image

Building upon David's answer, my two pennies on the onActivityResult() part. It takes care of the changes introduced in 5.1.1 and detects whether the user has picked a single or multiple image from the library.

private enum Outcome {
    camera, singleLibrary, multipleLibrary, unknown
}

/**
 * Returns a List<Uri> containing the image uri(s) chosen by the user
 *
 * @param data      The data intent coming from the onActivityResult()
 * @param cameraUri The uri that had been passed to the intent when the chooser was invoked.
 * @return A List<Uri>, never null.
 */
public List<Uri> getPicturesUriFromIntent(Intent data, Uri cameraUri) {

    Outcome outcome = Outcome.unknown;

    if (data == null || (data.getData() == null && data.getClipData() == null)) {
        outcome = Outcome.camera;
    } else if (data.getData() != null && data.getClipData() == null) {
        outcome = Outcome.singleLibrary;
    } else if (data.getData() == null) {
        outcome = Outcome.multipleLibrary;
    } else {
        final String action = data.getAction();
        if (action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE)) {
            outcome = Outcome.camera;
        }
    }

    // list the uri(s) we got back
    List<Uri> uris = new ArrayList<>();
    switch (outcome) {
        case camera:
            uris.add(cameraUri);
            break;

        case singleLibrary:
            uris.add(data.getData());
            break;

        case multipleLibrary:
            final ClipData clipData = data.getClipData();
            for (int i = 0; i < clipData.getItemCount(); i++) {
                ClipData.Item item = clipData.getItemAt(i);
                uris.add(item.getUri());
            }
            break;
    }

    return uris;
}

Using LIKE in an Oracle IN clause

You can put your values in ODCIVARCHAR2LIST and then join it as a regular table.

select tabl1.* FROM tabl1 LEFT JOIN 
(select column_value txt from table(sys.ODCIVARCHAR2LIST
('%val1%','%val2%','%val3%')
)) Vals ON tabl1.column LIKE Vals.txt WHERE Vals.txt IS NOT NULL

Count number of records returned by group by

A CTE worked for me:

with cte as (
  select 1 col1
  from temptable
  group by column_1
)

select COUNT(col1)
from cte;

ERROR 1148: The used command is not allowed with this MySQL version

All of this didn't solve it for me on my brand new Ubuntu 15.04.

I removed the LOCAL and got this command:

LOAD DATA
INFILE A.txt
INTO DB
LINES TERMINATED BY '|';

but then I got:

MySQL said: File 'A.txt' not found (Errcode: 13 - Permission denied)

That led me to this answer from Nelson to another question on stackoverflow which solved the issue for me!

Android EditText view Floating Hint in Material Design

@andruboy's suggestion of https://gist.github.com/chrisbanes/11247418 is probably your best bet.

https://github.com/thebnich/FloatingHintEditText kind of works with appcompat-v7 v21.0.0, but since v21.0.0 does not support accent colors with subclasses of EditText, the underline of the FloatingHintEditText will be the default solid black or white. Also the padding is not optimized for the Material style EditText, so you may need to adjust it.

Java command not found on Linux

I use the following script to update the default alternative after install jdk.

#!/bin/bash
export JAVA_BIN_DIR=/usr/java/default/bin # replace with your installed directory
cd ${JAVA_BIN_DIR}
a=(java javac javadoc javah javap javaws)
for exe in ${a[@]}; do
    sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${JAVA_BIN_DIR}/${exe}" 1
    sudo update-alternatives --set ${exe} ${JAVA_BIN_DIR}/${exe}
done

Executing Batch File in C#

Below code worked fine for me

using System.Diagnostics;

public void ExecuteBatFile()
{
    Process proc = null;

    string _batDir = string.Format(@"C:\");
    proc = new Process();
    proc.StartInfo.WorkingDirectory = _batDir;
    proc.StartInfo.FileName = "myfile.bat";
    proc.StartInfo.CreateNoWindow = false;
    proc.Start();
    proc.WaitForExit();
    ExitCode = proc.ExitCode;
    proc.Close();
    MessageBox.Show("Bat file executed...");
}

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

What is makeinfo, and how do I get it?

In (at least) Ubuntu when using bash, it tells you what package you need to install if you type in a command and its not found in your path. My terminal says you need to install 'texinfo' package.

sudo apt-get install texinfo

How to play videos in android from assets folder or raw folder?

I think that you need to look at this -- it should have everything you want.

EDIT: If you don't want to look at the link -- this pretty much sums up what you'd like.

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); mp.start();

But I still recommend reading the information at the link.

MSSQL Error 'The underlying provider failed on Open'

I had this error suddenly happen out of the blue on one of our sites. In my case, it turned out that the SQL user's password had expired! Unticking the password expiration box in SQL Server Management Studio did the trick!

Echo tab characters in bash script

you need to use -e flag for echo then you can

echo -e "\t\t x"

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:

android:name="android.support.multidex.MultiDexApplication" 

OR

MultiDex.install(this);

in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    }
}

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

A simple solution that no one else has said but worked for me was not running without sudo or not as root.

The difference between sys.stdout.write and print?

It is preferable when dynamic printing is useful, for instance, to give information in a long process:

import time, sys
Iterations = 555
for k in range(Iterations+1):

    # Some code to execute here ...

    percentage = k / Iterations
    time_msg = "\rRunning Progress at {0:.2%} ".format(percentage)
    sys.stdout.write(time_msg)
    sys.stdout.flush()
    time.sleep(0.01)

int array to string

To avoid the creation of an extra array you could do the following.

var builder = new StringBuilder();
Array.ForEach(arr, x => builder.Append(x));
var res = builder.ToString();

How to create dictionary and add key–value pairs dynamically?

JavaScript's Object is in itself like a dictionary. No need to reinvent the wheel.

var dict = {};

// Adding key-value -pairs
dict['key'] = 'value'; // Through indexer
dict.anotherKey = 'anotherValue'; // Through assignment

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:key value:value
  // key:anotherKey value:anotherValue
}

// Non existent key
console.log(dict.notExist); // undefined

// Contains key?
if (dict.hasOwnProperty('key')) {
  // Remove item
  delete dict.key;
}

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:anotherKey value:anotherValue
}

Fiddle

Why do I get a "permission denied" error while installing a gem?

I wanted to share the steps that I followed that fixed this issue for me in the hopes that it can help someone else (and also as a reminder for me in case something like this happens again)

The issues I'd been having (which were the same as OP's) may have to do with using homebrew to install Ruby.

To fix this, first I updated homebrew:

brew update && brew upgrade
brew doctor

(If brew doctor comes up with any issues, fix them first.) Then I uninstalled ruby

brew uninstall ruby

If rbenv is NOT installed at this point, then

brew install rbenv
brew install ruby-build
echo 'export RBENV_ROOT=/usr/local/var/rbenv' >> ~/.bash_profile
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile

Then I used rbenv to install ruby. First, find the desired version:

rbenv install -l

Install that version (e.g. 2.2.2)

rbenv install 2.2.2

Then set the global version to the desired ruby version:

rbenv global 2.2.2

At this point you should see the desired version set for the following commands:

rbenv versions

and

ruby --version

Now you should be able to install bundler:

gem install bundler

And once in the desired project folder, you can install all the required gems:

bundle
bundle install

How to use KeyListener

The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

  1. Make one Key listener class as

    class MyListener implements KeyListener{
    
       // override all the methods of KeyListener interface.
    }
    
  2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

  3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

    JFrame f=new JFrame();
    f.addKeyListener(new MyKeyListener);
    

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

As here str(u'\u2013') is causing error so use isinstance(foo,basestring) to check for unicode/string, if not of type base string convert it into Unicode and then apply encode

if isinstance(foo,basestring):
    foo.encode('utf8')
else:
    unicode(foo).encode('utf8')

further read

Why won't eclipse switch the compiler to Java 8?

I had the same problem even though I had:

  • a freshly downloaded JDK 1.8.0

  • JAVA_HOME is set

  • java -version on command line reports 1.8

  • Java in control panel is set to 1.8

  • downloaded Eclipse Mars

Eclipse only let me choose a compiler compliance level op to 1.7 in the compiler preferences, even though my installed JRE is 1.8.0. I also couldn't see a 1.8 in the Execution Environments underneath Installed JREs, only a JavaSE-1.7 (which I haven't even got installed!). When I clicked on that, it shows "jdk1.8.0" as a compatible JRE, so I selected that, but still no change.

Then I unzipped Eclipse Mars into a brand new directory, created a new project, and now I can select 1.8, hurrah! That greatly reduced the "Duplicate methods named spliterator..." errors I was getting when compiling my code under Java 1.8, however, there is still one left:

Duplicate default methods named spliterator with the parameters () and () are inherited from the types List and Set.

However, that's likely because I'm extending AbstractList and implementing Set, so I've fixed that for now by removing the implements Set because it doesn't really add anything in my case (other than signifying that my collection has only unique elements)

How can I symlink a file in Linux?

Links are basically of two types:

Symbolic links (soft): link to a symbolic path indicating the abstract location of another file

Hard links: link to the specific location of physical data.

Example 1:

ln /root/file1 /root/file2

The above is an example of a hard link where you can have a copy of your physical data.

Example 2:

ln -s /path/to/file1.txt /path/to/file2.txt

The above command will create a symbolic link to file1.txt.

If you delete a source file then you won't have anything to the destination in soft.

When you do:

ls -lai

You'll see that there is a different inode number for the symlinks.

For more details, you can read the man page of ln on your Linux OS.

Unable to auto-detect email address

You can solve the problem with the global solution, but firstly I want to describe the solution for each project individually, cause of trustfully compatibility with most of Git clients and other implemented Git environments:

  • Individual Solution

Go to the following location:

Local/repo/location/.git/

open "config" file there, and set your parameters like the example (add to the end of the file):

[user]
    name = YOUR-NAME
    email = YOUR-EMAIL-ADDRESS
  • Global Solution

Open a command line and type:

git config --global user.email "[email protected]"
git config --global user.name "YOUR NAME"

MongoDB: How to update multiple documents with a single command?

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :

db.test.update({"foo":"bar"},{"$set":{"test":"success!"}}, {multi:true} )

How to hide a <option> in a <select> menu with CSS?

Select inputs are tricky in this way. What about disabling it instead, this will work cross-browser:

$('select').children(':nth-child(even)').prop('disabled', true);

This will disable every-other <option> element, but you can select which ever one you want.

Here is a demo: http://jsfiddle.net/jYWrH/

Note: If you want to remove the disabled property of an element you can use .removeProp('disabled').

Update

You could save the <option> elements you want to hide in hidden select element:

$('#visible').on('change', function () {
    $(this).children().eq(this.selectedIndex).appendTo('#hidden');
});

You can then add the <option> elements back to the original select element:

$('#hidden').children().appendTo('#visible');

In these two examples it's expected that the visible select element has the id of visible and the hidden select element has the id of hidden.

Here is a demo: http://jsfiddle.net/jYWrH/1/

Note that .on() is new in jQuery 1.7 and in the usage for this answer is the same as .bind(): http://api.jquery.com/on

Getting the ID of the element that fired an event

this works with most types of elements:

$('selector').on('click',function(e){
    log(e.currentTarget.id);
    });

How to set all elements of an array to zero or any same value?

If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.

CREATE DATABASE permission denied in database 'master' (EF code-first)

  1. Create the empty database manually.
  2. Change the "Integrated Security" in connection string from "true" to "false".
  3. Be sure your user is sysadmin in your new database

Now I hope you can execute update-database successfully.

Reading a text file in MATLAB line by line

You cannot read text strings with csvread. Here is another solution:

fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
    line = fgets(fid1); %# read line by line
    A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
    if A(2)<4.185 %# test the values
        fprintf(fid2,'%s',line); %# write the line to the new file
    end
end
fclose(fid1);
fclose(fid2);

How to apply slide animation between two activities in Android?

Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.

Slide animations can be slid right, slide left, slide up and slide down.

Slide up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:toXScale="1.0"
        android:toYScale="0.0" />
</set>

Slide down

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

overridePendingTransition(R.anim.slide_down, R.anim.slide_up);

See activity transition animation examples for more activity transition examples.

Django model "doesn't declare an explicit app_label"

I had the same problem just now. I've fixed mine by adding a namespace on the app name. Hope someone find this helpful.

apps.py

from django.apps import AppConfig    

class SalesClientConfig(AppConfig):
        name = 'portal.sales_client'
        verbose_name = 'Sales Client'

C# Return Different Types?

You can have the return type to be a superclass of the three classes (either defined by you or just use object). Then you can return any one of those objects, but you will need to cast it back to the correct type when getting the result. Like:

public object GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return radio; or return computer; or return hello //should be possible?!      
}

Then:

Hello hello = (Hello)getAnything(); 

How can I start and check my MySQL log?

For me, general_log didn't worked. But adding this to my.ini worked

[mysqld]
log-output=FILE
slow_query_log = 1
slow_query_log_file = "d:/temp/developer.log"

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot: enter image description here

The graphs are now in the correct order.

Way to ng-repeat defined number of times instead of repeating over array?

angular gives a very sweet function called slice.. using this you can achieve what you are looking for. e.g. ng-repeat="ab in abc.slice(startIndex,endIndex)"

this demo :http://jsfiddle.net/sahilosheal/LurcV/39/ will help you out and tell you how to use this "making life easy" function. :)

html:

<div class="div" ng-app >
    <div ng-controller="Main">
        <h2>sliced list(conditional NG-repeat)</h2>
        <ul ng-controller="ctrlParent">
            <li ng-repeat="ab in abc.slice(2,5)"><span>{{$index+1}} :: {{ab.name}} </span></li>
        </ul>
        <h2>unsliced list( no conditional NG-repeat)</h2>
         <ul ng-controller="ctrlParent">
            <li ng-repeat="ab in abc"><span>{{$index+1}} :: {{ab.name}} </span></li>
        </ul>

    </div>

CSS:

ul
{
list-style: none;
}
.div{
    padding:25px;
}
li{
    background:#d4d4d4;
    color:#052349;
}

ng-JS:

 function ctrlParent ($scope) {
    $scope.abc = [
     { "name": "What we do", url: "/Home/AboutUs" },
     { "name": "Photo Gallery", url: "/home/gallery" },
     { "name": "What we work", url: "/Home/AboutUs" },
     { "name": "Photo play", url: "/home/gallery" },
     { "name": "Where", url: "/Home/AboutUs" },
     { "name": "playground", url: "/home/gallery" },
     { "name": "What we score", url: "/Home/AboutUs" },
     { "name": "awesome", url: "/home/gallery" },
     { "name": "oscar", url: "/Home/AboutUs" },
     { "name": "american hustle", url: "/home/gallery" }
    ];
}
function Main($scope){
    $scope.items = [{sort: 1, name: 'First'}, 
                    {sort: 2, name: 'Second'}, 
                    {sort: 3, name: 'Third'}, 
                    {sort: 4, name:'Last'}];
    }

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

Well, I think the error says that it can't find a nib file named "RootViewController" in your project.

You are writing these lines of code,

self.viewController = [[RootViewController alloc]      initWithNibName:@"RootViewController_iPhone.xib" bundle:nil];

self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController_iPad.xib" bundle:nil];

At the same time you are asking it to load a nib file named "RootviewController"..!! Where is it..? Do you have a xib file named "Rootviewcontroller"..?

Bootstrap footer at the bottom of the page

In my case for Bootstrap4:

<body class="d-flex flex-column min-vh-100">
    <div class="wrapper flex-grow-1"></div>
    <footer></footer>
</body>

Get a file name from a path

_splitpath should do what you need. You could of course do it manually but _splitpath handles all special cases as well.

EDIT:

As BillHoag mentioned it is recommended to use the more safe version of _splitpath called _splitpath_s when available.

Or if you want something portable you could just do something like this

std::vector<std::string> splitpath(
  const std::string& str
  , const std::set<char> delimiters)
{
  std::vector<std::string> result;

  char const* pch = str.c_str();
  char const* start = pch;
  for(; *pch; ++pch)
  {
    if (delimiters.find(*pch) != delimiters.end())
    {
      if (start != pch)
      {
        std::string str(start, pch);
        result.push_back(str);
      }
      else
      {
        result.push_back("");
      }
      start = pch + 1;
    }
  }
  result.push_back(start);

  return result;
}

...
std::set<char> delims{'\\'};

std::vector<std::string> path = splitpath("C:\\MyDirectory\\MyFile.bat", delims);
cout << path.back() << endl;

Detecting user leaving page with react-router

For react-router v3.x

I had the same issue where I needed a confirmation message for any unsaved change on the page. In my case, I was using React Router v3, so I could not use <Prompt />, which was introduced from React Router v4.

I handled 'back button click' and 'accidental link click' with the combination of setRouteLeaveHook and history.pushState(), and handled 'reload button' with onbeforeunload event handler.

setRouteLeaveHook (doc) & history.pushState (doc)

  • Using only setRouteLeaveHook was not enough. For some reason, the URL was changed although the page remained the same when 'back button' was clicked.

      // setRouteLeaveHook returns the unregister method
      this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
        this.props.route,
        this.routerWillLeave
      );
    
      ...
    
      routerWillLeave = nextLocation => {
        // Using native 'confirm' method to show confirmation message
        const result = confirm('Unsaved work will be lost');
        if (result) {
          // navigation confirmed
          return true;
        } else {
          // navigation canceled, pushing the previous path
          window.history.pushState(null, null, this.props.route.path);
          return false;
        }
      };
    

onbeforeunload (doc)

  • It is used to handle 'accidental reload' button

    window.onbeforeunload = this.handleOnBeforeUnload;
    
    ...
    
    handleOnBeforeUnload = e => {
      const message = 'Are you sure?';
      e.returnValue = message;
      return message;
    }
    

Below is the full component that I have written

  • note that withRouter is used to have this.props.router.
  • note that this.props.route is passed down from the calling component
  • note that currentState is passed as prop to have initial state and to check any change

    import React from 'react';
    import PropTypes from 'prop-types';
    import _ from 'lodash';
    import { withRouter } from 'react-router';
    import Component from '../Component';
    import styles from './PreventRouteChange.css';
    
    class PreventRouteChange extends Component {
      constructor(props) {
        super(props);
        this.state = {
          // initialize the initial state to check any change
          initialState: _.cloneDeep(props.currentState),
          hookMounted: false
        };
      }
    
      componentDidUpdate() {
    
       // I used the library called 'lodash'
       // but you can use your own way to check any unsaved changed
        const unsaved = !_.isEqual(
          this.state.initialState,
          this.props.currentState
        );
    
        if (!unsaved && this.state.hookMounted) {
          // unregister hooks
          this.setState({ hookMounted: false });
          this.unregisterRouteHook();
          window.onbeforeunload = null;
        } else if (unsaved && !this.state.hookMounted) {
          // register hooks
          this.setState({ hookMounted: true });
          this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
          );
          window.onbeforeunload = this.handleOnBeforeUnload;
        }
      }
    
      componentWillUnmount() {
        // unregister onbeforeunload event handler
        window.onbeforeunload = null;
      }
    
      handleOnBeforeUnload = e => {
        const message = 'Are you sure?';
        e.returnValue = message;
        return message;
      };
    
      routerWillLeave = nextLocation => {
        const result = confirm('Unsaved work will be lost');
        if (result) {
          return true;
        } else {
          window.history.pushState(null, null, this.props.route.path);
          if (this.formStartEle) {
            this.moveTo.move(this.formStartEle);
          }
          return false;
        }
      };
    
      render() {
        return (
          <div>
            {this.props.children}
          </div>
        );
      }
    }
    
    PreventRouteChange.propTypes = propTypes;
    
    export default withRouter(PreventRouteChange);
    

Please let me know if there is any question :)

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Htaccess: add/remove trailing slash from URL

This is what I've used for my latest app.

# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing

# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on 

# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]

# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/  -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^/?(.*?)/?$ $1.php

Why are only a few video games written in Java?

I think John Carmack said it best with:

The biggest problem is that Java is really slow. On a pure cpu / memory / display / communications level, most modern cell phones should be considerably better gaming platforms than a Game Boy Advanced. With Java, on most phones you are left with about the CPU power of an original 4.77 mhz IBM PC, and lousy control over everything. [...snip...] Write-once-run-anywhere. Ha. Hahahahaha. We are only testing on four platforms right now, and not a single pair has the exact same quirks. All the commercial games are tweaked and compiled individually for each (often 100+) platform. Portability is not a justification for the awful performance.

(source)

Granted, he was talking about mobile platforms, but I've found similar problems with Java as a whole coming from a C++ background. I miss being able to allocate memory on the Stack/Heap on my own terms.

Reverse / invert a dictionary mapping

To do this while preserving the type of your mapping (assuming that it is a dict or a dict subclass):

def inverse_mapping(f):
    return f.__class__(map(reversed, f.items()))

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How to replace space with comma using sed?

If you are talking about sed, this works:

sed -e "s/ /,/g" < a.txt

In vim, use same regex to replace:

s/ /,/g

Beautiful way to remove GET-variables with PHP?

Ok, to remove all variables, maybe the prettiest is

$url = strtok($url, '?');

See about strtok here.

Its the fastest (see below), and handles urls without a '?' properly.

To take a url+querystring and remove just one variable (without using a regex replace, which may be faster in some cases), you might do something like:

function removeqsvar($url, $varname) {
    list($urlpart, $qspart) = array_pad(explode('?', $url), 2, '');
    parse_str($qspart, $qsvars);
    unset($qsvars[$varname]);
    $newqs = http_build_query($qsvars);
    return $urlpart . '?' . $newqs;
}

A regex replace to remove a single var might look like:

function removeqsvar($url, $varname) {
    return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}

Heres the timings of a few different methods, ensuring timing is reset inbetween runs.

<?php

$number_of_tests = 40000;

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;

for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    preg_replace('/\\?.*/', '', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "regexp execution time: ".$totaltime." seconds; ";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    $str = explode('?', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "explode execution time: ".$totaltime." seconds; ";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    $qPos = strpos($str, "?");
    $url_without_query_string = substr($str, 0, $qPos);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "strpos execution time: ".$totaltime." seconds; ";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    $url_without_query_string = strtok($str, '?');
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "tok execution time: ".$totaltime." seconds; ";

shows

regexp execution time: 0.14604902267456 seconds; explode execution time: 0.068033933639526 seconds; strpos execution time: 0.064775943756104 seconds; tok execution time: 0.045819044113159 seconds; 
regexp execution time: 0.1408839225769 seconds; explode execution time: 0.06751012802124 seconds; strpos execution time: 0.064877986907959 seconds; tok execution time: 0.047760963439941 seconds; 
regexp execution time: 0.14162802696228 seconds; explode execution time: 0.065848112106323 seconds; strpos execution time: 0.064821004867554 seconds; tok execution time: 0.041788101196289 seconds; 
regexp execution time: 0.14043688774109 seconds; explode execution time: 0.066350221633911 seconds; strpos execution time: 0.066242933273315 seconds; tok execution time: 0.041517972946167 seconds; 
regexp execution time: 0.14228296279907 seconds; explode execution time: 0.06665301322937 seconds; strpos execution time: 0.063700199127197 seconds; tok execution time: 0.041836977005005 seconds; 

strtok wins, and is by far the smallest code.

Convert JSON String to JSON Object c#

If your JSon string has "" double quote instead of a single quote ' and has \n as a indicator of a next line then you need to remove it because that's not a proper JSon string, example as shown below:

            SomeClass dna = new SomeClass ();
            string response = wc.DownloadString(url);
            string strRemSlash = response.Replace("\"", "\'");
            string strRemNline = strRemSlash.Replace("\n", " ");
            // Time to desrialize it to convert it into an object class.
            dna = JsonConvert.DeserializeObject<SomeClass>(@strRemNline);

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

How to use split?

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ") 

How to get the Display Name Attribute of an Enum member via MVC Razor code?

combining all edge-cases together from above:

  • enum members with base object members' names (Equals, ToString)
  • optional Display attribute

here is my code:

public enum Enum
{
    [Display(Name = "What a weird name!")]
    ToString,

    Equals
}

public static class EnumHelpers
{
    public static string GetDisplayName(this Enum enumValue)
    {
        var enumType = enumValue.GetType();

        return enumType
                .GetMember(enumValue.ToString())
                .Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == enumType)
                .First()
                .GetCustomAttribute<DisplayAttribute>()?.Name ?? enumValue.ToString();
    }
}

void Main()
{
    Assert.Equals("What a weird name!", Enum.ToString.GetDisplayName());
    Assert.Equals("Equals", Enum.Equals.GetDisplayName());
}

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

must appear in the GROUP BY clause or be used in an aggregate function

For me, it is not about a "common aggregation problem", but just about an incorrect SQL query. The single correct answer for "select the maximum avg for each cname..." is

SELECT cname, MAX(avg) FROM makerar GROUP BY cname;

The result will be:

 cname  |      MAX(avg)
--------+---------------------
 canada | 2.0000000000000000
 spain  | 5.0000000000000000

This result in general answers the question "What is the best result for each group?". We see that the best result for spain is 5 and for canada the best result is 2. It is true, and there is no error. If we need to display wmname also, we have to answer the question: "What is the RULE to choose wmname from resulting set?" Let's change the input data a bit to clarify the mistake:

  cname | wmname |        avg           
--------+--------+-----------------------
 spain  | zoro   |  1.0000000000000000
 spain  | luffy  |  5.0000000000000000
 spain  | usopp  |  5.0000000000000000

Which result do you expect on runnig this query: SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;? Should it be spain+luffy or spain+usopp? Why? It is not determined in the query how to choose "better" wmname if several are suitable, so the result is also not determined. That's why SQL interpreter returns an error - the query is not correct.

In the other word, there is no correct answer to the question "Who is the best in spain group?". Luffy is not better than usopp, because usopp has the same "score".

How to check if spark dataframe is empty?

For Java users you can use this on a dataset :

public boolean isDatasetEmpty(Dataset<Row> ds) {
        boolean isEmpty;
        try {
            isEmpty = ((Row[]) ds.head(1)).length == 0;
        } catch (Exception e) {
            return true;
        }
        return isEmpty;
}

This check all possible scenarios ( empty, null ).

Ruby: How to turn a hash into HTTP parameters?

{:a=>"a", :b=>"b", :c=>"c"}.map{ |x,v| "#{x}=#{v}" }.reduce{|x,v| "#{x}&#{v}" }

"a=a&b=b&c=c"

Here's another way. For simple queries.

Is there a way to specify which pytest tests to run from a file?

My answer provides a ways to run a subset of test in different scenarios.

Run all tests in a project

pytest

Run tests in a Single Directory

To run all the tests from one directory, use the directory as a parameter to pytest:

pytest tests/my-directory

Run tests in a Single Test File/Module

To run a file full of tests, list the file with the relative path as a parameter to pytest:

pytest tests/my-directory/test_demo.py

Run a Single Test Function

To run a single test function, add :: and the test function name:

pytest -v tests/my-directory/test_demo.py::test_specific_function

-v is used so you can see which function was run.

Run a Single Test Class

To run just a class, do like we did with functions and add ::, then the class name to the file parameter:

pytest -v tests/my-directory/test_demo.py::TestClassName

Run a Single Test Method of a Test Class

If you don't want to run all of a test class, just one method, just add another :: and the method name:

pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method

Run a Set of Tests Based on Test Name

The -k option enables you to pass in an expression to run tests that have certain names specified by the expression as a substring of the test name. It is possible to use and, or, and not to create complex expressions.

For example, to run all of the functions that have _raises in their name:

pytest -v -k _raises

How does one reorder columns in a data frame?

Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:

df<-df[,order(colnames(df),decreasing=TRUE)]

That's what I use when I have large files with many columns.

What is the maximum possible length of a .NET string?

Since the Length property of System.String is an Int32, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32 size). If it allowed longer you couldn't check the Length since that would fail.

printf with std::string?

Use std::printf and c_str() example:

std::printf("Follow this command: %s", myString.c_str());

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How to specify new GCC path for CMake

This question is quite old but still turns up on Google Search. The accepted question wasn't working for me anymore and seems to be aged. The latest information about cmake is written in the cmake FAQ.

There are various ways to change the path of your compiler. One way would be

Set the appropriate CMAKE_FOO_COMPILER variable(s) to a valid compiler name or full path on the command-line using cmake -D. For example:

cmake -G "Your Generator" -D CMAKE_C_COMPILER=gcc-4.2 -D CMAKE_CXX_COMPILER=g++-4.2 path/to/your/source

instead of gcc-4.2 you can write the path/to/your/compiler like this

 cmake -D CMAKE_C_COMPILER=/path/to/gcc/bin/gcc -D CMAKE_CXX_COMPILER=/path/to/gcc/bin/g++ .

gcc warning" 'will be initialized after'

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.

oracle varchar to number

Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:

select * from exception where exception_value = to_char(105);

Initialize Array of Objects using NSArray

There is also a shorthand of doing this:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

How to solve time out in phpmyadmin?

I'm using version 4.0.3 of MAMP along with phpmyadmin. The top of /Applications/MAMP/bin/phpMyAdmin/libraries/config.default.php reads:

DO NOT EDIT THIS FILE, EDIT config.inc.php INSTEAD !!!

Changing the following line in /Applications/MAMP/bin/phpMyAdmin/config.inc.php and restarting MAMP worked for me.

$cfg['ExecTimeLimit'] = 0;

Setting Spring Profile variable

You can simply set a system property on the server as follows...

-Dspring.profiles.active=test

Edit: To add this to tomcat in eclipse, select Run -> Run Configurations and choose your Tomcat run configuration. Click the Arguments tab and add -Dspring.profiles.active=test at the end of VM arguments. Another way would be to add the property to your catalina.properties in your Servers project, but if you add it there omit the -D

Edit: For use with Spring Boot, you have an additional choice. You can pass the property as a program argument if you prepend the property with two dashes.

Here are two examples using a Spring Boot executable jar file...

System Property

[user@host ~]$ java -jar -Dspring.profiles.active=test myproject.jar

Program Argument

[user@host ~]$ java -jar myproject.jar --spring.profiles.active=test

One line if statement not working

For simplicity, If you need to default to some value if nil you can use:

@something.nil? = "No" || "Yes"

CryptographicException 'Keyset does not exist', but only through WCF

This is the only solution worked for me.

    // creates the CspParameters object and sets the key container name used to store the RSA key pair
    CspParameters cp = new CspParameters();
    cp.KeyContainerName = "MyKeyContainerName"; //Eg: Friendly name

    // instantiates the rsa instance accessing the key container MyKeyContainerName
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
    // add the below line to delete the key entry in MyKeyContainerName
    // rsa.PersistKeyInCsp = false;

    //writes out the current key pair used in the rsa instance
    Console.WriteLine("Key is : \n" + rsa.ToXmlString(true));

Reference 1

Reference 2

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

How do I wrap text in a pre tag?

I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.

 <div style="white-space: pre-wrap;">content</div>

How to use an output parameter in Java?

This is not accurate ---> "...* pass array. arrays are passed by reference. i.e. if you pass array of integers, modified the array inside the method.

Every parameter type is passed by value in Java. Arrays are object, its object reference is passed by value.

This includes an array of primitives (int, double,..) and objects. The integer value is changed by the methodTwo() but it is still the same arr object reference, the methodTwo() cannot add an array element or delete an array element. methodTwo() cannot also, create a new array then set this new array to arr. If you really can pass an array by reference, you can replace that arr with a brand new array of integers.

Every object passed as parameter in Java is passed by value, no exceptions.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.

var mockFileBrowser = new Mock<FileBrowser>();

instead of

var mockFileBrowser = new Mock<IFileBrowser>();

JAX-WS client : what's the correct path to access the local WSDL?

The best option is to use jax-ws-catalog.xml

When you compile the local WSDL file , override the WSDL location and set it to something like

http://localhost/wsdl/SOAService.wsdl

Don't worry this is only a URI and not a URL , meaning you don't have to have the WSDL available at that address.
You can do this by passing the wsdllocation option to the wsdl to java compiler.

Doing so will change your proxy code from

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "file:/C:/local/path/to/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'file:/C:/local/path/to/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

to

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "http://localhost/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'http://localhost/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

Notice file:// changed to http:// in the URL constructor.

Now comes in jax-ws-catalog.xml. Without jax-ws-catalog.xml jax-ws will indeed try to load the WSDL from the location

http://localhost/wsdl/SOAService.wsdl
and fail, as no such WSDL will be available.

But with jax-ws-catalog.xml you can redirect jax-ws to a locally packaged WSDL whenever it tries to access the WSDL @

http://localhost/wsdl/SOAService.wsdl
.

Here's jax-ws-catalog.xml

<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system">
        <system systemId="http://localhost/wsdl/SOAService.wsdl"
                uri="wsdl/SOAService.wsdl"/>
    </catalog>

What you are doing is telling jax-ws that when ever it needs to load WSDL from

http://localhost/wsdl/SOAService.wsdl
, it should load it from local path wsdl/SOAService.wsdl.

Now where should you put wsdl/SOAService.wsdl and jax-ws-catalog.xml ? That's the million dollar question isn't it ?
It should be in the META-INF directory of your application jar.

so something like this

ABCD.jar  
|__ META-INF    
    |__ jax-ws-catalog.xml  
    |__ wsdl  
        |__ SOAService.wsdl  

This way you don't even have to override the URL in your client that access the proxy. The WSDL is picked up from within your JAR, and you avoid having to have hard-coded filesystem paths in your code.

More info on jax-ws-catalog.xml http://jax-ws.java.net/nonav/2.1.2m1/docs/catalog-support.html

Hope that helps

Java 8 lambda get and remove element from list

I'm sure this will be an unpopular answer, but it works...

ProducerDTO[] p = new ProducerDTO[1];
producersProcedureActive
            .stream()
            .filter(producer -> producer.getPod().equals(pod))
            .findFirst()
            .ifPresent(producer -> {producersProcedureActive.remove(producer); p[0] = producer;}

p[0] will either hold the found element or be null.

The "trick" here is circumventing the "effectively final" problem by using an array reference that is effectively final, but setting its first element.

Convert HashBytes to VarChar

Contrary to what David Knight says, these two alternatives return the same response in MS SQL 2008:

SELECT CONVERT(VARCHAR(32),HashBytes('MD5', 'Hello World'),2)
SELECT UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('MD5', 'Hello World'), 1, 0))

So it looks like the first one is a better choice, starting from version 2008.

Call one constructor from another

Please, please, and pretty please do not try this at home, or work, or anywhere really.

This is a way solve to a very very specific problem, and I hope you will not have that.

I'm posting this since it is technically an answer, and another perspective to look at it.

I repeat, do not use it under any condition. Code is to run with LINQPad.

void Main()
{
    (new A(1)).Dump();
    (new B(2, -1)).Dump();
    
    var b2 = new B(2, -1);
    b2.Increment();
    
    b2.Dump();
}

class A 
{
    public readonly int I = 0;
    
    public A(int i)
    {
        I = i;
    }
}

class B: A
{
    public int J;
    public B(int i, int j): base(i)
    {
        J = j;
    }
    
    public B(int i, bool wtf): base(i)
    {
    }
    
    public void Increment()
    {
        int i = I + 1;

        var t = typeof(B).BaseType;
        var ctor = t.GetConstructors().First();
        
        ctor.Invoke(this, new object[] { i });
    }
}

Since constructor is a method, you can call it with reflection. Now you either think with portals, or visualize a picture of a can of worms. sorry about this.

How can I plot data with confidence intervals?

Here is part of my program related to plotting confidence interval.

1. Generate the test data

ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)

Result

enter image description here

2. Fitting the raw data using B-spline smoother method

sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
    tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
    tmp <- 1.96*sqrt(tmp)
    y_e_minus[i] <- y_e[i] - tmp
    y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')

Result

enter image description here

Convert Dictionary to JSON in Swift

Swift 3.0

With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

let dic = ["2": "B", "1": "A", "3": "C"]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type        
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}

Swift 2.x

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
    // here "decoded" is of type `AnyObject`, decoded from JSON data

    // you can now cast it with the right type 
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}

Swift 1

var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
    if error != nil {
        println(error)
    } else {
        // here "jsonData" is the dictionary encoded in JSON data
    }
}

if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
    if error != nil {
        println(error)
    } else {
        // here "decoded" is the dictionary decoded from JSON data
    }
}

Remove Rows From Data Frame where a Row matches a String

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

How to set image for bar button with swift?

Initialize barbuttonItem like following:

let pauseButton = UIBarButtonItem(image: UIImage(named: "big"),
                                  style: .plain,
                                  target: self,
                                  action: #selector(PlaybackViewController.pause))

How to insert programmatically a new line in an Excel cell in C#?

What worked for me:

worksheet.Cells[0, 0].Style.WrapText = true;
worksheet.Cells[0, 0].Value = yourStringValue.Replace("\\r\\n", "\r\n");

My issue was that the \r\n came escaped.

When is it appropriate to use C# partial classes?

Partial classes recently helped with source control where multiple developers were adding to one file where new methods were added into the same part of the file (automated by Resharper).

These pushes to git caused merge conflicts. I found no way to tell the merge tool to take the new methods as a complete code block.

Partial classes in this respect allows for developers to stick to a version of their file, and we can merge them back in later by hand.

example -

  • MainClass.cs - holds fields, constructor, etc
  • MainClass1.cs - a developers new code as they implement
  • MainClass2.cs - is another developers class for their new code.

Get all column names of a DataTable into string array using (LINQ/Predicate)

Use

var arrayNames = (from DataColumn x in dt.Columns
                  select x.ColumnName).ToArray();

Use sudo with password as parameter

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

Difference between setTimeout with and without quotes and parentheses

With the parentheses:

setTimeout("alertMsg()", 3000); // It work, here it treat as a function

Without the quotes and the parentheses:

setTimeout(alertMsg, 3000); // It also work, here it treat as a function

And the third is only using quotes:

setTimeout("alertMsg", 3000); // It not work, here it treat as a string

_x000D_
_x000D_
function alertMsg1() {_x000D_
        alert("message 1");_x000D_
    }_x000D_
    function alertMsg2() {_x000D_
        alert("message 2");_x000D_
    }_x000D_
    function alertMsg3() {_x000D_
        alert("message 3");_x000D_
    }_x000D_
    function alertMsg4() {_x000D_
        alert("message 4");_x000D_
    }_x000D_
_x000D_
    // this work after 2 second_x000D_
    setTimeout(alertMsg1, 2000);_x000D_
_x000D_
    // This work immediately_x000D_
    setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
    // this fail_x000D_
    setTimeout('alertMsg3', 6000);_x000D_
_x000D_
    // this work after 8second_x000D_
    setTimeout('alertMsg4()', 8000);
_x000D_
_x000D_
_x000D_

In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.

Error inflating class fragment

Fragments cannot be nested in XML

Learnt this the hard way - if you nest an XML layout based <fragment> tag inside a (potentially) dynamically loaded fragment from FragmentManager, then you start to get weird errors, trying to inflate your fragment xml.

Turns out, that this is not supported - it will work fine if you do this through purely the FragmentManager approach.

I was getting this problem because I was trying load a fragment inside a <DrawerLayout> from xml, and this was causing a crash in the onCreateView() method when I popped the back stack.

How do I uniquely identify computers visiting my web site?

These people have developed a fingerprinting method for recognising a user with a high level of accuracy:

https://panopticlick.eff.org/static/browser-uniqueness.pdf

We investigate the degree to which modern web browsers are subject to “device fingerprinting” via the version and configuration information that they will transmit to websites upon request. We implemented one possible fingerprinting algorithm, and collected these fingerprints from a large sample of browsers that visited our test side, panopticlick.eff.org. We observe that the distribution of our finger- print contains at least 18.1 bits of entropy, meaning that if we pick a browser at random, at best we expect that only one in 286,777 other browsers will share its fingerprint. Among browsers that support Flash or Java, the situation is worse, with the average browser carrying at least 18.8 bits of identifying information. 94.2% of browsers with Flash or Java were unique in our sample.

By observing returning visitors, we estimate how rapidly browser fingerprints might change over time. In our sample, fingerprints changed quite rapidly, but even a simple heuristic was usually able to guess when a fingerprint was an “upgraded” version of a previously observed browser’s fingerprint, with 99.1% of guesses correct and a false positive rate of only 0.86%.

We discuss what privacy threat browser fingerprinting poses in practice, and what countermeasures may be appropriate to prevent it. There is a tradeoff between protection against fingerprintability and certain kinds of debuggability, which in current browsers is weighted heavily against privacy. Paradoxically, anti-fingerprinting privacy technologies can be self- defeating if they are not used by a sufficient number of people; we show that some privacy measures currently fall victim to this paradox, but others do not...

Can't start Tomcat as Windows Service

Solution suggested by Prashant worked fine for me.

Tomcat9 Properties > Configure > Startup > Mode = Java Tomcat9 Properties > Configure > Shutdown > Mode = Java

How to compare DateTime in C#?

Microsoft has also implemented the operators '<' and '>'. So you use these to compare two dates.

if (date1 < DateTime.Now)
   Console.WriteLine("Less than the current time!");

Android: Test Push Notification online (Google Cloud Messaging)

Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool

How to increase heap size for jBoss server

In my case, for jboss 6.3 I had to change JAVA_OPTS in file jboss-eap-6.3\bin\standalone.conf.bat and set following values -Xmx8g -Xms8g -Xmn3080m for jvm to take 8gb space.

`&mdash;` or `&#8212;` is there any difference in HTML output?

SGML parsers (or XML parsers in the case of XHTML) can handle &#8212; without having to process the DTD (which doesn't matter to browsers as they just slurp tag soup), while &mdash; is easier for humans to read and write in the source code.

Personally, I would stick to a literal em-dash and ensure that my character encoding settings were consistent.

Setting PATH environment variable in OSX permanently

You have to add it to /etc/paths.

Reference (which works for me) : Here

How to check if running in Cygwin, Mac or Linux?

Use only this from command line works very fine, thanks to Justin:

#!/bin/bash

################################################## #########
# Bash script to find which OS
################################################## #########

OS=`uname`
echo "$OS"

source