Programs & Examples On #Schemaless

How to export collection to CSV in MongoDB?

Also, you are not allowed spaces between comma separated field names.

BAD: -f firstname, lastname

GOOD: -f firstname,lastname

SQL Server Group By Month

Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

If you have a date (not a datetime) value, then you can zero it directly:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )

If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )

Error in Swift class: Property not initialized at super.init call

Add nil to the end of the declaration.


// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil

// Init the view
override init(frame: CGRect)
    super.init(frame: frame)
    ...

This worked for my case, but may not work for yours

Facebook Like-Button - hide count?

This is what I've tried and it works fine in ff, chrome and ie8:

/* set width for the <fb:like> tag */

.fb-button {
    width:51px;
}

/* set width for the iframe below, to hide the count label*/

.fb-button iframe{
    width:45px!important;
}

How do I put my website's logo to be the icon image in browser tabs?

<link rel="apple-touch-icon" sizes="114x114" href="${resource(dir: 'images', file: 
'apple-touch-icon-retina.png')}">

or you can use this one

<link rel="shortcut icon" sizes="114x114" href="${resource(dir: 'images', file: 'favicon.ico')}"
type="image/x-icon">

Find and replace - Add carriage return OR Newline

If you set "Use regular expressions" flag then \n would be translated. But keep in mind that you would have to modify you search term to be regexp friendly. In your case it should be escaped like this "\~\~\?" (no quotes).

Escape Character in SQL Server

You can escape quotation like this:

select 'it''s escaped'

result will be

it's escaped

What are the best PHP input sanitizing functions?

what about this

$string = htmlspecialchars(strip_tags($_POST['example']));

or this

$string = htmlentities($_POST['example'], ENT_QUOTES, 'UTF-8');

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

How to highlight a current menu item?

My solution to this problem, use route.current in the angular template.

As you have the /tasks route to highlight in your menu, you can add your own property menuItem to the routes declared by your module:

$routeProvider.
  when('/tasks', {
    menuItem: 'TASKS',
    templateUrl: 'my-templates/tasks.html',
    controller: 'TasksController'
  );

Then in your template tasks.htmlyou can use following ng-class directive:

<a href="app.html#/tasks" 
    ng-class="{active : route.current.menuItem === 'TASKS'}">Tasks</a>

In my opinion, this is much cleaner than all proposed solutions.

Oracle JDBC intermittent Connection Issue

OracleXETNSListener - this service has to be started if it was disabled.

run -> services.msc 

and look out for that services

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Better way to sum a property value in an array

Use reduce with destructuring to sum Amount:

const traveler = [
  { description: 'Senior', Amount: 50 },
  { description: 'Senior', Amount: 50 },
  { description: 'Adult', Amount: 75 },
  { description: 'Child', Amount: 35 },
  { description: 'Infant', Amount: 25 },
];

console.log(traveler.reduce((n, {Amount}) => n + Amount, 0))

How to concatenate a std::string and an int?

The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:

#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
    static_cast<std::ostringstream&>(          \
        std::ostringstream().flush() << tokens \
    ).str()                                    \
    /**/

Now you can format strings like this:

int main() {
    int i = 123;
    std::string message = MAKE_STRING("i = " << i);
    std::cout << message << std::endl; // prints: "i = 123"
}

Python decorators in classes

import functools


class Example:

    def wrapper(func):
        @functools.wraps(func)
        def wrap(self, *args, **kwargs):
            print("inside wrap")
            return func(self, *args, **kwargs)
        return wrap

    @wrapper
    def method(self):
        print("METHOD")

    wrapper = staticmethod(wrapper)


e = Example()
e.method()

How to remove only 0 (Zero) values from column in excel 2010

You shouldn't use a space " " instead of "0" because the excel deal with the space as a value.

So, the answer is with the option by (Ctrl + F). Then, click the options and put in the Find with "0". Next, click (Match entire cell contents. Finally, replaced or replaced all up to you.

This solution can give more also. You can use (*) before or after the values to delete any parts you want.

Thanks.

go get results in 'terminal prompts disabled' error for github private repo

It complains because it needs to use ssh instead of https but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh instead of https. a simple way to do this by running the following:

git config --global --add url."[email protected]:".insteadOf "https://github.com/"

or if you already use ssh with git in your machine, you can safely edit ~/.gitconfig and add the following line at the very bottom

Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
        insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/
  • If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.

  • For more information on how to add ssh to your github account, please visit this page.

Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.

To do this, you need to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.

The variable is a comma-separated list of patterns (same syntax of Go's path.Match) of module path prefixes. For example,

export GOPRIVATE=*.corp.example.com,github.com/mycompany/*

Or

go env -w GOPRIVATE=github.com/mycompany/*
  • For more information on how to solve private packages/modules checksum validation issues, please read this article.
  • For more information about go 13 modules and new enhancements, please check out Go 1.13 Modules Release notes.

One last thing not to forget to mention, you can still configure go get to authenticate and fetch over https, all you need to do is to add the following line to $HOME/.netrc

machine github.com login USERNAME password APIKEY
  • For GitHub accounts, the password can be a personal access tokens.
  • For more information on how to do this, please check Go FAQ page.

I hope this helps the community and saves others' time to solve described issues quickly. please feel free to leave a comment in case you want more support or help.

How to call a method with a separate thread in Java?

Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression

  new Thread(() -> {
                      "code here"
            }).start();

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

Test if a property is available on a dynamic variable

Here is the other way:

using Newtonsoft.Json.Linq;

internal class DymanicTest
{
    public static string Json = @"{
            ""AED"": 3.672825,
            ""AFN"": 56.982875,
            ""ALL"": 110.252599,
            ""AMD"": 408.222002,
            ""ANG"": 1.78704,
            ""AOA"": 98.192249,
            ""ARS"": 8.44469
}";

    public static void Run()
    {
        dynamic dynamicObject = JObject.Parse(Json);

        foreach (JProperty variable in dynamicObject)
        {
            if (variable.Name == "AMD")
            {
                var value = variable.Value;
            }
        }
    }
}

C# windows application Event: CLR20r3 on application start

To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable

log4j configuration via JVM argument(s)?

Generally, as long as your log4j.properties file is on the classpath, Log4j should just automatically pick it up at JVM startup.

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

Is it possible to write to the console in colour in .NET?

Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour

Dynamically add item to jQuery Select2 control that uses AJAX

Extending on Bumptious Q Bangwhistle's answer:

$('#select2').append($('<option>', { 
    value: item,
    text : item 
})).select2();

This would add the new options into the <select> tags and lets select2 re-render it.

How to get child element by ID in JavaScript?

$(selectedDOM).find();

function looking for all dom objects inside the selected DOM. i.e.

<div id="mainDiv">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <div id="innerDiv">
         <a href="#">link</a>
         <p>Paragraph 3</p>
    </div>
</div>

here if you write;

$("#mainDiv").find("p");

you will get tree p elements together. On the other side,

$("#mainDiv").children("p");

Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

JSON Invalid UTF-8 middle byte

client text protocol

POST http://127.0.0.1/bom/create HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: 50ecfbfe-741f-4a2b-a3d3-cdf162ada27f
Host: 127.0.0.1
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 405

{
  "fwoid": 1,
  "list": [
    {
      "bomIndex": "10001",
      "desc": "?GH 1.25 13pin ???? ??",
      "pn": "084.0001.0036",
      "preUse": 1,
      "type": "?? ???-??PCB??"
    },
     {
      "bomIndex": "10002",
      "desc": "????-?????",
      "pn": "Z.08.013.0051",
      "preUse": 1,
      "type": "E060A0302301"
    }
  ]
}
HTTP/1.1 200 OK
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:23:42 GMT
Content-Length: 40

{"code":"0","message":"BOM????"}

a springboot Controller code as below:

@PostMapping("/bom/create")
@ApiOperation(value = "??BOM")
@BusinessOperation(module = "BOM",methods = "??BOM")
public JsonResult save(@RequestBody BOMSaveQuery query)
{
    return bomService.saveBomList(query);
}

when i debug on loopback interface,it works ok. while deploy on internet server via bat command, i got an error

ServletInvocableHandlerMethod - Could not resolve parameter [0] in public XXXController.save(com.h2.mes.query.BOMSaveQuery): JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
 at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
 at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])]
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - Completed 400 BAD_REQUEST
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}

add a jvm arguement works for me. java -Dfile.encoding=UTF-8

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

According to this thread, there is no way in Firebug to view what events are attached to listeners on a DOM element.

It looks like the best you can do is either what tj111 suggests, or you could right-click the element in the HTML viewer, and click "Log Events" so you can see which events are firing for a particular DOM element. I suppose one could do that to see what events could be firing off particular functions.

Spring Boot - Loading Initial Data

You can use something like this:

@SpringBootApplication  
public class Application {

@Autowired
private UserRepository userRepository;

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
InitializingBean sendDatabase() {
    return () -> {
        userRepository.save(new User("John"));
        userRepository.save(new User("Rambo"));
      };
   }
}

How do I get the web page contents from a WebView?

If you are working on kitkat and above, you can use the chrome remote debugging tools to find all the requests and responses going in and out of your webview and also the the html source code of the page viewed.

https://developer.chrome.com/devtools/docs/remote-debugging

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

Drop all tables whose names begin with a certain string

select 'DROP TABLE ' + name from sysobjects
where type = 'U' and sysobjects.name like '%test%'

-- Test is the table name

PHP cURL custom headers

Use the following Syntax

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.5',
    'Cache-Control: no-cache',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Host: www.example.com',
    'Referer: http://www.example.com/index.php', //Your referrer address
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
    'X-MicrosoftAjax: Delta=true'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

Seeing the console's output in Visual Studio 2010?

You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.

How to embed an autoplaying YouTube video in an iframe?

August 2018 I didn't find a working example on the iframe implementation. Other questions were related to Chrome only, which gave it away a little.

You'll have to mute sound mute=1 in order to autoplay on Chrome. FF and IE seem to be working just fine using autoplay=1 as parameter.

<iframe src="//www.youtube.com/embed/{{YOUTUBE-ID}}?autoplay=1&mute=1" name="youtube embed" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Role/Purpose of ContextLoaderListener in Spring?

I believe its real use comes when you want to have more than one config files or you have xyz.xml file instead of applicationcontext.xml for eg

<context-param><param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/training-service.xml, /WEB-INF/training-data.xml</param-value> </context-param>

Another approach to ContextLoaderListener is using ContextLoaderServlet like below

<servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Intro to GPU programming

Take a look at the ATI Stream Computing SDK. It is based on BrookGPU developed at Stanford.

In the future all GPU work will be standardized using OpenCL. It's an Apple-sponsored initiative that will be graphics card vendor neutral.

How do browser cookie domains work?

Although there is the RFC 2965 (Set-Cookie2, had already obsoleted RFC 2109) that should define the cookie nowadays, most browsers don’t fully support that but just comply to the original specification by Netscape.

There is a distinction between the Domain attribute value and the effective domain: the former is taken from the Set-Cookie header field and the latter is the interpretation of that attribute value. According to the RFC 2965, the following should apply:

  • If the Set-Cookie header field does not have a Domain attribute, the effective domain is the domain of the request.
  • If there is a Domain attribute present, its value will be used as effective domain (if the value does not start with a . it will be added by the client).

Having the effective domain it must also domain-match the current requested domain for being set; otherwise the cookie will be revised. The same rule applies for choosing the cookies to be sent in a request.


Mapping this knowledge onto your questions, the following should apply:

  • Cookie with Domain=.example.com will be available for www.example.com
  • Cookie with Domain=.example.com will be available for example.com
  • Cookie with Domain=example.com will be converted to .example.com and thus will also be available for www.example.com
  • Cookie with Domain=example.com will not be available for anotherexample.com
  • www.example.com will be able to set cookie for example.com
  • www.example.com will not be able to set cookie for www2.example.com
  • www.example.com will not be able to set cookie for .com

And to set and read a cookie for/by www.example.com and example.com, set it for .www.example.com and .example.com respectively. But the first (.www.example.com) will only be accessible for other domains below that domain (e.g. foo.www.example.com or bar.www.example.com) where .example.com can also be accessed by any other domain below example.com (e.g. foo.example.com or bar.example.com).

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

What are best practices for multi-language database design?

What we do, is to create two tables for each multilingual object.

E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language.

In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language.

Example:

Table "Product":
----------------
ID                 : int
<any other language-neutral fields>


Table "ProductTranslations"
---------------------------
ID                 : int      (foreign key referencing the Product)
Language           : varchar  (e.g. "en-US", "de-CH")
IsDefault          : bit
ProductDescription : nvarchar
<any other localized data>

With this approach, you can handle as many languages as needed (without having to add additional fields for each new language).


Update (2014-12-14): please have a look at this answer, for some additional information about the implementation used to load multilingual data into an application.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Looking at the Volley perspective here are some advantages for your requirement:

Volley, on one hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks

Pros and cons of Volley:

So what’s nice about Volley?

  • The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.

  • NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.

  • Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.

  • Volley apparently has futures, too. Check out RequestFuture if you’re interested.

  • If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.

  • Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance )

  • Volley plays nice with the Activity life cycle.

Problems With Volley:
Since Volley is new, few things are not supported yet, but it's fixed.

  1. Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)

  2. status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley)

    Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick!

  3. it's less documented but many of the people are supporting volley in github, java like documentation can be found here. On android developer website, you may find guide for Transmitting Network Data Using Volley. And volley source code can be found at Google Git

  4. To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above)

Also you can read this Comparing Volley's image loading with Picasso

Retrofit:

It's released by Square, This offers very easy to use REST API's (Update: Voila! with NIO support)

Pros of Retrofit:

  • Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.

  • We can use it with any serialization library, with error handling.

Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2

  • version 1.6 of Retrofit with OkHttp 2.0 is now dependent on Okio to support java.io and java.nio which makes it much easier to access, store and process your data using ByteString and Buffer to do some clever things to save CPU and memory. (FYI: This reminds me of the Koush's OIN library with NIO support!) We can use Retrofit together with RxJava to combine and chain REST calls using rxObservables to avoid ugly callback chains (to avoid callback hell!!).

Cons of Retrofit for version 1.6:

  • Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support.

  • Minimum threading assistance can result call back hell if we use this in an improper way.

(All above Cons have been solved in the new version of Retrofit 2.0 beta)

========================================================================

Update:

Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):

Android Async vs Volley vs Retrofit performance benchmarks

(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)

In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. That is a massive real-world difference. In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically.

RetroFit Wins in benchmark test!

In the end, we decided to go with Retrofit for our application. Not only is it ridiculously fast, but it meshes quite well with our existing architecture. We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. Now that we have a few fragments completely converted, it’s pretty painless. There were some growing pains and issues that we had to overcome, but overall it went smoothly. In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it.

When to use Volley?!

We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! also Volley has better memory related error handling than Retrofit!

OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.

Source, credit: volley-vs-retrofit by Mr. Josh Ruesch

Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

Tkinter module not found on Ubuntu

this works for me:

from tkinter import *
root = Tk()
l = Label(root, text="Does it work")
l.pack()

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

Using jQuery to build table rows from AJAX response(json)

I do following to get JSON response from Ajax and parse without using parseJson:

$.ajax({
  dataType: 'json', <----
  type: 'GET',
  url: 'get/allworldbankaccounts.json',
  data: $("body form:first").serialize(),

If you are using dataType as Text then you need $.parseJSON(response)

What is the difference between properties and attributes in HTML?

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

wamp server mysql user id and password

By default, you can access your databases at http:// localhost/phpmyadmin using user: root and a blank password.

Once logged in PHPmyAdmin, click on the Privileges tab. and on the Add a new user link located under the User Overview table

C# Lambda expressions: Why should I use them?

Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:

using System;
using System.Linq;
using System.Linq.Expressions;


namespace ExpressionTreeThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
            var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
            Console.WriteLine(del(5)); //we are just invoking a delegate at this point
            Console.ReadKey();
        }
    }
}

This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.

Filename too long in Git for Windows

Executing git config --system core.longpaths true thrown an error to me:

"error: could not lock config file C:\Program Files (x86)\Git\mingw32/etc/gitconfig: Permission denied"

Fixed with executing the command at the global level:

git config --global core.longpaths true

How to use comparison operators like >, =, < on BigDecimal

Here is an example for all six boolean comparison operators (<, ==, >, >=, !=, <=):

BigDecimal big10 = new BigDecimal(10);
BigDecimal big20 = new BigDecimal(20);

System.out.println(big10.compareTo(big20) < -1);  // false
System.out.println(big10.compareTo(big20) <= -1); // true
System.out.println(big10.compareTo(big20) == -1); // true
System.out.println(big10.compareTo(big20) >= -1); // true
System.out.println(big10.compareTo(big20) > -1);  // false
System.out.println(big10.compareTo(big20) != -1); // false

System.out.println(big10.compareTo(big20) < 0);   // true
System.out.println(big10.compareTo(big20) <= 0);  // true
System.out.println(big10.compareTo(big20) == 0);  // false
System.out.println(big10.compareTo(big20) >= 0);  // false
System.out.println(big10.compareTo(big20) > 0);   // false
System.out.println(big10.compareTo(big20) != 0);  // true

System.out.println(big10.compareTo(big20) < 1);   // true
System.out.println(big10.compareTo(big20) <= 1);  // true
System.out.println(big10.compareTo(big20) == 1);  // false
System.out.println(big10.compareTo(big20) >= 1);  // false
System.out.println(big10.compareTo(big20) > 1);   // false
System.out.println(big10.compareTo(big20) != 1);  // true

How to set proxy for wget?

For all users of the system via the /etc/wgetrc or for the user only with the ~/.wgetrc file:

use_proxy=yes
http_proxy=127.0.0.1:8080
https_proxy=127.0.0.1:8080

or via -e options placed after the URL:

wget ... -e use_proxy=yes -e http_proxy=127.0.0.1:8080 ...

jQuery lose focus event

Use blur event to call your function when element loses focus :

$('#filter').blur(function() {
  $('#options').hide();
});

What's the console.log() of java?

The Log class:

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Outside of Android, System.out.println(String msg) is used.

Creating a custom JButton in Java

Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates.

Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text.

package test;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;

import javax.swing.JButton;
import javax.swing.JFrame;

public class MyButton extends JButton {

    private static final long serialVersionUID = 1L;

    private Color circleColor = Color.BLACK;

    public MyButton(String label) {
        super(label);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Dimension originalSize = super.getPreferredSize();
        int gap = (int) (originalSize.height * 0.2);
        int x = originalSize.width + gap;
        int y = gap;
        int diameter = originalSize.height - (gap * 2);

        g.setColor(circleColor);
        g.fillOval(x, y, diameter, diameter);
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension size = super.getPreferredSize();
        size.width += size.height;
        return size;
    }

    /*Test the button*/
    public static void main(String[] args) {
        MyButton button = new MyButton("Hello, World!");

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(button);

        frame.setVisible(true);
    }

}

Note that by overriding paintComponent that the contents of the button can be changed, but that the border is painted by the paintBorder method. The getPreferredSize method also needs to be managed in order to dynamically support changes to the content. Care needs to be taken when measuring font metrics and image dimensions.

For creating a control that you can rely on, the above code is not the correct approach. Dimensions and colours are dynamic in Swing and are dependent on the look and feel being used. Even the default Metal look has changed across JRE versions. It would be better to implement AbstractButton and conform to the guidelines set out by the Swing API. A good starting point is to look at the javax.swing.LookAndFeel and javax.swing.UIManager classes.

http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html

http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html

Understanding the anatomy of LookAndFeel is useful for writing controls: Creating a Custom Look and Feel

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

How to delete multiple values from a vector?

q <- c(1,1,2,2,3,3,3,4,4,5,5,7,7)
rm <- q[11]
remove(rm)
q
q[13] = NaN
q
q %in% 7

This sets the 13 in a vector to not a number(NAN) it shows false remove(q[c(11,12,13)]) if you try this you will see that remove function don't work on vector number. you remove entire vector but maybe not a single element.

Difference between drop table and truncate table?

DROP and TRUNC do different things:

TRUNCATE TABLE

Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.

DROP TABLE

Removes one or more table definitions and all data, indexes, triggers, constraints, and permission specifications for those tables.

As far as speed is concerned the difference should be small. And anyway if you don't need the table structure at all, certainly use DROP.

How can I discover the "path" of an embedded resource?

I use the following method to grab embedded resources:

    protected static Stream GetResourceStream(string resourcePath)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());

        resourcePath = resourcePath.Replace(@"/", ".");
        resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));

        if (resourcePath == null)
            throw new FileNotFoundException("Resource not found");

        return assembly.GetManifestResourceStream(resourcePath);
    }

I then call this with the path in the project:

GetResourceStream(@"DirectoryPathInLibrary/Filename")

Regular expressions in C: examples?

man regex.h reports there is no manual entry for regex.h, but man 3 regex gives you a page explaining the POSIX functions for pattern matching.
The same functions are described in The GNU C Library: Regular Expression Matching, which explains that the GNU C Library supports both the POSIX.2 interface and the interface the GNU C Library has had for many years.

For example, for an hypothetical program that prints which of the strings passed as argument match the pattern passed as first argument, you could use code similar to the following one.

#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_regerror (int errcode, size_t length, regex_t *compiled);

int
main (int argc, char *argv[])
{
  regex_t regex;
  int result;

  if (argc < 3)
    {
      // The number of passed arguments is lower than the number of
      // expected arguments.
      fputs ("Missing command line arguments\n", stderr);
      return EXIT_FAILURE;
    }

  result = regcomp (&regex, argv[1], REG_EXTENDED);
  if (result)
    {
      // Any value different from 0 means it was not possible to 
      // compile the regular expression, either for memory problems
      // or problems with the regular expression syntax.
      if (result == REG_ESPACE)
        fprintf (stderr, "%s\n", strerror(ENOMEM));
      else
        fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
      return EXIT_FAILURE;               
    }
  for (int i = 2; i < argc; i++)
    {
      result = regexec (&regex, argv[i], 0, NULL, 0);
      if (!result)
        {
          printf ("'%s' matches the regular expression\n", argv[i]);
        }
      else if (result == REG_NOMATCH)
        {
          printf ("'%s' doesn't the regular expression\n", argv[i]);
        }
      else
        {
          // The function returned an error; print the string 
          // describing it.
          // Get the size of the buffer required for the error message.
          size_t length = regerror (result, &regex, NULL, 0);
          print_regerror (result, length, &regex);       
          return EXIT_FAILURE;
        }
    }

  /* Free the memory allocated from regcomp(). */
  regfree (&regex);
  return EXIT_SUCCESS;
}

void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
  char buffer[length];
  (void) regerror (errcode, compiled, buffer, length);
  fprintf(stderr, "Regex match failed: %s\n", buffer);
}

The last argument of regcomp() needs to be at least REG_EXTENDED, or the functions will use basic regular expressions, which means that (for example) you would need to use a\{3\} instead of a{3} used from extended regular expressions, which is probably what you expect to use.

POSIX.2 has also another function for wildcard matching: fnmatch(). It doesn't allow to compile the regular expression, or get the substrings matching a sub-expression, but it is very specific for checking when a filename match a wildcard (e.g. it uses the FNM_PATHNAME flag).

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

SQLite - getting number of rows in a database

If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want

SELECT COALESCE(MAX(id)+1, 0) FROM words

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

Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.

From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.

Mac SQLite editor

MesaSQLite is the best I've found so far.

www.desertsandsoftware.com

Looks very promising indeed.

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

Set ANDROID_HOME environment variable in mac

MacOS

add this string in file ~/.bashrc or ~/.zshrc

export ANDROID_HOME="/Users/<userlogin>/Library/Android/sdk"

Set Icon Image in Java

I use this:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class IconImageUtilities
{
    public static void setIconImage(Window window)
    {
        try
        {
            InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
            BufferedImage bufferedImage = ImageIO.read(imageInputStream);
            window.setIconImage(bufferedImage);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }
    }
}

Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:

IconImageUtilities.setIconImage(this);

jinja2.exceptions.TemplateNotFound error

You put your template in the wrong place. From the Flask docs:

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

How to write PNG image to string with the PIL?

You can use the BytesIO class to get a wrapper around strings that behaves like a file. The BytesIO object provides the same interface as a file, but saves the contents just in memory:

import io

with io.BytesIO() as output:
    image.save(output, format="GIF")
    contents = output.getvalue()

You have to explicitly specify the output format with the format parameter, otherwise PIL will raise an error when trying to automatically detect it.

If you loaded the image from a file it has a format parameter that contains the original file format, so in this case you can use format=image.format.

In old Python 2 versions before introduction of the io module you would have used the StringIO module instead.

Remove certain characters from a string

One issue with REPLACE will be where city names contain the district name. You can use something like.

SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM   dbo.tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004' 

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Best way to check function arguments?

You can use Type Enforcement accept/returns decorators from PythonDecoratorLibrary It's very easy and readable:

@accepts(int, int, float)
def myfunc(i1, i2, i3):
    pass

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

The whole cell doesn't need to be remade. You could use the indentationLevel and indentationWidth property of tableViewCells to shift the content of your cell. Then you add your custom imageView to the left side of the cell.

Laravel: Validation unique on update

The Best Option is here try just once no need more code when unique validation on updating data

'email' => 'unique:users,email_address,' . $userId,

hereemailis field name and users is table name and email_address is table attribute name which you want unique and $userid is updating row id

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

Pass variables from servlet to jsp

You could set all the values into the response object before forwaring the request to the jsp. Or you can put your values into a session bean and access it in the jsp.

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

json_encode/json_decode - returns stdClass instead of Array in PHP

To answer the actual question:

Why does PHP turn the JSON Object into a class?

Take a closer look at the output of the encoded JSON, I've extended the example the OP is giving a little bit:

$array = array(
    'stuff' => 'things',
    'things' => array(
        'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
    )
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}

The JSON format was derived from the same standard as JavaScript (ECMAScript Programming Language Standard) and if you would look at the format it looks like JavaScript. It is a JSON object ({} = object) having a property "stuff" with value "things" and has a property "things" with it's value being an array of strings ([] = array).

JSON (as JavaScript) doesn't know associative arrays only indexed arrays. So when JSON encoding a PHP associative array, this will result in a JSON string containing this array as an "object".

Now we're decoding the JSON again using json_decode($arrayEncoded). The decode function doesn't know where this JSON string originated from (a PHP array) so it is decoding into an unknown object, which is stdClass in PHP. As you will see, the "things" array of strings WILL decode into an indexed PHP array.

Also see:


Thanks to https://www.randomlists.com/things for the 'things'

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Without resetting Visual Studio settings :

I found simply

  • ReSharper > Options > Keyboards
  • Apply Scheme button
  • Save button

Brought back my lost ReSharper keyboard commands without messing with my VS settings.

(Visual Studio Community 2017 + ReSharper Ultimate)

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

List of encodings that Node.js supports

The list of encodings that node supports natively is rather short:

  • ascii
  • base64
  • hex
  • ucs2/ucs-2/utf16le/utf-16le
  • utf8/utf-8
  • binary/latin1 (ISO8859-1, latin1 only in node 6.4.0+)

If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:

Use iconv-lite to recode files:

var iconvlite = require('iconv-lite');
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    return iconvlite.decode(content, encoding);
}

Alternatively, use iconv:

var Iconv = require('iconv').Iconv;
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    var iconv = new Iconv(encoding, 'UTF-8');
    var buffer = iconv.convert(content);
    return buffer.toString('utf8');
}

Facebook share button and custom text

We use something like this [use in one line]:

<a title="send to Facebook" 
  href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
  target="_blank">
  <span>
    <img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook 
  </span>
</a>

jQuery: selecting each td in a tr

Fully example to demonstrate how jQuery query all data in HTML table.

Assume there is a table like the following in your HTML code.

<table id="someTable">
  <thead>
    <tr>
      <td>title 0</td>
      <td>title 1</td>
      <td>title 2</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>row 0 td 0</td>
      <td>row 0 td 1</td>
      <td>row 0 td 2</td>
    </tr>
    <tr>
      <td>row 1 td 0</td>
      <td>row 1 td 1</td>
      <td>row 1 td 2</td>
    </tr>
    <tr>
      <td>row 2 td 0</td>
      <td>row 2 td 1</td>
      <td>row 2 td 2</td>
    </tr>
    <tr> ... </tr>
    <tr> ... </tr>
    ...
    <tr> ... </tr>
    <tr>
      <td>row n td 0</td>
      <td>row n td 1</td>
      <td>row n td 2</td>
    </tr>
  </tbody>
</table>

Then, The Answer, the code to print all row all column, should like this

$('#someTable tbody tr').each( (tr_idx,tr) => {
    $(tr).children('td').each( (td_idx, td) => {
        console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
    });                 
});

After running the code, the result will show

[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2

Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.

From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.

Why don’t my SVG images scale using the CSS "width" property?

You have to modify the viewBox property to change the height and the width correctly with a svg. It is in the <svg> tag of the svg.

https://developer.mozilla.org/en/docs/Web/SVG/Attribute/viewBox

Is there a difference between x++ and ++x in java?

In Java there is a difference between x++ and ++x

++x is a prefix form: It increments the variables expression then uses the new value in the expression.

For example if used in code:

int x = 3;

int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4

System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'

x++ is a postfix form: The variables value is first used in the expression and then it is incremented after the operation.

For example if used in code:

int x = 3;

int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4

System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4' 

Hope this is clear. Running and playing with the above code should help your understanding.

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

Column/Vertical selection with Keyboard in SublimeText 3

Alright, here's the best solution I've found that meets all the requirements:

  1. Download the Sublime-Text-Advanced-CSV Sublime plugin and install.
  2. Specify a delimiter for your column (default is ","), via the "CSV: Set Delimiter" command.
  3. Hit "ctrl + , s" (or select from Command Palette) and your column will be selected.

No need for mouse interaction whatsoever.

How to execute two mysql queries as one in PHP/MYSQL?

As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.

For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:

$stmt = $dbh->prepare("
    select sql_calc_found_rows * from foo limit 1 ; 
    select found_rows()");
$stmt->execute();
do {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
} while ($stmt->nextRowset());

However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.

How to make git mark a deleted and a new file as a file move?

Use git mv command to move the files, instead of the OS move commands: https://git-scm.com/docs/git-mv

Please note that git mv command only exists in Git versions 1.8.5 and up. So you may have to update your Git to use this command.

Writing files in Node.js

You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:

var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
  stream.write("My first row\n");
  stream.write("My second row\n");
  stream.end();
});

Rounding a double to turn it into an int (java)

Documentation of Math.round says:

Returns the result of rounding the argument to an integer. The result is equivalent to (int) Math.floor(f+0.5).

No need to cast to int. Maybe it was changed from the past.

How to hide code from cells in ipython notebook visualized with nbviewer?

This is now possible directly from nbconvert as of version 5.2.1: content can be filtered using the built-in template exporter exclude options. For example:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

will exclude the "input code" cells, ie the code itself. Similar options exist to exclude prompts, markdown cells, or outputs, or both inputs and outputs.

(These options should work irrespective of output format.)

How to extract text from a string using sed?

How about using grep -E?

echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'

Reading a column from CSV file using JAVA

Read the input continuously within the loop so that the variable line is assigned a value other than the initial value

while ((line = br.readLine()) !=null) {
  ...
}

Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files

Export to CSV using MVC, C# and jQuery

Respect to Biff, here's a few tweaks that let me use the method to bounce CSV from jQuery/Post against the server and come back as a CSV prompt to the user.

    [Themed(false)]
    public FileContentResult DownloadCSV()
    {

        var csvStringData = new StreamReader(Request.InputStream).ReadToEnd();

        csvStringData = Uri.UnescapeDataString(csvStringData.Replace("mydata=", ""));

        return File(new System.Text.UTF8Encoding().GetBytes(csvStringData), "text/csv", "report.csv");
    }

You'll need the unescape line if you are hitting this from a form with code like the following,

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val(data);
    $('#downloadForm').append($(input));
    $("#downloadForm").submit();

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Dynamic tabs with user-click chosen components

I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.

'@angular/core': {
  main: 'bundles/core.umd.js',
  defaultExtension: 'js'
},
'@angular/compiler': {
  main: 'bundles/compiler.umd.js',
  defaultExtension: 'js'
},
'@angular/common': {
  main: 'bundles/common.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
  main: 'bundles/platform-browser-dynamic.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser': {
  main: 'bundles/platform-browser.umd.js',
  defaultExtension: 'js'
},

https://plnkr.co/edit/kVJvI1vkzrLZJeRFsZuv?p=preview

Trying to handle "back" navigation button action in iOS

Use a custom UINavigationController subclass, which implements the shouldPop method.

In Swift:

class NavigationController: UINavigationController, UINavigationBarDelegate
{
    var shouldPopHandler: (() -> Bool)?

    func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool
    {
        if let shouldPopHandler = self.shouldPopHandler, !shouldPopHandler()
        {
            return false
        }
        self.popViewController(animated: true) // Needed!
        return true
    }
}

When set, your shouldPopHandler() will be called to decide whether the controller will be pop or not. When not set it will just get popped as usual.

It is a good idea to disable UINavigationControllers interactivePopGestureRecognizer as the gesture won't call your handler otherwise.

Initializing a list to a known number of elements in Python

Without knowing more about the problem domain, it's hard to answer your question. Unless you are certain that you need to do something more, the pythonic way to initialize a list is:

verts = []

Are you actually seeing a performance problem? If so, what is the performance bottleneck? Don't try to solve a problem that you don't have. It's likely that performance cost to dynamically fill an array to 1000 elements is completely irrelevant to the program that you're really trying to write.

The array class is useful if the things in your list are always going to be a specific primitive fixed-length type (e.g. char, int, float). But, it doesn't require pre-initialization either.

Type.GetType("namespace.a.b.ClassName") returns null

Try this method.

public static Type GetType(string typeName)
{
    var type = Type.GetType(typeName);
    if (type != null) return type;
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = a.GetType(typeName);
        if (type != null)
            return type;
    }
    return null;
}

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

Trying to mock datetime.date.today(), but not working

We can use pytest-mock (https://pypi.org/project/pytest-mock/) mocker object to mock datetime behaviour in a particular module

Let's say you want to mock date time in the following file

# File path - source_dir/x/a.py
import datetime

def name_function():
     name = datetime.now()
     return f"name_{name}"

In the test function, mocker will be added to the function when test runs

def test_name_function(mocker):
     mocker.patch('x.a.datetime')
     x.a.datetime.now.return_value = datetime(2019, 1, 1)

     actual = name_function()

     assert actual == "name_2019-01-01"

Elegant way to create empty pandas DataFrame with NaN of type float

Hope this can help!

 pd.DataFrame(np.nan, index = np.arange(<num_rows>), columns = ['A'])

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

How do you get a directory listing sorted by creation date in python?

Without changing directory:

import os    

path = '/path/to/files/'
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

print time_sorted_list

# if you want just the filenames sorted, simply remove the dir from each
sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
print sorted_filename_list

What's a clean way to stop mongod on Mac OS X?

If you installed mongodb with homebrew, there's an easier way:

List mongo job with launchctl:

launchctl list | grep mongo

Stop mongo job:

launchctl stop <job label>

(For me this is launchctl stop homebrew.mxcl.mongodb)

Start mongo job:

launchctl start <job label>

Hibernate error - QuerySyntaxException: users is not mapped [from users]

In a Spring project: I typed wrong hibernate.packagesToScan=com.okan.springdemo.entity and got this error. Now it's working well.

The type or namespace name 'DbContext' could not be found

having referenced entityframework.dll both system.data.entity worked.

How to revert multiple git commits?

I really wanted to avoid hard resets, this is what I came up with.

A -> B -> C -> D -> HEAD

To go back to A (which is 4 steps back):

git pull                  # Get latest changes
git reset --soft HEAD~4   # Set back 4 steps
git stash                 # Stash the reset
git pull                  # Go back to head
git stash pop             # Pop the reset 
git commit -m "Revert"    # Commit the changes

How to subtract X days from a date using Java calendar?

It can be done easily by the following

Calendar calendar = Calendar.getInstance();
        // from current time
        long curTimeInMills = new Date().getTime();
        long timeInMills = curTimeInMills - 5 * (24*60*60*1000);    // `enter code here`subtract like 5 days
        calendar.setTimeInMillis(timeInMills);
        System.out.println(calendar.getTime());

        // from specific time like (08 05 2015)
        calendar.set(Calendar.DAY_OF_MONTH, 8);
        calendar.set(Calendar.MONTH, (5-1));
        calendar.set(Calendar.YEAR, 2015);
        timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);
        calendar.setTimeInMillis(timeInMills);
        System.out.println(calendar.getTime());

how to change text in Android TextView

The first line of new text view is unnecessary

t=new TextView(this); 

you can just do this

TextView t = (TextView)findViewById(R.id.TextView01);

as far as a background thread that sleeps here is an example, but I think there is a timer that would be better for this. here is a link to a good example using a timer instead http://android-developers.blogspot.com/2007/11/stitch-in-time.html

    Thread thr = new Thread(mTask);
    thr.start();
}

Runnable mTask = new Runnable() {
    public void run() {
        // just sleep for 30 seconds.
                    try {
                        Thread.sleep(3000);
                        runOnUiThread(done);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    };

    Runnable done = new Runnable() {
        public void run() {
                   // t.setText("done");
            }
        };

How to position a Bootstrap popover?

Maybe you don't need this logic for a responsive behavior.

E.g.

placement: 'auto left'

Bootstrap 3 has auto value for placement. Bootstrap doc:

When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right.

How to Disable landscape mode in Android?

If you want user-settings,

then I'd recommend setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

You can change the settings from a settings menu.

I require this because my timers must correspond to what's on the screen, and rotating the screen will destroy the current activity.

How to select the row with the maximum value in each group

Using dplyr 1.0.2 there are now two ways to do this, one is long hand and the other is using the verb across():

      # create data
      ID    <- c(1,1,1,2,2,2,2,3,3)
      Value <- c(2,3,5,2,5,8,17,3,5)
      Event <- c(1,1,2,1,2,1,2,2,2)
      
      group <- data.frame(Subject=ID, pt=Value, Event=Event)

Long hand the verb is max() but note the na.rm = TRUE which is useful for examples where there are NAs as in the closed question: Merge rows in a dataframe where the rows are disjoint and contain NAs:

       group %>% 
        group_by(Subject) %>% 
        summarise(pt = max(pt, na.rm = TRUE),
                  Event = max(Event, na.rm = TRUE))

This is ok if there are only a few columns but if the table has many columns across() is useful. The examples for this verb are often with summarise(across(start_with... but in this example the columns don't start with the same characters. Either they could be changed or the positions listed:

    group %>% 
        group_by(Subject) %>% 
        summarise(across(1:ncol(group)-1, max, na.rm = TRUE, .names = "{.col}"))

Note for the verb across() 1 refers to the first column after the first actual column so using ncol(group) won't work as that is too many columns (makes it position 4 rather than 3).

How to list the properties of a JavaScript object?

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

What are the lengths of Location Coordinates, latitude and longitude?

Please check the UTM coordinate system https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

These values must be in meters for a specific map projection. For example, the peak of Mount Assiniboine (at 50°52'10"N 115°39'03"W) in UTM Zone 11 is represented by 11U 594934.108296 5636174.091274 where (594934.108296, 5636174.091274) are in meters.

Deleting a pointer in C++

int value, *ptr;

value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.

ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.

ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

Ignoring new fields on JSON objects using Jackson

@JsonIgnoreProperties(ignoreUnknown = true) worked well for me. I have a java application which runs on tomcat with jdk 1.7.

How to get client IP address in Laravel 5+

If you call this function then you easily get the client's IP address. I have already used this in my existing project:

public function getUserIpAddr(){
       $ipaddress = '';
       if (isset($_SERVER['HTTP_CLIENT_IP']))
           $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
       else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_X_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
       else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_FORWARDED'];
       else if(isset($_SERVER['REMOTE_ADDR']))
           $ipaddress = $_SERVER['REMOTE_ADDR'];
       else
           $ipaddress = 'UNKNOWN';    
       return $ipaddress;
    }

Android: How to add R.raw to project?

Here is the string to access files in raw folder. Replace filename with name of your file.

android.resource://" + getPackageName() + "/" + R.raw.filename

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

You can use the CONCAT function to do that:

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

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

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

Git Server Like GitHub?

Gitorious is an open source web interface to git that you can run on your own server, much like github:

http://getgitorious.com/

Update:

http://gitlab.org/ is another alternative now as well.

Update 2:

Gitorious has now joined with GitLab

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

How to filter multiple values (OR operation) in angularJS

The quickest solution that I've found is to use the filterBy filter from angular-filter, for example:

<input type="text" placeholder="Search by name or genre" ng-model="ctrl.search"/>   
<ul>
  <li ng-repeat="movie in ctrl.movies | filterBy: ['name', 'genre']: ctrl.search">
    {{movie.name}} ({{movie.genre}}) - {{movie.rating}}
  </li>
</ul>

The upside is that angular-filter is a fairly popular library (~2.6k stars on GitHub) which is still actively developed and maintained, so it should be fine to add it to your project as a dependency.

Difference between JSONObject and JSONArray

To understand it in a easier way, following are the diffrences between JSON object and JSON array:

Link to Tabular Difference : https://i.stack.imgur.com/GIqI9.png

JSON Array

1. Arrays in JSON are used to organize a collection of related items
   (Which could be JSON objects)
2.  Array values must be of type string, number, object, array, boolean or null
3.  Syntax: 
           [ "Ford", "BMW", "Fiat" ]
4.  JSON arrays are surrounded by square brackets []. 
    **Tip to remember**  :  Here, order of element is important. That means you have 
    to go straight like the shape of the bracket i.e. straight lines. 
   (Note :It is just my logic to remember the shape of both.) 
5.  Order of elements is important. Example:  ["Ford","BMW","Fiat"] is not 
    equal to ["Fiat","BMW","Ford"]
6.  JSON can store nested Arrays that are passed as a value.

JSON Object

1.  JSON objects are written in key/value pairs.
2.  Keys must be strings, and values must be a valid JSON data type (string, number, 
    object, array, boolean or null).Keys and values are separated by a colon.
    Each key/value pair is separated by a comma.
3.  Syntax:
         { "name":"Somya", "age":25, "car":null }
4.  JSON objects are surrounded by curly braces {} 
    Tip to remember : Here, order of element is not important. That means you can go 
    the way you like. Therefore the shape of the braces i.e. wavy. 
    (Note : It is just my logic to remember the shape of both.)
5.  Order of elements is not important. 
    Example:  { rollno: 1, firstname: 'Somya'} 
                   is equal to 
             { firstname: 'Somya', rollno: 1}
6.  JSON can store nested objects in JSON format in addition to nested arrays.

runOnUiThread in fragment

Try this: getActivity().runOnUiThread(new Runnable...

It's because:

1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

2) Fragment doesn't have runOnUiThread.

However, Activity does.

Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());

// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.

EDIT: @rciovati is right, you are in onPostExecute, that's already on the main thread.

change <audio> src with javascript

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();

How can I format bytes a cell in Excel as KB, MB, GB etc?

All the answers here supply values with powers of 10. Here is a format using proper SI units (multiples of 1024, i.e. Mebibytes, Gibibytes, and Tebibytes):

[>1099511627776]#.##,,,," TiB";[>1073741824]#.##,,," GiB";0.##,," MiB"

This supports MiB, GiB, and TiB showing two decimal places.

How do you reverse a string in place in C or C++?

If you're looking for reversing NULL terminated buffers, most solutions posted here are OK. But, as Tim Farley already pointed out, these algorithms will work only if it's valid to assume that a string is semantically an array of bytes (i.e. single-byte strings), which is a wrong assumption, I think.

Take for example, the string "año" (year in Spanish).

The Unicode code points are 0x61, 0xf1, 0x6f.

Consider some of the most used encodings:

Latin1 / iso-8859-1 (single byte encoding, 1 character is 1 byte and vice versa):

Original:

0x61, 0xf1, 0x6f, 0x00

Reverse:

0x6f, 0xf1, 0x61, 0x00

The result is OK

UTF-8:

Original:

0x61, 0xc3, 0xb1, 0x6f, 0x00

Reverse:

0x6f, 0xb1, 0xc3, 0x61, 0x00

The result is gibberish and an illegal UTF-8 sequence

UTF-16 Big Endian:

Original:

0x00, 0x61, 0x00, 0xf1, 0x00, 0x6f, 0x00, 0x00

The first byte will be treated as a NUL-terminator. No reversing will take place.

UTF-16 Little Endian:

Original:

0x61, 0x00, 0xf1, 0x00, 0x6f, 0x00, 0x00, 0x00

The second byte will be treated as a NUL-terminator. The result will be 0x61, 0x00, a string containing the 'a' character.

How to Specify "Vary: Accept-Encoding" header in .htaccess

I'm afraid Aularon didn't provide enough steps to complete the process. With a little trial and error, I was able to successfully enable Gzipping on my dedicated WHM server.

Below are the steps:

  • Run EasyApache within WHM, select Deflate within the Exhaustive Options list, and rebuild the server.

  • Once done, goto Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include, select All Versions, and then paste the mod_headers.c and mod_headers.c code (listed above in Aularon's post) on top of on another within the input field.

  • Once saved, I was seeing a 75.36% data savings on average! You can run a before and after test by using this HTTP Compression tool to see your own results: http://www.whatsmyip.org/http_compression/

Hope this works for you all!

  • Matt

How do I close an open port from the terminal on the Mac?

  1. Find out the process ID (PID) which is occupying the port number (e.g., 5955) you would like to free

    sudo lsof -i :5955
    
  2. Kill the process which is currently using the port using its PID

    sudo kill -9 PID
    

PermissionError: [Errno 13] Permission denied

I faced a similar problem. I am using Anaconda on windows and I resolved it as follows: 1) search for "Anaconda prompt" from the start menu 2) Right click and select "Run as administrator" 3) The follow the installation steps...

This takes care of the permission issues

Tkinter understanding mainloop

tk.mainloop() blocks. It means that execution of your Python commands halts there. You can see that by writing:

while 1:
    ball.draw()
    tk.mainloop()
    print("hello")   #NEW CODE
    time.sleep(0.01)

You will never see the output from the print statement. Because there is no loop, the ball doesn't move.

On the other hand, the methods update_idletasks() and update() here:

while True:
    ball.draw()
    tk.update_idletasks()
    tk.update()

...do not block; after those methods finish, execution will continue, so the while loop will execute over and over, which makes the ball move.

An infinite loop containing the method calls update_idletasks() and update() can act as a substitute for calling tk.mainloop(). Note that the whole while loop can be said to block just like tk.mainloop() because nothing after the while loop will execute.

However, tk.mainloop() is not a substitute for just the lines:

tk.update_idletasks()
tk.update()

Rather, tk.mainloop() is a substitute for the whole while loop:

while True:
    tk.update_idletasks()
    tk.update()

Response to comment:

Here is what the tcl docs say:

Update idletasks

This subcommand of update flushes all currently-scheduled idle events from Tcl's event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk's redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you're in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)

APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:

So update_idletasks() causes some subset of events to be processed that update() causes to be processed.

From the update docs:

update ?idletasks?

The update command is used to bring the application “up to date” by entering the Tcl event loop repeatedly until all pending events (including idle callbacks) have been processed.

If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.

KBK (12 February 2000) -- My personal opinion is that the [update] command is not one of the best practices, and a programmer is well advised to avoid it. I have seldom if ever seen a use of [update] that could not be more effectively programmed by another means, generally appropriate use of event callbacks. By the way, this caution applies to all the Tcl commands (vwait and tkwait are the other common culprits) that enter the event loop recursively, with the exception of using a single [vwait] at global level to launch the event loop inside a shell that doesn't launch it automatically.

The commonest purposes for which I've seen [update] recommended are:

  1. Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window's geometry. See Centering a window for an alternative.

What's wrong with update? There are several answers. First, it tends to complicate the code of the surrounding GUI. If you work the exercises in the Countdown program, you'll get a feel for how much easier it can be when each event is processed on its own callback. Second, it's a source of insidious bugs. The general problem is that executing [update] has nearly unconstrained side effects; on return from [update], a script can easily discover that the rug has been pulled out from under it. There's further discussion of this phenomenon over at Update considered harmful.

.....

Is there any chance I can make my program work without the while loop?

Yes, but things get a little tricky. You might think something like the following would work:

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        while True:
           self.canvas.move(self.id, 0, -1)

ball = Ball(canvas, "red")
ball.draw()
tk.mainloop()

The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.

So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget's after() method:

from Tkinter import *
import random
import time

tk = Tk()
tk.title = "Game"
tk.resizable(0,0)
tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(1, self.draw)  #(time_delay, method_to_execute)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment
tk.mainloop()

The after() method doesn't block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:

from Tkinter import *
import random
import time

root = Tk()
root.title = "Game"
root.resizable(0,0)
root.wm_attributes("-topmost", 1)

canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

        self.canvas.bind("<Button-1>", self.canvas_onclick)
        self.text_id = self.canvas.create_text(300, 200, anchor='se')
        self.canvas.itemconfig(self.text_id, text='hello')

    def canvas_onclick(self, event):
        self.canvas.itemconfig(
            self.text_id, 
            text="You clicked at ({}, {})".format(event.x, event.y)
        )

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(50, self.draw)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment.
root.mainloop()

Base64 encoding and decoding in oracle

Solution with utl_encode.base64_encode and utl_encode.base64_decode have one limitation, they work only with strings up to 32,767 characters/bytes.

In case you have to convert bigger strings you will face several obstacles.

  • For BASE64_ENCODE the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€ stored at UTF-8, aka AL32UTF8) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB into BLOB first.
  • The same problem applies for BASE64_DECODE. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 Characters
  • Typically a BASE64-String has NEW_LINE (CR and/or LF) character each 64 characters. Such new-line characters have to be ignored while decoding.

Taking all this into consideration the full featured solution could be this one:

CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS

    blob_loc BLOB;
    clob_trim CLOB;
    res CLOB;

    lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
    dest_offset INTEGER := 1;
    src_offset INTEGER := 1;
    read_offset INTEGER := 1;
    warning INTEGER;
    ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);

    amount INTEGER := 1440; -- must be a whole multiple of 4
    buffer RAW(1440);
    stringBuffer VARCHAR2(1440);
    -- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient

BEGIN

    IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN 
        RETURN NULL;
    ELSIF ClobLen<= 32000 THEN
        RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
    END IF;        
    -- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger    

    -- Remove all NEW_LINE from base64 string
    ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
    DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
    LOOP
        EXIT WHEN read_offset > ClobLen;
        stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
        DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
        read_offset := read_offset + amount;
    END LOOP;

    read_offset := 1;
    ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
    DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
    LOOP
        EXIT WHEN read_offset > ClobLen;
        buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
        DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
        read_offset := read_offset + amount;
    END LOOP;

    DBMS_LOB.CREATETEMPORARY(res, TRUE);
    DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset,  DBMS_LOB.DEFAULT_CSID, lang_context, warning);

    DBMS_LOB.FREETEMPORARY(blob_loc);
    DBMS_LOB.FREETEMPORARY(clob_trim);
    RETURN res;    

END DecodeBASE64;




CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS

    dest_lob BLOB;  
    lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
    dest_offset INTEGER := 1;
    src_offset INTEGER := 1;
    read_offset INTEGER := 1;
    warning INTEGER;
    ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);

    amount INTEGER := 1440; -- must be a whole multiple of 3
    -- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters 
    buffer RAW(1440);
    res CLOB := EMPTY_CLOB();

BEGIN

    IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN 
        RETURN NULL;
    ELSIF ClobLen <= 24000 THEN
        RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
    END IF;
    -- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger    

    DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
    DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
    LOOP
        EXIT WHEN read_offset >= dest_offset;
        DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
        res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));       
        read_offset := read_offset + amount;
    END LOOP;
    DBMS_LOB.FREETEMPORARY(dest_lob);
    RETURN res;

END EncodeBASE64;

Extracting specific columns from a data frame

Where df1 is your original data frame:

df2 <- subset(df1, select = c(1, 2, 5))

Inheritance and Overriding __init__ in python

Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

Finding rows that don't contain numeric data in Oracle

To get an indicator:

DECODE( TRANSLATE(your_number,' 0123456789',' ')

e.g.

SQL> select DECODE( TRANSLATE('12345zzz_not_numberee',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"contains char"

and

SQL> select DECODE( TRANSLATE('12345',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"number"

and

SQL> select DECODE( TRANSLATE('123405',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"number"

Oracle 11g has regular expressions so you could use this to get the actual number:

SQL> SELECT colA
  2  FROM t1
  3  WHERE REGEXP_LIKE(colA, '[[:digit:]]');

COL1
----------
47845
48543
12
...

If there is a non-numeric value like '23g' it will just be ignored.

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

https://material.angular.io/components/select/api

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

SO So So simple solution , go to c:/Users/user_name/.ssh/ and delete all pub / private key pairs , this way heroku will generate keys for you.

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

A comment for the top answer about setting font-size to 16px asked how that is a solution, what if you want bigger/smaller font.

I don't know about you all, but using px for font sizes is not the best way to go, you should be using em.

I ran into this issue on my responsive site where my text field is larger than 16 pixels. I had my form container set to 2rem and my input field set to 1.4em. In my mobile queries I change html font-size depending on the viewport. Since the default html is 10, my input field calculates to 28px on desktop

To remove the auto-zoom I had to change my input to 1.6em. This increased my font size to 32px. Just slightly higher and hardly noticeable. On my iPhone 4&5 I change my html font-size to 15px for portrait and back to 10px for landscape. It appeard that the sweet spot for that pixel size was 48px which is why I changed to from 1.4em (42px) to 1.6em (48px).

The thing you need to do is find the sweet spot on font-size and then convert it backwards in your rem/em sizes.

Counting words in string

I think this method is more than you want

var getWordCount = function(v){
    var matches = v.match(/\S+/g) ;
    return matches?matches.length:0;
}

What's the best way to detect a 'touch screen' device using JavaScript?

Extent jQuery support object:

jQuery.support.touch = 'ontouchend' in document;

And now you can check it anywhere, like this:

if( jQuery.support.touch )
   // do touch stuff

How to annotate MYSQL autoincrement field with JPA annotations

As you have define the id in int type at the database creation, you have to use the same data type in the model class too. And as you have defined the id to auto increment in the database, you have to mention it in the model class by passing value 'GenerationType.AUTO' into the attribute 'strategy' within the annotation @GeneratedValue. Then the code becomes as below.

@Entity
public class Operator{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  private String username;

  private String password;

  private Integer active;

  //Getters and setters...
}

How to call a button click event from another method

For people wondering, this also works for button click. For example:

private void btn_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Test")
        }

private void txb_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btn_Click(sender, e);
            }

When pressing Enter in the textfield(txb) in this case it will click the button which will active the MessageBox.

How to encrypt String in Java

Here a simple solution with only java.* and javax.crypto.* dependencies for encryption of bytes providing confidentiality and integrity. It shall be indistinguishable under a choosen plaintext attack for short messages in the order of kilobytes.

It uses AES in the GCM mode with no padding, a 128bit key is derived by PBKDF2 with lots of iterations and a static salt from the provided password. This makes sure brute forcing passwords is hard and distributes the entropy over the entire key.

A random initialisation vector (IV) is generated and will be prepended to the ciphertext. Furthermore, the static byte 0x01 is prepended as the first byte as a 'version'.

The entire message goes into the message authentication code (MAC) generated by AES/GCM.

Here it goes, zero external dependencies encryption class providing confidentiality and integrity:

package ch.n1b.tcrypt.utils;

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * This class implements AES-GCM symmetric key encryption with a PBKDF2 derived password.
 * It provides confidentiality and integrity of the plaintext.
 *
 * @author Thomas Richner
 * @created 2018-12-07
 */
public class AesGcmCryptor {

    // https://crypto.stackexchange.com/questions/26783/ciphertext-and-tag-size-and-iv-transmission-with-aes-in-gcm-mode
    private static final byte VERSION_BYTE = 0x01;
    private static final int VERSION_BYTE_LENGTH = 1;
    private static final int AES_KEY_BITS_LENGTH = 128;


    // fixed AES-GCM constants
    private static final String GCM_CRYPTO_NAME = "AES/GCM/NoPadding";
    private static final int GCM_IV_BYTES_LENGTH = 12;
    private static final int GCM_TAG_BYTES_LENGTH = 16;

    // can be tweaked, more iterations = more compute intensive to brute-force password
    private static final int PBKDF2_ITERATIONS = 1024;

    // protects against rainbow tables
    private static final byte[] PBKDF2_SALT = hexStringToByteArray("4d3fe0d71d2abd2828e7a3196ea450d4");

    public String encryptString(char[] password, String plaintext) throws CryptoException {

        byte[] encrypted = null;
        try {
            encrypted = encrypt(password, plaintext.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException //
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException //
                | InvalidKeySpecException e) {
            throw new CryptoException(e);
        }
        return byteArrayToHexString(encrypted);
    }

    public String decryptString(char[] password, String ciphertext)
            throws CryptoException {

        byte[] ct = hexStringToByteArray(ciphertext);
        byte[] plaintext = null;
        try {
            plaintext = decrypt(password, ct);
        } catch (AEADBadTagException e) {
            throw new CryptoException(e);
        } catch ( //
                NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeySpecException //
                        | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException //
                        | BadPaddingException e) {
            throw new CryptoException(e);
        }
        return new String(plaintext, StandardCharsets.UTF_8);
    }

    /**
     * Decrypts an AES-GCM encrypted ciphertext and is
     * the reverse operation of {@link AesGcmCryptor#encrypt(char[], byte[])}
     *
     * @param password   passphrase for decryption
     * @param ciphertext encrypted bytes
     * @return plaintext bytes
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws InvalidKeySpecException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws IllegalArgumentException           if the length or format of the ciphertext is bad
     * @throws CryptoException
     */
    public byte[] decrypt(char[] password, byte[] ciphertext)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

        // input validation
        if (ciphertext == null) {
            throw new IllegalArgumentException("ciphertext cannot be null");
        }

        if (ciphertext.length <= VERSION_BYTE_LENGTH + GCM_IV_BYTES_LENGTH + GCM_TAG_BYTES_LENGTH) {
            throw new IllegalArgumentException("ciphertext too short");
        }

        // the version must match, we don't decrypt other versions
        if (ciphertext[0] != VERSION_BYTE) {
            throw new IllegalArgumentException("wrong version: " + ciphertext[0]);
        }

        // input seems legit, lets decrypt and check integrity

        // derive key from password
        SecretKey key = deriveAesKey(password, PBKDF2_SALT, AES_KEY_BITS_LENGTH);

        // init cipher
        Cipher cipher = Cipher.getInstance(GCM_CRYPTO_NAME);
        GCMParameterSpec params = new GCMParameterSpec(GCM_TAG_BYTES_LENGTH * 8,
                ciphertext,
                VERSION_BYTE_LENGTH,
                GCM_IV_BYTES_LENGTH
        );
        cipher.init(Cipher.DECRYPT_MODE, key, params);

        final int ciphertextOffset = VERSION_BYTE_LENGTH + GCM_IV_BYTES_LENGTH;

        // add version and IV to MAC
        cipher.updateAAD(ciphertext, 0, ciphertextOffset);

        // decipher and check MAC
        return cipher.doFinal(ciphertext, ciphertextOffset, ciphertext.length - ciphertextOffset);
    }

    /**
     * Encrypts a plaintext with a password.
     * <p>
     * The encryption provides the following security properties:
     * Confidentiality + Integrity
     * <p>
     * This is achieved my using the AES-GCM AEAD blockmode with a randomized IV.
     * <p>
     * The tag is calculated over the version byte, the IV as well as the ciphertext.
     * <p>
     * Finally the encrypted bytes have the following structure:
     * <pre>
     *          +-------------------------------------------------------------------+
     *          |         |               |                             |           |
     *          | version | IV bytes      | ciphertext bytes            |    tag    |
     *          |         |               |                             |           |
     *          +-------------------------------------------------------------------+
     * Length:     1B        12B            len(plaintext) bytes            16B
     * </pre>
     * Note: There is no padding required for AES-GCM, but this also implies that
     * the exact plaintext length is revealed.
     *
     * @param password  password to use for encryption
     * @param plaintext plaintext to encrypt
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws InvalidKeySpecException
     */
    public byte[] encrypt(char[] password, byte[] plaintext)
            throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
            InvalidKeySpecException {

        // initialise random and generate IV (initialisation vector)
        SecretKey key = deriveAesKey(password, PBKDF2_SALT, AES_KEY_BITS_LENGTH);
        final byte[] iv = new byte[GCM_IV_BYTES_LENGTH];
        SecureRandom random = SecureRandom.getInstanceStrong();
        random.nextBytes(iv);

        // encrypt
        Cipher cipher = Cipher.getInstance(GCM_CRYPTO_NAME);
        GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_BYTES_LENGTH * 8, iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, spec);

        // add IV to MAC
        final byte[] versionBytes = new byte[]{VERSION_BYTE};
        cipher.updateAAD(versionBytes);
        cipher.updateAAD(iv);

        // encrypt and MAC plaintext
        byte[] ciphertext = cipher.doFinal(plaintext);

        // prepend VERSION and IV to ciphertext
        byte[] encrypted = new byte[1 + GCM_IV_BYTES_LENGTH + ciphertext.length];
        int pos = 0;
        System.arraycopy(versionBytes, 0, encrypted, 0, VERSION_BYTE_LENGTH);
        pos += VERSION_BYTE_LENGTH;
        System.arraycopy(iv, 0, encrypted, pos, iv.length);
        pos += iv.length;
        System.arraycopy(ciphertext, 0, encrypted, pos, ciphertext.length);

        return encrypted;
    }

    /**
     * We derive a fixed length AES key with uniform entropy from a provided
     * passphrase. This is done with PBKDF2/HMAC256 with a fixed count
     * of iterations and a provided salt.
     *
     * @param password passphrase to derive key from
     * @param salt     salt for PBKDF2 if possible use a per-key salt, alternatively
     *                 a random constant salt is better than no salt.
     * @param keyLen   number of key bits to output
     * @return a SecretKey for AES derived from a passphrase
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private SecretKey deriveAesKey(char[] password, byte[] salt, int keyLen)
            throws NoSuchAlgorithmException, InvalidKeySpecException {

        if (password == null || salt == null || keyLen <= 0) {
            throw new IllegalArgumentException();
        }
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, keyLen);
        SecretKey pbeKey = factory.generateSecret(spec);

        return new SecretKeySpec(pbeKey.getEncoded(), "AES");
    }

    /**
     * Helper to convert hex strings to bytes.
     * <p>
     * May be used to read bytes from constants.
     */
    private static byte[] hexStringToByteArray(String s) {

        if (s == null) {
            throw new IllegalArgumentException("Provided `null` string.");
        }

        int len = s.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("Invalid length: " + len);
        }

        byte[] data = new byte[len / 2];
        for (int i = 0; i < len - 1; i += 2) {
            byte b = (byte) toHexDigit(s, i);
            b <<= 4;
            b |= toHexDigit(s, i + 1);
            data[i / 2] = b;
        }
        return data;
    }

    private static int toHexDigit(String s, int pos) {
        int d = Character.digit(s.charAt(pos), 16);
        if (d < 0) {
            throw new IllegalArgumentException("Cannot parse hex digit: " + s + " at " + pos);
        }
        return d;
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    public class CryptoException extends Exception {

        public CryptoException(Throwable cause) {
            super(cause);
        }
    }
}

Here the entire project with a nice CLI: https://github.com/trichner/tcrypt

Edit: now with appropriate encryptString and decryptString

How to log SQL statements in Spring Boot?

Log in to standard output

Add to application.properties

### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.

Using Logging Framework

Add to application.properties

### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

remove script tag from HTML content

An example modifing ctf0's answer. This should only do the preg_replace once but also check for errors and block char code for forward slash.

$str = '<script> var a - 1; <&#47;script>'; 

$pattern = '/(script.*?(?:\/|&#47;|&#x0002F;)script)/ius';
$replace = preg_replace($pattern, '', $str); 
return ($replace !== null)? $replace : $str;  

If you are using php 7 you can use the null coalesce operator to simplify it even more.

$pattern = '/(script.*?(?:\/|&#47;|&#x0002F;)script)/ius'; 
return (preg_replace($pattern, '', $str) ?? $str); 

Reset all changes after last commit in git

First, reset any changes

This will undo any changes you've made to tracked files and restore deleted files:

git reset HEAD --hard

Second, remove new files

This will delete any new files that were added since the last commit:

git clean -fd

Files that are not tracked due to .gitignore are preserved; they will not be removed

Warning: using -x instead of -fd would delete ignored files. You probably don't want to do this.

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I had the same error and I solved it with MultiDex, like described on this link : https://developer.android.com/studio/build/multidex.html


Sometimes it is not enough just to enable MultiDex.

If any class that's required during startup is not provided in the primary DEX file, then your app crashes with the error java.lang.NoClassDefFoundError. https://developer.android.com/studio/build/multidex#keep

FirebaseInitProvider is required during startup.

So you must manually specify FirebaseInitProvider as required in the primary DEX file.

build.gradle file

android {
    buildTypes {
        release {
            multiDexKeepFile file('multidex-config.txt')
            ...
        }
    }
}

multidex-config.txt (in the same directory as the build.gradle file)

com/google/firebase/provider/FirebaseInitProvider.class

How to import an excel file in to a MySQL database

You could use DocChow, a very intuitive GIU for importing Excel into MySQL, and it's free on most common platforms (including Linux).

More especially if you are concerned about date, datetime datatypes, DocChow easily handles datatypes. If you are working with multiple Excel spreadsheets that you want to import into one MySQL table DocChow does the dirty work.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.

Documentation is at http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping

Deleting row from datatable in C#

This question will give you good insights on how to delete a record from a DataTable:

DataTable, How to conditionally delete rows

It would look like this:

DataRow[] drr = dt.Select("Student=' " + id + " ' "); 
foreach (var row in drr)
   row.Delete();

Don't forget that if you want to update your database, you are going to need to call the Update command. For more information on that, see this link:

http://www.codeguru.com/forum/showthread.php?t=471027

MySQL my.ini location

You have to look I the folder C:\Program Files\MySQL\MySQL Server 5.5 but there is a problem. When you perform an MSI install of MySQL, my.ini is not created. There will be sample .ini files in that folder. In order to use one of them, say my-medium.ini, you need to do the following before a MySQL restart:

cd C:\Program Files\MySQL\MySQL Server 5.5
copy my-medium.ini my.ini
net stop mysql
net start mysql

Once, you do this, my.ini can be read by C:\Program Files\MySQL\MySQL Server 5.5\bin\mysql.exe.

How to install Boost on Ubuntu

Get the version of Boost that you require. This is for 1.55 but feel free to change or manually download yourself:

wget -O boost_1_55_0.tar.gz https://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.tar.gz/download
tar xzvf boost_1_55_0.tar.gz
cd boost_1_55_0/

Get the required libraries, main ones are icu for boost::regex support:

sudo apt-get update
sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev libbz2-dev libboost-all-dev

Boost's bootstrap setup:

./bootstrap.sh --prefix=/usr/

Then build it with:

./b2

and eventually install it:

sudo ./b2 install

AngularJS disable partial caching on dev machine

As others have said, defeating caching completely for dev purposes can be done easily without changing code: use a browser setting or a plugin. Outside of dev, to defeat Angular template caching of route-based templates, remove the template URL from the cache during $routeChangeStart (or $stateChangeStart, for UI Router) as Shayan showed. However, that does NOT affect the caching of templates loaded by ng-include, because those templates are not loaded through the router.

I wanted to be able to hotfix any template, including those loaded by ng-include, in production and have users receive the hotfix in their browser quickly, without having to reload the entire page. I'm also not concerned about defeating HTTP caching for templates. The solution is to intercept every HTTP request that the app makes, ignore those that are not for my app's .html templates, then add a param to the template's URL that changes every minute. Note that the path-checking is specific to the path of your app's templates. To get a different interval, change the math for the param, or remove the % completely to get no caching.

// this defeats Angular's $templateCache on a 1-minute interval
// as a side-effect it also defeats HTTP (browser) caching
angular.module('myApp').config(function($httpProvider, ...) {
    $httpProvider.interceptors.push(function() {
        return {
            'request': function(config) {
                config.url = getTimeVersionedUrl(config.url);
                return config;
            }
        };
    });

    function getTimeVersionedUrl(url) {
        // only do for html templates of this app
        // NOTE: the path to test for is app dependent!
        if (!url || url.indexOf('a/app/') < 0 || url.indexOf('.html') < 0) return url;
        // create a URL param that changes every minute
        // and add it intelligently to the template's previous url
        var param = 'v=' + ~~(Date.now() / 60000) % 10000; // 4 unique digits every minute
        if (url.indexOf('?') > 0) {
            if (url.indexOf('v=') > 0) return url.replace(/v=[0-9](4)/, param);
            return url + '&' + param;
        }
        return url + '?' + param;
    }

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

Modifying a subset of rows in a pandas dataframe

Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc

here is a working example

>>> import pandas as pd 
>>> import numpy as np 
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
>>> 

Explanation:

As explained in the doc here, .loc is primarily label based, but may also be used with a boolean array.

So, what we are doing above is applying df.loc[row_index, column_index] by:

  • Exploiting the fact that loc can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index
  • Exploiting the fact loc is also label based to select the column using the label 'B' in the column_index

We can use logical, condition or any operation that returns a series of booleans to construct the array of booleans. In the above example, we want any rows that contain a 0, for that we can use df.A == 0, as you can see in the example below, this returns a series of booleans.

>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df 
   A  B
0  0  2
1  1  0
2  0  5
>>> df.A == 0 
0     True
1    False
2     True
Name: A, dtype: bool
>>> 

Then, we use the above array of booleans to select and modify the necessary rows:

>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN

For more information check the advanced indexing documentation here.

MySQL Select last 7 days

Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:

SELECT 
    p1.kArtikel, 
    p1.cName, 
    p1.cKurzBeschreibung, 
    p1.dLetzteAktualisierung, 
    p1.dErstellt, 
    p1.cSeo,
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad  
FROM 
    tartikel AS p1 INNER JOIN tartikelpict AS p2 
    ON p1.kArtikel = p2.kArtikel
WHERE
  DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
  AND p2.nNr = 1
ORDER BY 
  p1.kArtikel DESC
LIMIT
    100;

How to set an HTTP proxy in Python 2.7?

You can try downloading the Windows binaries for pip from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip.

For using pip to download other modules, see @Ben Burn's answer.

When do you use varargs in Java?

In Java doc of Var-Args it is quite clear the usage of var args:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

about usage it says:

"So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "

How do I change the background color of a plot made with ggplot2

To avoid deprecated opts and theme_rect use:

myplot + theme(panel.background = element_rect(fill='green', colour='red'))

To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):

theme_jack <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            axis.text = element_text(colour = "white"),
            axis.title.x = element_text(colour = "pink", size=rel(3)),
            axis.title.y = element_text(colour = "blue", angle=45),
            panel.background = element_rect(fill="green"),
            panel.grid.minor.y = element_line(size=3),
            panel.grid.major = element_line(colour = "orange"),
            plot.background = element_rect(fill="red")
    )   
}

To make your custom theme the default when ggplot is called in future, without masking:

theme_set(theme_jack())

If you want to change an element of the currently set theme:

theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))

To store the current default theme as an object:

theme_pink <- theme_get()

Note that theme_pink is a list whereas theme_jack was a function. So to return the theme to theme_jack use theme_set(theme_jack()) whereas to return to theme_pink use theme_set(theme_pink).

You can replace theme_gray by theme_bw in the definition of theme_jack if you prefer. For your custom theme to resemble theme_bw but with all gridlines (x, y, major and minor) turned off:

theme_nogrid <- function (base_size = 12, base_family = "") {
    theme_bw(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            panel.grid = element_blank()
    )   
}

Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.

theme_map <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.ticks.length=unit(0.3, "lines"),
            axis.ticks.margin=unit(0.5, "lines"),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            legend.background=element_rect(fill="white", colour=NA),
            legend.key=element_rect(colour="white"),
            legend.key.size=unit(1.2, "lines"),
            legend.position="right",
            legend.text=element_text(size=rel(0.8)),
            legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            panel.margin=unit(0, "lines"),
            plot.background=element_blank(),
            plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
            plot.title=element_text(size=rel(1.2)),
            strip.background=element_rect(fill="grey90", colour="grey50"),
            strip.text.x=element_text(size=rel(0.8)),
            strip.text.y=element_text(size=rel(0.8), angle=-90) 
        )   
}

Is there any quick way to get the last two characters in a string?

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

How exactly does <script defer="defer"> work?

Should be also noted that there might be problems in IE<=9 when using script defer in certain situations. More on this: https://github.com/h5bp/lazyweb-requests/issues/42

Webview load html from assets directory

You are getting the WebView before setting the Content view so the wv is probably null.

public class ViewWeb extends Activity {  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);  
            WebView wv;  
            wv = (WebView) findViewById(R.id.webView1);  
            wv.loadUrl("file:///android_asset/aboutcertified.html");   // now it will not fail here
        }  
    }

sql query with multiple where statements

This..

(
        (meta_key = 'lat' AND meta_value >= '60.23457047672217')
    OR
        (meta_key = 'lat' AND meta_value <= '60.23457047672217')
)

is the same as

(
        (meta_key = 'lat')
)

Adding it all together (the same applies to the long filter) you have this impossible WHERE clause which will give no rows because meta_key cannot be 2 values in one row

WHERE
    (meta_key = 'lat' AND meta_key = 'long' )

You need to review your operators to make sure you get the correct logic

Post an object as data using Jquery Ajax

[object Object] This means somewhere the object is being converted to a string.

Converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product + ''); 

Not converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product);

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How is TeamViewer so fast?

Oddly. but in my experience TeamViewer is not faster/more responsive than VNC, only easier to setup. I have a couple of win-boxen that I VNC over OpenVPN into (so there is another overhead layer) and that's on cheap Cable (512 up) and I find properly setup TightVNC to be much more responsive than TeamViewer to same boxen. RDP (naturally) even more so since by large part it sends GUI draw commands instead of bitmap tiles.

Which brings us to:

  1. Why are you not using VNC? There are plethora of open source solutions, and Tight is probably on top of it's game right now.

  2. Advanced VNC implementations use lossy compression and that seems to achieve better results than your choice of PNG. Also, IIRC the rest of the payload is also squashed using zlib. Bothj Tight and UltraVNC have very optimized algos, especially for windows. On top of that Tight is open-source.

  3. If win boxen are your primary target RDP may be a better option, and has an opensource implementation (rdesktop)

  4. If *nix boxen are your primary target NX may be a better option and has an open source implementation (FreeNX, albeit not as optimised as NoMachine's proprietary product).

If compressing JPEG is a performance issue for your algo, I'm pretty sure that image comparison would still take away some performance. I'd bet they use best-case compression for every specific situation ie lossy for large frames, some quick and dirty internall losless for smaller ones, compare bits of images and send only diffs of sort and bunch of other optimisation tricks.

And a lot of those tricks must be present in Tight > 2.0 since again, in my experience it beats the hell out of TeamViewer performance wyse, YMMV.

Also the choice of a JIT compiled runtime over something like C++ might take a slice from your performance edge, especially in memory constrained machines (a lot of performance tuning goes to the toilet when windows start using the pagefile intensively). And you will need memory to keep previous image states for internal comparison atop of what DF mirage gives you.

How do you get the process ID of a program in Unix or Linux using Python?

If you are not limiting yourself to the standard library, I like psutil for this.

For instance to find all "python" processes:

>>> import psutil
>>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']]
[{'name': 'python3', 'pid': 21947},
 {'name': 'python', 'pid': 23835}]

How to create a css rule for all elements except one class?

The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.

Change Circle color of radio button

@jh314 is correct. In AndroidManifest.xml,

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

In style.xml

  <!-- Application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/red</item>
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

the item name must be colorAccent,it decides the application's widgets default color.

But if you want to change the color in code,Maybe @aknay's answer is correct.

What does the C++ standard state the size of int, long type to be?

You can use:

cout << "size of datatype = " << sizeof(datatype) << endl;

datatype = int, long int etc. You will be able to see the size for whichever datatype you type.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

The above error can occur for multiple cases during servlet startup / request. Hope you check the full stack trace of the server log, If you have tomcat, you can also see the exact causes in html preview of the 500 Internal Server Error page.

Weird thing is, if you try to hit the request url a second time, you would get 404 Not Found page.

You can also debug this issue, by placing breakpoints on all the classes constructor initialization block, whose objects are created during servlet startup/request.

In my case, I didn't had javaassist jar loaded for the Weld CDI injection to work. And it shown NoClassDefFound Error.

Maven2: Best practice for Enterprise Project (EAR file)

What helped me a lot was to run the Maven archetype:generate goal and select from one of the archetypes, some of which seem to be updated regularly (in particular JBoss seems to be well maintained).

mvn archetype:generate

Hundreds of archetypes appeared in a numbered list from which to select (519 as of now!). The goal, still running, prompted me to make a selection by entering a number or entering a search string e.g.:

513: remote -> org.xwiki.commons:xwiki-commons-component-archetype
514: remote -> org.xwiki.rendering:xwiki-rendering-archetype-macro
515: remote -> org.zkoss:zk-archetype-component
516: remote -> org.zkoss:zk-archetype-webapp
517: remote -> ru.circumflex:circumflex-archetype (-)
518: remote -> se.vgregion.javg.maven.archetypes:javg-minimal-archetype (-)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains):

I entered the search string "ear," which reduced the list to only 8 items (as of today):

Choose archetype:
1: remote -> org.codehaus.mojo.archetypes:ear-j2ee14 (-)
2: remote -> org.codehaus.mojo.archetypes:ear-javaee6 (-)
3: remote -> org.codehaus.mojo.archetypes:ear-jee5 (-)
4: remote -> org.hibernate:hibernate-search-quickstart (-)
5: remote -> org.jboss.spec.archetypes:jboss-javaee6-ear-webapp 
6: remote -> org.jboss.spec.archetypes:jboss-javaee6-webapp-ear-archetype
7: remote -> org.jboss.spec.archetypes:jboss-javaee6-webapp-ear-archetype-blank
8: remote -> org.ow2.weblab.tools.maven:weblab-archetype-searcher

I selected "org.jboss.spec.archetypes:jboss-javaee6-ear-webapp" (by entering the selection "5" in this example).

Next, the goal asked me to enter the groupId, artifactId, package names, etc., and it then generated the following well-documented example application:

[pgarner@localhost Foo]$ tree
.
|-- Foo-ear
|   `-- pom.xml
|-- Foo-ejb
|   |-- pom.xml
|   `-- src
|       |-- main
|       |   |-- java
|       |   |   `-- com
|       |   |       `-- foo
|       |   |           |-- controller
|       |   |           |   `-- MemberRegistration.java
|       |   |           |-- data
|       |   |           |   `-- MemberListProducer.java
|       |   |           |-- model
|       |   |           |   `-- Member.java
|       |   |           `-- util
|       |   |               `-- Resources.java
|       |   `-- resources
|       |       |-- import.sql
|       |       `-- META-INF
|       |           |-- beans.xml
|       |           `-- persistence.xml
|       `-- test
|           |-- java
|           |   `-- com
|           |       `-- foo
|           |           `-- test
|           |               `-- MemberRegistrationTest.java
|           `-- resources
|-- Foo-web
|   |-- pom.xml
|   `-- src
|       `-- main
|           |-- java
|           |   `-- com
|           |       `-- foo
|           |           `-- rest
|           |               |-- JaxRsActivator.java
|           |               `-- MemberResourceRESTService.java
|           `-- webapp
|               |-- index.html
|               |-- index.xhtml
|               |-- resources
|               |   |-- css
|               |   |   `-- screen.css
|               |   `-- gfx
|               |       |-- banner.png
|               |       `-- logo.png
|               `-- WEB-INF
|                   |-- beans.xml
|                   |-- faces-config.xml
|                   `-- templates
|                       `-- default.xhtml
|-- pom.xml
`-- README.md

32 directories, 23 files

After reading the four POM files, which were well-commented, I had pretty much all the information I needed.

./pom.xml
./Foo-ear/pom.xml
./Foo-ejb/pom.xml
./Foo-web/pom.xml

Remove portion of a string after a certain character

$variable = substr($variable, 0, strpos($variable, "By"));

In plain english: Give me the part of the string starting at the beginning and ending at the position where you first encounter the deliminator.

The value violated the integrity constraints for the column

the point can be if you are not using valid login for linked server. Problem is on destination server side.

There are few steps to try:

  1. Align db user and login on destination server: alter user [DBUSER_of_linkedserverlogin] with login = [linkedserverlogin]

  2. recreate login on destination server used by linked server.

  3. Backup table and recreate it.

2nd resolved my issue with "The value violated the integrity constraints for the column.".

"The system cannot find the file specified"

Considering that a LocalDb instance only intended for use in development. LocalDb is not available for production servers When you deploy the final result.

I think your connection string is pointing to a LocalDb instance and you need to take certain steps to turn it into the SQL Server database. It's not just a matter of copying an mdf file either. It will possibly differ from one hosting company to another, but typically, you need to create a backup of your existing database (a .bak file) and then restore that to the hosting company's SQL Server. You should ask them where you can find instructions on deploying your database into production.

Generate random integers between 0 and 9

Best way is to use import Random function

import random
print(random.sample(range(10), 10))

or without any library import:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

here the popitems removes and returns an arbitrary value from the dictionary n.

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

Create a mocked list by mockito

When dealing with mocking lists and iterating them, I always use something like:

@Spy
private List<Object> parts = new ArrayList<>();

What does ||= (or-equals) mean in Ruby?

It means or-equals to. It checks to see if the value on the left is defined, then use that. If it's not, use the value on the right. You can use it in Rails to cache instance variables in models.

A quick Rails-based example, where we create a function to fetch the currently logged in user:

class User > ActiveRecord::Base

  def current_user
    @current_user ||= User.find_by_id(session[:user_id])
  end

end

It checks to see if the @current_user instance variable is set. If it is, it will return it, thereby saving a database call. If it's not set however, we make the call and then set the @current_user variable to that. It's a really simple caching technique but is great for when you're fetching the same instance variable across the application multiple times.

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

Remove URL parameters without refreshing page

a simple way to do this, works on any page, requires HTML 5

// get the string following the ?
var query = window.location.search.substring(1)

// is there anything there ?
if(query.length) {
   // are the new history methods available ?
   if(window.history != undefined && window.history.pushState != undefined) {
        // if pushstate exists, add a new state to the history, this changes the url without reloading the page

        window.history.pushState({}, document.title, window.location.pathname);
   }
}

Change the maximum upload file size

I had the same problem and i created a .user.ini file and put it in the directory in which the upload script was located. Than inside that file i set these these two values:

  upload_max_filesize = 40M

  post_max_size = 40M

and it worked great for me!

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

just add .col-xs-12 to your responsive image. It's should work.

How to remove \xa0 from string in Python?

There's many useful things in Python's unicodedata library. One of them is the .normalize() function.

Try:

new_str = unicodedata.normalize("NFKD", unicode_str)

Replacing NFKD with any of the other methods listed in the link above if you don't get the results you're after.

How do I change the color of radio buttons?

I builded another fork of @klewis' code sample to demonstrate some playing with pure css and gradients by using :before/:after pseudo elements and a hidden radio input button.

enter image description here

HTML:

sample radio buttons:
<div style="background:lightgrey;">
    <span class="radio-item">
        <input type="radio" id="ritema" name="ritem" class="true" value="ropt1" checked="checked">
        <label for="ritema">True</label>
    </span>

    <span class="radio-item">
        <input type="radio" id="ritemb" name="ritem" class="false" value="ropt2">
        <label for="ritemb">False</label>
    </span>
</div>

:

CSS:

.radio-item input[type='radio'] {
    visibility: hidden;
    width: 20px;
    height: 20px;
    margin: 0 5px 0 5px;
    padding: 0;
}
    .radio-item input[type=radio]:before {
        position: relative;
        margin: 4px -25px -4px 0;
        display: inline-block;
        visibility: visible;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        border: 2px inset rgba(150,150,150,0.75);
        background: radial-gradient(ellipse at top left, rgb(255,255,255) 0%, rgb(250,250,250) 5%, rgb(230,230,230) 95%, rgb(225,225,225) 100%);
        content: "";
    }
        .radio-item input[type=radio]:checked:after {
            position: relative;
            top: 0;
            left: 9px;
            display: inline-block;
            visibility: visible;
            border-radius: 6px;
            width: 12px;
            height: 12px;
            background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            content: "";
        }
            .radio-item input[type=radio].true:checked:after {
                background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
            }
            .radio-item input[type=radio].false:checked:after {
                background: radial-gradient(ellipse at top left, rgb(255,225,200) 0%, rgb(250,200,150) 5%, rgb(200,25,0) 95%, rgb(100,25,0) 100%);
            }
.radio-item label {
    display: inline-block;
    height: 25px;
    line-height: 25px;
    margin: 0;
    padding: 0;
}

preview: https://www.codeply.com/p/y47T4ylfib

How to make HTML element resizable using pure Javascript?

I have created a function that recieve an id of an html element and adds a border to it's right side the function is general and just recieves an id so you can copy it as it is and it will work

_x000D_
_x000D_
var myoffset;_x000D_
function resizeE(elem){_x000D_
    var borderDiv = document.createElement("div");_x000D_
    borderDiv.className = "border";_x000D_
    borderDiv.addEventListener("mousedown",myresize = function myrsize(e) {_x000D_
     myoffset = e.clientX - (document.getElementById(elem).offsetLeft + parseInt(window.getComputedStyle(document.getElementById(elem)).getPropertyValue("width")));_x000D_
     window.addEventListener("mouseup",mouseUp);_x000D_
     document.addEventListener("mousemove",mouseMove = function mousMove(e) {_x000D_
      document.getElementById(elem).style.width = `${e.clientX -  myoffset - document.getElementById(elem).offsetLeft}px`;_x000D_
  });_x000D_
 });_x000D_
    document.getElementById(elem).appendChild(borderDiv);_x000D_
}_x000D_
_x000D_
function mouseUp() {_x000D_
    document.removeEventListener("mousemove", mouseMove);_x000D_
    window.removeEventListener("mouseup",mouseUp);_x000D_
}_x000D_
_x000D_
function load() _x000D_
{_x000D_
 resizeE("resizeableDiv");_x000D_
 resizeE("anotherresizeableDiv");_x000D_
  resizeE("anotherresizeableDiv1");_x000D_
}
_x000D_
.border {_x000D_
_x000D_
  position: absolute;_x000D_
  cursor: e-resize;_x000D_
  width: 9px;_x000D_
  right: -5px;_x000D_
  top: 0;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#resizeableDiv {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #84f4c6;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #9394f4;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv1 {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #43f4f4;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv1 .border{_x000D_
  background-color: black;_x000D_
}_x000D_
#anotherresizeableDiv .border{_x000D_
  width: 30px;_x000D_
  right: -200px;_x000D_
  background-color: green;_x000D_
}
_x000D_
<body onload="load()">_x000D_
_x000D_
  <div id="resizeableDiv">change my size with the east border</div>_x000D_
  <div id="anotherresizeableDiv1">with visible border</div>_x000D_
</body>_x000D_
  <div id="anotherresizeableDiv">with editted outside border</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

resizeE("resizeableDiv"); //this calls a function that does the magic to the id inserted