Programs & Examples On #Jaxm

Setting initial values on load with Select2 with Ajax

Maybe this work for you!! This works for me...

initSelection: function (element, callback) {

            callback({ id: 1, text: 'Text' });
}

Check very well that code is correctly spelled, my issue was in the initSelection, I had initselection

jquery fill dropdown with json data

If your data is already in array form, it's really simple using jQuery:

 $(data.msg).each(function()
 {
     alert(this.value);
     alert(this.label);

     //this refers to the current item being iterated over

     var option = $('<option />');
     option.attr('value', this.value).text(this.label);

     $('#myDropDown').append(option);
 });

.ajax() is more flexible than .getJSON() - for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().

How do I fix "Expected to return a value at the end of arrow function" warning?

The easiest way only if you don't need return something it'ts just return null

Swift addsubview and remove it

You have to use the viewWithTag function to find the view with the given tag.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let point = touch.locationInView(self.view)

    if let viewWithTag = self.view.viewWithTag(100) {
        print("Tag 100")
        viewWithTag.removeFromSuperview()
    } else {
        print("tag not found")
    }
}

Tainted canvases may not be exported

If someone views on my answer, you maybe in this condition:

1. Trying to get a map screenshot in canvas using openlayers (version >= 3)
2. And viewed the example of exporting map
3. Using ol.source.XYZ to render map layer

Bingo!

Using ol.source.XYZ.crossOrigin = 'Anonymous' to solve your confuse. Or like following code:

     var baseLayer = new ol.layer.Tile({
         name: 'basic',
         source: new ol.source.XYZ({
             url: options.baseMap.basic,
             crossOrigin: "Anonymous"
         })
     });

Is there a way to cache GitHub credentials for pushing commits?

There's an easy, old-fashioned way to store user credentials in an HTTPS URL:

https://user:[email protected]/...

You can change the URL with git remote set-url <remote-repo> <URL>

The obvious downside to that approach is that you have to store the password in plain text. You can still just enter the user name (https://[email protected]/...) which will at least save you half the hassle.

You might prefer to switch to SSH or to use the GitHub client software.

relative path to CSS file

if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"

How to get the sizes of the tables of a MySQL database?

If you want a query to use currently selected database. simply copy paste this query. (No modification required)

SELECT table_name ,
  round(((data_length + index_length) / 1024 / 1024), 2) as SIZE_MB
FROM information_schema.TABLES
WHERE table_schema = DATABASE() ORDER BY SIZE_MB DESC;

Java simple code: java.net.SocketException: Unexpected end of file from server

In my case url contained wrong chars like spaces . Overall log your url and in some cases use browser.

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

  • When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.

  • By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs:

To fix this issue add following lines After Return and Before Begin statement:

READS SQL DATA
DETERMINISTIC

For Example :

CREATE FUNCTION f2()
RETURNS CHAR(36) CHARACTER SET utf8
/*ADD HERE */
READS SQL DATA
DETERMINISTIC
BEGIN

For more detail about this issue please read Here

How can I put strings in an array, split by new line?

David: Great direction, but you missed \r. this worked for me:

$array = preg_split("/(\r\n|\n|\r)/", $string);

jQuery Show-Hide DIV based on Checkbox Value

That is because you are only checking the current checkbox.

Change it to

function checkUncheck() { 
    $('.pChk').click(function() {
        if ( $('.pChk:checked').length > 0) {
            $("#ProjectListButton").show();
        } else {
            $("#ProjectListButton").hide();
        }
    }); 
}

to check if any of the checkboxes is checked (lots of checks in this line..).

reference: http://api.jquery.com/checked-selector/

jQuery count number of divs with a certain class?

I just created this js function using the jQuery size function http://api.jquery.com/size/

function classCount(name){
  alert($('.'+name).size())
}

It alerts out the number of times the class name occurs in the document.

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

How exactly does the python any() function work?

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True

Algorithm to detect overlapping periods

This is my solution:

public static bool OverlappingPeriods(DateTime aStart, DateTime aEnd,
                                      DateTime bStart, DateTime bEnd)
{
    if (aStart > aEnd)
        throw new ArgumentException("A start can not be after its end.");

    if(bStart > bEnd)
        throw new ArgumentException("B start can not be after its end.");

    return !((aEnd < bStart && aStart < bStart) ||
                (bEnd < aStart && bStart < aStart));
}

I unit tested it with 100% coverage.

Mysql password expired. Can't connect

Just open MySQL Workbench and choose [Instance] Startup/Shutdown and click on start server. It worked for me

Does bootstrap 4 have a built in horizontal divider?

Here are some custom utility classes:

_x000D_
_x000D_
hr.dashed {
    border-top: 2px dashed #999;
}

hr.dotted {
    border-top: 2px dotted #999;
}

hr.solid {
    border-top: 2px solid #999;
}


hr.hr-text {
  position: relative;
    border: none;
    height: 1px;
    background: #999;
}

hr.hr-text::before {
    content: attr(data-content);
    display: inline-block;
    background: #fff;
    font-weight: bold;
    font-size: 0.85rem;
    color: #999;
    border-radius: 30rem;
    padding: 0.2rem 2rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}



/*
*
* ==========================================
* FOR DEMO PURPOSES
* ==========================================
*
*/

body {
    min-height: 100vh;
    background-color: #fff; 
    color: #333;
}
.text-uppercase {
  letter-spacing: .1em;
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">

<div class="container py-5">
    <!-- For Demo Purpose -->
    <header class="py-5 text-center">
        <h1 class="display-4">Bootstrap Divider</h1>
        <p class="lead mb-0">Some divider variants using &lt;hr&gt; element.    </p>
    </header>


    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="mb-4">
                <h6 class=" text-uppercase">Dashed</h6>
                <!-- Dashed divider -->
                <hr class="dashed">
            </div>
            <div class="mb-4">
                <h6 class=" text-uppercase">Dotted</h6>
                <!-- Dotted divider -->
                <hr class="dotted">
            </div>
            <div class="mb-4">
                <h6 class="text-uppercase">Solid</h6>
                <!-- Solid divider -->
                <hr class="solid">
            </div>
            <div class="mb-4">
                <h6 class=" text-uppercase">Text content</h6>
                <!-- Gradient divider -->
                <hr data-content="AND" class="hr-text">
            </div>
           
        </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Here is my solution:

/^(2[0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (0[0-9]|1[0-9]|2[0123])\:([012345][0-9])\:([012345][0-9])$/u

Disable vertical scroll bar on div overflow: auto

If you want to accomplish the same in Gecko (NS6+, Mozilla, etc) and IE4+ simultaneously, I believe this should do the trick:V

body {
overflow: -moz-scrollbars-vertical;
overflow-x: hidden;
overflow-y: auto;
}

This will be applied to entire body tag, please update it to your relevant css and apply this properties.

How to quickly and conveniently create a one element arraylist

Yet another alternative is double brace initialization, e.g.

new ArrayList<String>() {{ add(s); }};

but it is inefficient and obscure. Therefore only suitable:

  • in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
  • and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.

How can I uninstall Ruby on ubuntu?

If you used rbenv to install it, you can use

rbenv versions 

to see which versions you have installed.

Then, use the uninstall command:

rbenv uninstall [-f|--force] <version>

for example:

rbenv uninstall 2.4.0  # Uninstall Ruby 2.4.0

If you installed Rails, it will be removed, too.

Convert UTC to local time in Rails 3

Don't know why but in my case it doesn't work the way suggested earlier. But it works like this:

Time.now.change(offset: "-3000")

Of course you need to change offset value to yours.

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

Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers

How to allocate aligned memory only using the standard library?

We do this sort of thing all the time for Accelerate.framework, a heavily vectorized OS X / iOS library, where we have to pay attention to alignment all the time. There are quite a few options, one or two of which I didn't see mentioned above.

The fastest method for a small array like this is just stick it on the stack. With GCC / clang:

 void my_func( void )
 {
     uint8_t array[1024] __attribute__ ((aligned(16)));
     ...
 }

No free() required. This is typically two instructions: subtract 1024 from the stack pointer, then AND the stack pointer with -alignment. Presumably the requester needed the data on the heap because its lifespan of the array exceeded the stack or recursion is at work or stack space is at a serious premium.

On OS X / iOS all calls to malloc/calloc/etc. are always 16 byte aligned. If you needed 32 byte aligned for AVX, for example, then you can use posix_memalign:

void *buf = NULL;
int err = posix_memalign( &buf, 32 /*alignment*/, 1024 /*size*/);
if( err )
   RunInCirclesWaivingArmsWildly();
...
free(buf);

Some folks have mentioned the C++ interface that works similarly.

It should not be forgotten that pages are aligned to large powers of two, so page-aligned buffers are also 16 byte aligned. Thus, mmap() and valloc() and other similar interfaces are also options. mmap() has the advantage that the buffer can be allocated preinitialized with something non-zero in it, if you want. Since these have page aligned size, you will not get the minimum allocation from these, and it will likely be subject to a VM fault the first time you touch it.

Cheesy: Turn on guard malloc or similar. Buffers that are n*16 bytes in size such as this one will be n*16 bytes aligned, because VM is used to catch overruns and its boundaries are at page boundaries.

Some Accelerate.framework functions take in a user supplied temp buffer to use as scratch space. Here we have to assume that the buffer passed to us is wildly misaligned and the user is actively trying to make our life hard out of spite. (Our test cases stick a guard page right before and after the temp buffer to underline the spite.) Here, we return the minimum size we need to guarantee a 16-byte aligned segment somewhere in it, and then manually align the buffer afterward. This size is desired_size + alignment - 1. So, In this case that is 1024 + 16 - 1 = 1039 bytes. Then align as so:

#include <stdint.h>
void My_func( uint8_t *tempBuf, ... )
{
    uint8_t *alignedBuf = (uint8_t*) 
                          (((uintptr_t) tempBuf + ((uintptr_t)alignment-1)) 
                                        & -((uintptr_t) alignment));
    ...
}

Adding alignment-1 will move the pointer past the first aligned address and then ANDing with -alignment (e.g. 0xfff...ff0 for alignment=16) brings it back to the aligned address.

As described by other posts, on other operating systems without 16-byte alignment guarantees, you can call malloc with the larger size, set aside the pointer for free() later, then align as described immediately above and use the aligned pointer, much as described for our temp buffer case.

As for aligned_memset, this is rather silly. You only have to loop in up to 15 bytes to reach an aligned address, and then proceed with aligned stores after that with some possible cleanup code at the end. You can even do the cleanup bits in vector code, either as unaligned stores that overlap the aligned region (providing the length is at least the length of a vector) or using something like movmaskdqu. Someone is just being lazy. However, it is probably a reasonable interview question if the interviewer wants to know whether you are comfortable with stdint.h, bitwise operators and memory fundamentals, so the contrived example can be forgiven.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

when I run mockito test occurs WrongTypeOfReturnValue Exception

In my case the bean has been initialized using @Autowired annotation instead of @MockBean

So in this way mocking of DAOs and Services throws such exception

How do I declare a two dimensional array?

And I like this way:

$cars = array
  (
  array("Volvo",22),
  array("BMW",15),
  array("Saab",5),
  array("Land Rover",17)
  );

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

Calculating days between two dates with Java

Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.

Minimal working example:

import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class DateTestCase {

    public static void main(String[] args) {

        System.out.print("Insert first date: ");
        Scanner s = new Scanner(System.in);
        String firstdate = s.nextLine();
        System.out.print("Insert second date: ");
        String seconddate = s.nextLine();

        // Formatter
        DateTimeFormatter dateStringFormat = DateTimeFormat
                .forPattern("dd MM yyyy");
        DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
        DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
        int days = Days.daysBetween(new LocalDate(firstTime),
                                    new LocalDate(secondTime)).getDays();
        System.out.println("Days between the two dates " + days);
    }
}

How to save SELECT sql query results in an array in C# Asp.net

A great alternative that hasn't been mentioned is to use the entity framework, which uses an object that is the table - to get data into an array you can do things like:

var rows = db.someTable.SqlQuery("SELECT col1,col2 FROM  someTable").ToList().ToArray();

for info on getting started with Entity Framework see https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

Magento - How to add/remove links on my account navigation?

Most of the above work, but for me, this was the easiest.

Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.

http://www.magentocommerce.com/magento-connect/frontend-links-manager.html

PHP cURL HTTP CODE return 0

Try this:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

How can I disable a specific LI element inside a UL?

I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

_x000D_
_x000D_
a.noclick       {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
_x000D_
_x000D_

Node.js quick file server (static files over HTTP)

Install express using npm: https://expressjs.com/en/starter/installing.html

Create a file named server.js at the same level of your index.html with this content:

var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);

If you wish to put it in a different location, set the path on the third line:

server.use('/', express.static(__dirname + '/public'));

CD to the folder containing your file and run node from the console with this command:

node server.js

Browse to localhost:8080

Vertical alignment of text and icon in button

There is one rule that is set by font-awesome.css, which you need to override.

You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline; by default and which I've corrected here:

<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:

enter image description here

I've downsized the font-size of the icon above in this instance to 30px, as it feels too big at 40px for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:

enter image description here

symfony2 : failed to write cache directory

Maybe you forgot to change the permissions of app/cache app/log

I'm using Ubuntu so

sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs

Hope it helps..

Convert Json string to Json object in Swift 4

I tried the solutions here, and as? [String:AnyObject] worked for me:

do{
    if let json = stringToParse.data(using: String.Encoding.utf8){
        if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
            let id = jsonData["id"] as! String
            ...
        }
    }
}catch {
    print(error.localizedDescription)

}

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

Select first 10 distinct rows in mysql

SELECT * 
FROM people 
WHERE names ='SMITH'
ORDER BY names asc
limit 10

If you need add group by clause. If you search Smith you would have to sort on something else.

new Image(), how to know if image 100% loaded or not?

Using the Promise pattern:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling the function we can handle its response or error quite neatly.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

JSON.stringify output to div in pretty print way

Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

_x000D_
_x000D_
var data = {_x000D_
  "data": {_x000D_
    "x": "1",_x000D_
    "y": "1",_x000D_
    "url": "http://url.com"_x000D_
  },_x000D_
  "event": "start",_x000D_
  "show": 1,_x000D_
  "id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
_x000D_
_x000D_

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.

NotSupportedException: Specified method is not supported. 

For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:

public async Task<IActionResult> Index(WebhookRequest request)
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // this won't fix your string empty problems
    // because exception will be thrown
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var body = await reader.ReadToEndAsync();

    // Do stuff
}

You'll need to take your model binding out of the method parameters, and manually bind yourself:

public async Task<IActionResult> Index()
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // You shouldn't need this line anymore.
    // reader.BaseStream.Seek(0, SeekOrigin.Begin);

    // You now have the body string raw
    var body = await reader.ReadToEndAsync();

    // As well as a bound model
    var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}

It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...

CSS - Make divs align horizontally

Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.

It's important to note that the container should not wrap if the elements MUST display horizontally: white-space: nowrap

PostgreSQL error: Fatal: role "username" does not exist

Manually creating a DB cluster solved it in my case.

For some reason, when I installed postgres, the "initial DB" wasn't created. Executing initdb did the trick for me.

This solution is provided in the PostgreSQL Wiki - First steps:

initdb

Typically installing postgres to your OS creates an "initial DB" and starts the postgres server daemon running. If not then you'll need to run initdb

php foreach with multidimensional array

You can use array_walk_recursive:

array_walk_recursive($array, function ($item, $key) {
    echo "$key holds $item\n";
});

javascript check for not null

It is possibly because the value of val is actually the string "null" rather than the value null.

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

How to use PHP to connect to sql server

if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file

extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll

im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll

if you are using xampp version 5.5 dll files is not included in the link...hope it helps

How to set selected index JComboBox by value

for example

enter image description here

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class ComboboxExample {

    private JFrame frame = new JFrame("Test");
    private JComboBox comboBox = new JComboBox();

    public ComboboxExample() {
        createGui();
    }

    private void createGui() {
        comboBox.addItem("One");
        comboBox.addItem("Two");
        comboBox.addItem("Three");
        JButton button = new JButton("Show Selected");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem());
                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        comboBox.requestFocus();
                        comboBox.requestFocusInWindow();
                    }
                });
            }
        });
        JButton button1 = new JButton("Append Items");
        button1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                appendCbItem();
            }
        });
        JButton button2 = new JButton("Reduce Items");
        button2.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                reduceCbItem();
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(4, 1));
        frame.add(comboBox);
        frame.add(button);
        frame.add(button1);
        frame.add(button2);
        frame.setLocation(200, 200);
        frame.pack();
        frame.setVisible(true);
        selectFirstItem();
    }

    public void appendCbItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.addItem("Four");
                comboBox.addItem("Five");
                comboBox.addItem("Six");
                comboBox.setSelectedItem("Six");
                requestCbFocus();
            }
        });
    }

    public void reduceCbItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.removeItem("Four");
                comboBox.removeItem("Five");
                comboBox.removeItem("Six");
                selectFirstItem();
            }
        });
    }

    public void selectFirstItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.setSelectedIndex(0);
                requestCbFocus();
            }
        });
    }

    public void requestCbFocus() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.requestFocus();
                comboBox.requestFocusInWindow();
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboboxExample comboboxExample = new ComboboxExample();
            }
        });
    }
}

Difference between \w and \b regular expression meta characters

\w matches a word character. \b is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)

\w matches a, b, c, d, e, and f in "abc def"
\b matches the (zero-width) position before a, after c, before d, and after f in "abc def"

See: http://www.regular-expressions.info/reference.html/

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

I think groupby should work.

df.groupby(['A', 'B']).max()['C']

If you need a dataframe back you can chain the reset index call.

df.groupby(['A', 'B']).max()['C'].reset_index()

How to remove default chrome style for select Input?

input:-webkit-autofill { background: #fff !important; }

How to prevent text in a table cell from wrapping

I came to this question needing to prevent text wrapping at the hyphen.

This is how I did it:

<td><nobr>Table Text</nobr></td>

Reference:

How to prevent line break at hyphens on all browsers

How to beautifully update a JPA entity in Spring Data?

So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.

Normally, you have the following workflow:

  1. User requests his data from server and obtains them in UI;
  2. User corrects his data and sends it back to server with already present ID;
  3. On server you obtain DTO with updated data by user, find it in DB by ID (otherwise throw exception) and transform DTO -> Entity with all given data, foreign keys, etc...
  4. Then you just merge it, or if using Spring Data invoke save(), which in turn will merge it (see this thread);

P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.

P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

how can I display tooltip or item information on mouse over?

The simplest way to get tooltips in most browsers is to set some text in the title attribute.

eg.

<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />

produces (hover your mouse over the image):

a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg

Title attributes can be applied to most HTML elements.

Generating CSV file for Excel, how to have a newline inside a value

This will not work if you try to import the file into EXCEL.

Associate the file extension csv with EXCEL.EXE so you will be able to invoke EXCEL by double-clicking the csv file.

Here I place some text followed by the NewLine Char followed by some more text AND enclosing the whole string with double quotes.

Do not use a CR since EXCEL will place part of the string in the next cell.

""text" + NL + "text""

When you invoke EXCEL, you will see this. You may have to auto size the height to see it all. Where the line breaks will depend on the width of the cell.

2

DATE

Here's the code in Basic

CHR$(34,"2", 10,"DATE", 34)

Converting camel case to underscore case in ruby

Short oneliner for CamelCases when you have spaces also included (doesn't work correctly if you have a word inbetween with small starting-letter):

a = "Test String"
a.gsub(' ', '').underscore

  => "test_string"

How to generate a QR Code for an Android application?

Maybe this old topic but i found this library is very helpful and easy to use

QRGen

example for using it in android

 Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);

Repeat command automatically in Linux

Watch every 5 seconds ...

watch -n 5 ls -l

If you wish to have visual confirmation of changes, append --differences prior to the ls command.

According to the OSX man page, there's also

The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed. The -t or --no-title option turns off the header showing the interval, command, and current time at the top of the display, as well as the following blank line.

Linux/Unix man page can be found here

Python Selenium accessing HTML source

By using the page source you will get the whole HTML code.
So first decide the block of code or tag in which you require to retrieve the data or to click the element..

options = driver.find_elements_by_name_("XXX")
for option in options:
    if option.text == "XXXXXX":
        print(option.text)
        option.click()

You can find the elements by name, XPath, id, link and CSS path.

Compare string with all values in list

If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ...

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]]

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None)

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

Understanding slice notation

I want to add one Hello, World! example that explains the basics of slices for the very beginners. It helped me a lot.

Let's have a list with six values ['P', 'Y', 'T', 'H', 'O', 'N']:

+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
  0   1   2   3   4   5

Now the simplest slices of that list are its sublists. The notation is [<index>:<index>] and the key is to read it like this:

[ start cutting before this index : end cutting before this index ]

Now if you make a slice [2:5] of the list above, this will happen:

        |           |
+---+---|---+---+---|---+
| P | Y | T | H | O | N |
+---+---|---+---+---|---+
  0   1 | 2   3   4 | 5

You made a cut before the element with index 2 and another cut before the element with index 5. So the result will be a slice between those two cuts, a list ['T', 'H', 'O'].

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Convert pyQt UI to python

You can use pyuic4 command on shell: pyuic4 input.ui -o output.py

perform an action on checkbox checked or unchecked event on html form

Have you tried using the JQuery change event?

$("#g01-01").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

Then you can also remove onchange="doalert(this.id)" from your checkbox :)

Edit:

I don't know if you are using JQuery, but if you're not yet using it, you will need to put the following script in your page so you can use it:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

How to Resize a Bitmap in Android?

If you already have a bitmap, you could use the following code to resize:

Bitmap originalBitmap = <original initialization>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
    originalBitmap, newWidth, newHeight, false);

How do I get the base URL with PHP?

Try the following code :

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];

jQuery changing style of HTML element

changing style with jquery

Try This

$('#selector_id').css('display','none');

You can also change multiple attribute in a single query

Try This

$('#replace-div').css({'padding-top': '5px' , 'margin' : '10px'});

How to disable copy/paste from/to EditText

You can do this by disabling the long press of the EditText

To implement it, just add the following line in the xml -

android:longClickable="false"

Python circular importing?

If you run into this issue in a fairly complex app it can be cumbersome to refactor all your imports. PyCharm offers a quickfix for this that will automatically change all usage of the imported symbols as well.

enter image description here

matplotlib does not show my drawings although I call pyplot.show()

Similar to @Rikki, I solved this problem by upgrading matplotlib with pip install matplotlib --upgrade. If you can't upgrade uninstalling and reinstalling may work.

pip uninstall matplotlib
pip install matplotlib

jQuery checkbox change and click event

Demo

Use mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});

Get all LI elements in array

QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li tag) to get all of the li present inside the div with navbar element.

_x000D_
_x000D_
    let navbar = document_x000D_
      .getElementById("navbar")_x000D_
      .querySelectorAll('li');_x000D_
_x000D_
    navbar.forEach((item, index) => {_x000D_
      console.log({ index, item })_x000D_
    });
_x000D_
   _x000D_
<div id="navbar">_x000D_
 <ul>_x000D_
  <li id="navbar-One">One</li>_x000D_
  <li id="navbar-Two">Two</li>_x000D_
  <li id="navbar-Three">Three</li>_x000D_
  <li id="navbar-Four">Four</li>_x000D_
  <li id="navbar-Five">Five</li>_x000D_
 </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Selenium WebDriver How to Resolve Stale Element Reference Exception?

I would suggest not to use @CachelookUp for Selenium WebDriver for StaleElementReferenceException.

If you are using @FindBy annotation and have @CacheLookUp, just comment it out and check.

How to add a TextView to LinearLayout in Android

try using

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info);
...
linearLayout.addView(valueTV);

also make sure that the layout params you're creating are LinearLayout.LayoutParams...

calling a java servlet from javascript

   function callServlet()


{
 document.getElementById("adminForm").action="./Administrator";
 document.getElementById("adminForm").method = "GET";
 document.getElementById("adminForm").submit();

}

<button type="submit"  onclick="callServlet()" align="center"> Register</button>

Java JTable getting the data of the selected row

if you want to get the data in the entire row, you can use this combination below

tableModel.getDataVector().elementAt(jTable.getSelectedRow());

Where "tableModel" is the model for the table that can be accessed like so

(DefaultTableModel) jTable.getModel();

this will return the entire row data.

I hope this helps somebody

How to view the stored procedure code in SQL Server Management Studio

In case you don't have permission to 'Modify', you can install a free tool called "SQL Search" (by Redgate). I use it to search for keywords that I know will be in the SP and it returns a preview of the SP code with the keywords highlighted.

Ingenious! I then copy this code into my own SP.

How to exit an application properly

Application.Exit
    End

will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.

Best regrads,

Dynamic Height Issue for UITableView Cells (Swift)

This strange bug was solved through Interface Builder parameters as the other answers did not resolve the issue.

All I did was make the default label size larger than the content potentially could be and have it reflected in the estimatedRowHeight height too. Previously, I set the default row height in Interface Builder to 88px and reflected it like so in my controller viewDidLoad():

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0

But that didn't work. So I realized that content wouldn't ever become larger than maybe 100px, so I set the default cell height to 108px (larger than the potential content) and reflected it like so in the controller viewDidLoad():

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 108.0

This actually allowed the code to shrink down the initial labels to the correct size. In other words, it never expanded out to a larger size, but could always shrink down... Also, no additional self.tableView.reloadData() was needed in viewWillAppear().

I know this does not cover highly variable content sizes, but this worked in my situation where the content had a maximum possible character count.

Not sure if this is a bug in Swift or Interface Builder but it works like a charm. Give it a try!

spark submit add multiple jars in classpath

For --driver-class-path option you can use : as delimeter to pass multiple jars. Below is the example with spark-shell command but I guess the same should work with spark-submit as well

    spark-shell --driver-class-path /path/to/example.jar:/path/to/another.jar

Spark version: 2.2.0

Create stacked barplot where each stack is scaled to sum to 100%

prop.table is a nice friendly way of obtaining proportions of tables.

m <- matrix(1:4,2)

 m
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Leaving margin blank gives you proportions of the whole table

 prop.table(m, margin=NULL)
     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

Giving it 1 gives you row proportions

 prop.table(m, 1)
      [,1]      [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667

And 2 is column proportions

 prop.table(m, 2)
          [,1]      [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286

How to move Jenkins from one PC to another

Let us say we are migrating Jenkins LTS from PC1 to PC2 (irrispective of LTS version is same of upgraded). It is easy to use ThinBackUp Plugin for migration or Upgrade of Jenkins version.

Step1: Prepare PC1 for migration

  • Manage Jenkins -> ThinbackUp -> Setting
  • Select correct options and directory for backup
  • If you need a job history and artifacts need to be added then please select 'Back build results' option as well.

enter image description here

  • Go back click on Backup Now.

enter image description here

Note: This Thinbackup will also take Plugin Backup which is optional.

  • Check the ThinbackUp folder must have a folder with current date and timestamp. (wait for couple of minutes it might take some time.)
  • You are ready with your back, .zip it and copy to PARTICULAR (which will be 'Backup directory') directory in PC2.
  • Unzip ThinbackUp zipped folder.
  • Stop Jenkins Service in PC1.

Step2: Install Jenkins (Install using .war file or Paste archived version) in PC2.

  • Create Jenkins Service using command sc create <Jenkins_PC2Servicename> binPath="<Path_to_Jenkinsexe>/jenkins.exe"
  • Modify JENKINS_HOME/jenkins.xml if needed in PC2.
  • Run windows service <Jenkins_PC2Servicename> in PC2
  • Manage Jenkins -> ThinbackUp -> Setting
  • Make sure that you PERTICULAR path from step1 as Backup Directory in ThinBackup settings.
  • ThinbackUp -> Restore will give you a Dropdown list, choose a right backup (identify with date and timestamp).

enter image description here

  • Wait for some minutes and you have latest backup configurations including jobs history and plugins in PC2.
  • In case if there are additional changes needed in JENKINS_HOME/Jenkins.xml (coming from PC1 ThinbackUp which is not needed) then this modification need to do manually.

NOTE: If you are using Database setting of SCM in your Jenkins jobs then you need to take extra care as all SCM plugins do not support to carry Database settings with the help of ThinbackUp plugin. e.g. If you are using PTC Integrity SCM Plugin, and some Jenkins jobs are using DB using Integrity, then it will create a directory JENKINS_Home/IntegritySCM, ThinbackUp will not include this DB while taking backup.

Solution: Directly Copy this JENKINS_Home/IntegritySCM folder from PC1 to PC2.

jQuery Refresh/Reload Page if Ajax Success after time

I prefer this way Using ajaxStop + setInterval,, this will refresh the page after any XHR[ajax] request in the same page

    $(document).ajaxStop(function() {
        setInterval(function() {
            location.reload();
        }, 3000);
    });

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Position Relative vs Absolute?

Relative : Relative to it’s current position, but can be moved. Or A RELATIVE positioned element is positioned relative to ITSELF.

Absolute : An ABSOLUTE positioned element is positioned relative to IT'S CLOSEST POSITIONED PARENT. if one is present, then it works like fixed.....relative to the window.

<div style="position:relative"> <!--2nd parent div-->
    <div>   <!--1st parent div-->
        <div style="position:absolute;left:10px;....."> <!--Middle div-->
          Md. Arif
       </div>
    </div>
</div>

Here, 2nd parent div position is relative so the middle div will changes it's position with respect to 2nd parent div. If 1st parent div position would relative then the Middle div would changes it's position with respect to 1st parent div. Details

Converting string to Date and DateTime

If you want to get the last day of the current month you can do it with the following code.

$last_day_this_month  = date('F jS Y', strtotime(date('F t Y')));

Java: using switch statement with enum under subclass

Change it to this:

switch (enumExample) {
    case VALUE_A: {
        //..
        break;
    }
}

The clue is in the error. You don't need to qualify case labels with the enum type, just its value.

Switch case with conditions

What you are doing is to look for (0) or (1) results.

(cnt >= 10 && cnt <= 20) returns either true or false.

--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--

How to check if a table is locked in sql server

You can use the sys.dm_tran_locks view, which returns information about the currently active lock manager resources.

Try this

 SELECT 
     SessionID = s.Session_id,
     resource_type,   
     DatabaseName = DB_NAME(resource_database_id),
     request_mode,
     request_type,
     login_time,
     host_name,
     program_name,
     client_interface_name,
     login_name,
     nt_domain,
     nt_user_name,
     s.status,
     last_request_start_time,
     last_request_end_time,
     s.logical_reads,
     s.reads,
     request_status,
     request_owner_type,
     objectid,
     dbid,
     a.number,
     a.encrypted ,
     a.blocking_session_id,
     a.text       
 FROM   
     sys.dm_tran_locks l
     JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
     LEFT JOIN   
     (
         SELECT  *
         FROM    sys.dm_exec_requests r
         CROSS APPLY sys.dm_exec_sql_text(sql_handle)
     ) a ON s.session_id = a.session_id
 WHERE  
     s.session_id > 50

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

Text in Border CSS HTML

Yes, but it's not a div, it's a fieldset

_x000D_
_x000D_
fieldset {
    border: 1px solid #000;
}
_x000D_
<fieldset>
  <legend>AAA</legend>
</fieldset>
_x000D_
_x000D_
_x000D_

Using classes with the Arduino

I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

class AMLed
{
    private:
          uint8_t _ledPin;
          long _turnOffTime;

    public:
          AMLed(uint8_t pin);
          void setOn();
          void setOff();
          // Turn the led on for a given amount of time (relies
          // on a call to check() in the main loop()).
          void setOnForTime(int millis);
          void check();
};

And here is the main source

AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
    pinMode(_ledPin, OUTPUT);
}

void AMLed::setOn()
{
    digitalWrite(_ledPin, HIGH);
}

void AMLed::setOff()
{
    digitalWrite(_ledPin, LOW);
}

void AMLed::setOnForTime(int p_millis)
{
    _turnOffTime = millis() + p_millis;
    setOn();
}

void AMLed::check()
{
    if (_turnOffTime != 0 && (millis() > _turnOffTime))
    {
        _turnOffTime = 0;
        setOff();
    }
}

It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

To use, I simply do something like this in the .pde file:

#include "AM_Led.h"

#define TIME_LED    12   // The port for the LED

AMLed test(TIME_LED);

Maven Unable to locate the Javac Compiler in:

None of the current answers helped me here. We were getting something like:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
    #.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar

This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib in the path. Our tools.jar is in $JAVA_HOME/lib/tools.jar not in $JAVA_HOME/../lib/tools.jar.

Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <fork>true</fork>  <!-- not sure if this is also needed -->
      <executable>${JAVA_HOME}/bin/javac</executable>
      <!--        ^^^^^^^^^^^^^^^^^^^^^^ -->
    </configuration>
  </plugin>

By pointing the executable to the right place this at least got past our compilation failures.

Sorting HashMap by values

In Java 8:

Map<Integer, String> sortedMap = 
     unsortedMap.entrySet().stream()
    .sorted(Entry.comparingByValue())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                              (e1, e2) -> e1, LinkedHashMap::new));

jQuery replace one class with another

You can use .removeClass and .addClass. More in http://api.jquery.com.

How create Date Object with values in java

I think the best way would be using a SimpleDateFormat object.

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

run Android SDK Manager as administrator. that solved my problem

sudo android

How to remove any URL within a string in Python

Python script:

import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)

Output:

text1
text2
text3
text4
text5
text6

Test this code here.

Tablix: Repeat header rows on each page not working - Report Builder 3.0

Another way to accomplish this if you still have that issue is by doing the following :

  • Clear all the Table header text leave it empty.
  • On the Reports “Header” section add textboxes inside a rectangle , each textbox will represent a column header for the table.
  • As this rectangle is on the Reports Header section it will display on all report pages.

Thanks, Sufian.

How to remove trailing whitespaces with sed?

To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"

jQuery: Check if button is clicked

$('#submit1, #submit2').click(function () {
   if (this.id == 'submit1') {
      alert('Submit 1 clicked');
   }
   else if (this.id == 'submit2') {
      alert('Submit 2 clicked');
   }
});

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

ERROR 2006 (HY000): MySQL server has gone away

For Drupal 8 users looking for solution for DB import failure:

At end of sql dump file there can commands inserting data to "webprofiler" table. That's I guess some debug log file and is not really important for site to work so all this can be removed. I deleted all those inserts including LOCK TABLES and UNLOCK TABLES (and everything between). It's at very bottom of the sql file. Issue is described here:

https://www.drupal.org/project/devel/issues/2723437

But there is no solution for it beside truncating that table.

BTW I tried all solutions from answers above and nothing else helped.

Does JSON syntax allow duplicate keys in an object?

Asking for purpose, there are different answers:

Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.

However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:

To use duplicate keys to comment our JSON samples. Example:

{ "property1" : "value1", "REMARK" : "... prop1 controls ...", "property2" : "value2", "REMARK" : "... value2 raises an exception ...", }

The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.

So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.

How can I count the occurrences of a string within a file?

if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

sudo service mysql stop

sudo mysqld --skip-grant-tables &

mysql -u root mysql

Change MYSECRET with your new root password

UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;

Invoking a jQuery function after .each() has completed

I meet the same problem and I solved with a solution like the following code:

var drfs = new Array();
var external = $.Deferred();
drfs.push(external.promise());

$('itemSelector').each( function() {
    //initialize the context for each cycle
    var t = this; // optional
    var internal = $.Deferred();

    // after the previous deferred operation has been resolved
    drfs.pop().then( function() {

        // do stuff of the cycle, optionally using t as this
        var result; //boolean set by the stuff

        if ( result ) {
            internal.resolve();
        } else {
            internal.reject();
        }
    }
    drfs.push(internal.promise());
});

external.resolve("done");

$.when(drfs).then( function() {
    // after all each are resolved

});

The solution solves the following problem: to synchronize the asynchronous operations started in the .each() iteration, using Deferred object.

Linux command for extracting war file?

Using unzip

unzip -c whatever.war META-INF/MANIFEST.MF  

It will print the output in terminal.

And for extracting all the files,

 unzip whatever.war

Using jar

jar xvf test.war

Note! The jar command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).

Node - how to run app.js?

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Copy Pasting @Lichtamberg's comments to gotoalberto's answer

Works also for Java 1.8:

# in ~/.zshrc and ~/.bashrc

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home 
export PATH=$JAVA_HOME/bin:$PATH 

This fixed my issue on java 8.

Passing arguments to AsyncTask, and returning results

I dont do it like this. I find it easier to overload the constructor of the asychtask class ..

public class calc_stanica extends AsyncTask>

String String mWhateveryouwantToPass;

 public calc_stanica( String whateveryouwantToPass)
{

    this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use  whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/   ...  ...  

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

Is there a function to make a copy of a PHP array to another?

simple and makes deep copy breaking all links

$new=unserialize(serialize($old));

Find out free space on tablespace

Here is a query used by Oracle SQL Developer in its Tablespaces view

select a.tablespace_name as "Tablespace Name",
       round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
       round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
       round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
       round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
       100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
       round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from  ( select  f.tablespace_name,
               sum(f.bytes) bytes_alloc,
               sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
        from dba_data_files f
        group by tablespace_name) a,
      ( select  f.tablespace_name,
               sum(f.bytes)  bytes_free
        from dba_free_space f
        group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select 
       h.tablespace_name as tablespace_name,
       round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
       round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
       round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
       round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
       100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
       round(sum(f.maxbytes) / 1048576) max
from   sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where  p.file_id(+) = h.file_id
and    p.tablespace_name(+) = h.tablespace_name
and    f.file_id = h.file_id
and    f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

div with dynamic min-height based on browser window height

No hack or js needed. Just apply the following rule to your root element:

min-height: 100%;
height: auto;

It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.

How to check if a number is between two values?

I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values

if (500 < size && size < 600) { doStuff(); }

lodash: mapping array to object

This is probably more verbose than you want, but you're asking for a slightly complex operation so actual code might be involved (the horror).

My recommendation, with zipObject that's pretty logical:

_.zipObject(_.map(params, 'name'), _.map(params, 'input'));

Another option, more hacky, using fromPairs:

_.fromPairs(_.map(params, function(val) { return [val['name'], val['input']));

The anonymous function shows the hackiness -- I don't believe JS guarantees order of elements in object iteration, so callling .values() won't do.

How can I set the default value for an HTML <select> element?

I used this php function to generate the options, and insert it into my HTML

<?php
  # code to output a set of options for a numeric drop down list
  # parameters: (start, end, step, format, default)
  function numericoptions($start, $end, $step, $formatstring, $default)
  {
    $retstring = "";
    for($i = $start; $i <= $end; $i = $i + $step)
    {
      $retstring = $retstring . '<OPTION ';
      $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
      if($default == $i)
      {
        $retstring = $retstring . ' selected="selected"';
      }
      $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
    }

  return $retstring;
  }

?>

And then in my webpage code I use it as below;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

This is my Df contain 4 is repeated twice so here will remove repeated values.

scala> df.show
+-----+
|value|
+-----+
|    1|
|    4|
|    3|
|    5|
|    4|
|   18|
+-----+

scala> val newdf=df.dropDuplicates

scala> newdf.show
+-----+
|value|
+-----+
|    1|
|    3|
|    5|
|    4|
|   18|
+-----+

What is the difference between typeof and instanceof and when should one be used vs. the other?

Performance

typeof is faster than instanceof in situations where both are applicable.

Depending on your engine, the performance difference in favor of typeof could be around 20%. (Your mileage may vary)

Here is a benchmark testing for Array:

var subject = new Array();
var iterations = 10000000;

var goBenchmark = function(callback, iterations) {
    var start = Date.now();
    for (i=0; i < iterations; i++) { var foo = callback(); }
    var end = Date.now();
    var seconds = parseFloat((end-start)/1000).toFixed(2);
    console.log(callback.name+" took: "+ seconds +" seconds.");
    return seconds;
}

// Testing instanceof
var iot = goBenchmark(function instanceofTest(){
     (subject instanceof Array);
}, iterations);

// Testing typeof
var tot = goBenchmark(function typeofTest(){
     (typeof subject == "object");
}, iterations);

var r = new Array(iot,tot).sort();
console.log("Performance ratio is: "+ parseFloat(r[1]/r[0]).toFixed(3));

Result

instanceofTest took: 9.98 seconds.
typeofTest took: 8.33 seconds.
Performance ratio is: 1.198

How can I write a regex which matches non greedy?

The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.

Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator * - it always matches the longest possible string.

The trick then is to limit what it's allowed to match in the first place. Instead of .* you seem to be looking for

[^>]*

which still matches as many of something as possible; but the something is not just . "any character", but instead "any character which isn't >".

Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.

Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.

For example, a regular expression with a trailing context after the wildcard like .*?><br/> will jump over any nested > until it finds the trailing context (here, ><br/>) even if that requires straddling multiple > instances and newlines if you let it, where [^>]*><br/> (or even [^\n>]*><br/> if you have to explicitly disallow newline) obviously can't and won't do that.

Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.

Oracle insert if not exists statement

insert into OPT       (email,        campaign_id) 
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select                 email,        campaign_id from OPT;

If there is already a record with [email protected]/100 in OPT, the MINUS will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual record and nothing will be inserted. On the other hand, if there is no such record, the MINUS does not subract anything and the values mom@coxnet/100 will be inserted.

As p.marino has already pointed out, merge is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

How to log out user from web site using BASIC authentication?

type chrome://restart in the address bar and chrome, with all its apps that are running in background, will restart and the Auth password cache will be cleaned.

How to add many functions in ONE ng-click?

You have 2 options :

  1. Create a third method that wrap both methods. Advantage here is that you put less logic in your template.

  2. Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index) like this

    ng-click="edit($index); open()"

See here : http://jsfiddle.net/laguiz/ehTy6/

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

How to draw rounded rectangle in Android UI?

In monodroid, you can do like this for rounded rectangle, and then keeping this as a parent class, editbox and other layout features can be added.

 class CustomeView : TextView
    {
       public CustomeView (Context context, IAttributeSet ) : base (context, attrs)  
        {  
        }
       public CustomeView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)  
        {  
        }
       protected override void OnDraw(Android.Graphics.Canvas canvas)
       {
           base.OnDraw(canvas);
           Paint p = new Paint();
           p.Color = Color.White;
           canvas.DrawColor(Color.DarkOrange);

           Rect rect = new Rect(0,0,3,3);

           RectF rectF = new RectF(rect);


           canvas.DrawRoundRect( rectF, 1,1, p);



       }  
    }
}

Simple JavaScript problem: onClick confirm not preventing default action

try this:

OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'

Appending a line to a file only if it does not already exist

If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"

Number of processors/cores in command line

If you need an os independent method, works across Windows and Linux. Use python

$ python -c 'import multiprocessing as m; print m.cpu_count()'
16

Pythonic way to create a long multi-line string

Another option that I think is more readable when the code (e.g., a variable) is indented and the output string should be a one-liner (no newlines):

def some_method():

    long_string = """
A presumptuous long string
which looks a bit nicer
in a text editor when
written over multiple lines
""".strip('\n').replace('\n', ' ')

    return long_string

Fixed height and width for bootstrap carousel

Apply following style to carousel listbox.

_x000D_
_x000D_
<div class="carousel-inner" role="listbox" style=" width:100%; height: 500px !important;">_x000D_
_x000D_
..._x000D_
_x000D_
</div
_x000D_
_x000D_
_x000D_

Convert Python dictionary to JSON array

ensure_ascii=False really only defers the issue to the decoding stage:

>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "????"}
>>> json.loads(json1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.

>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} 
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

If you want to remove the support for any architecture, for example, ARMv7-s in your case, use menu Project -> Build Settings -> remove the architecture from "valid architectures".

You can use this as a temporary solution until the library has been updated. You have to remove the architecture from your main project, not from the library.

Alternatively, you can set the flag for your debug configuration's "Build Active Architecture Only" to Yes. Leave the release configuration's "Build Active Architecture Only" to No, just so you'll get a reminder before releasing that you ought to upgrade any third-party libraries you're using.

change array size

In C#, arrays cannot be resized dynamically.

  • One approach is to use System.Collections.ArrayList instead of a native array.

  • Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array.

    The generic function resizeArray (below) can be used to do that.

    public static System.Array ResizeArray (System.Array oldArray, int newSize)  
        {
          int oldSize = oldArray.Length;
          System.Type elementType = oldArray.GetType().GetElementType();
          System.Array newArray = System.Array.CreateInstance(elementType,newSize);
    
          int preserveLength = System.Math.Min(oldSize,newSize);
    
          if (preserveLength > 0)
          System.Array.Copy (oldArray,newArray,preserveLength);
    
         return newArray; 
      }  
    
     public static void Main ()  
           {
            int[] a = {1,2,3};
            a = (int[])ResizeArray(a,5);
            a[3] = 4;
            a[4] = 5;
    
            for (int i=0; i<a.Length; i++)
                  System.Console.WriteLine (a[i]); 
            }
    

How to make space between LinearLayout children?

Android now supports adding a Space view between views. It's available from 4.0 ICS onwards.

Detect iPhone/iPad purely by css

This is how I handle iPhone (and similar) devices [not iPad]:

In my CSS file:

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
   /* CSS overrides for mobile here */
}

In the head of my HTML document:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">

Anchor links in Angularjs?

You can also Navigate to HTML id from inside controller

$location.hash('id_in_html');

Oracle - How to create a materialized view with FAST REFRESH and JOINS

Have you tried it without the ANSI join ?

CREATE MATERIALIZED VIEW MV_Test
  NOLOGGING
  CACHE
  BUILD IMMEDIATE 
  REFRESH FAST ON COMMIT 
  AS
SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P 
WHERE  P.PROJECTID = V.PROJECTID

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

how to set mongod --dbpath

mongod  --port portnumber --dbpath /path_to_your_folder

By default portnumber is 27017 and path is /var/lib/mongodb

You can set your own port number and path where you want to keep all your database.

Bootstrap 4 File Input

 <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="inputGroupFile01">
    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
  </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
 <script>
$(function() {
  $(document).on('change', ':file', function() {var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');input.trigger('fileselect', [numFiles, label]);
  });
  $(document).ready( function() {
      $(':file').on('fileselect', function(event, numFiles, label) {var input = $(this).parents('.custom-file').find('.custom-file-label'),
      log = numFiles > 1 ? numFiles + ' files selected' : label;if( input.length ) {input.text(log);} else {if( log ) alert(log);}});
  });
});
 </script>
  </body>
</html>

Send JSON via POST in C# and Receive the JSON returned?

You can build your HttpContent using the combination of JObject to avoid and JProperty and then call ToString() on it when building the StringContent:

        /*{
          "agent": {                             
            "name": "Agent Name",                
            "version": 1                                                          
          },
          "username": "Username",                                   
          "password": "User Password",
          "token": "xxxxxx"
        }*/

        JObject payLoad = new JObject(
            new JProperty("agent", 
                new JObject(
                    new JProperty("name", "Agent Name"),
                    new JProperty("version", 1)
                    ),
                new JProperty("username", "Username"),
                new JProperty("password", "User Password"),
                new JProperty("token", "xxxxxx")    
                )
            );

        using (HttpClient client = new HttpClient())
        {
            var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");

            using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JObject.Parse(responseBody);
            }
        }

How to get parameters from the URL with JSP

request.getParameter("accountID") is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.

Presenting a UIAlertController properly on an iPad using iOS 8

Swift 4 and above

I have created an extension

extension UIViewController {
  public func addActionSheetForiPad(actionSheet: UIAlertController) {
    if let popoverPresentationController = actionSheet.popoverPresentationController {
      popoverPresentationController.sourceView = self.view
      popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
      popoverPresentationController.permittedArrowDirections = []
    }
  }
}

How to use:

let actionSheetVC = UIAlertController(title: "Title", message: nil, preferredStyle: .actionSheet)
addActionSheetForIpad(actionSheet: actionSheetVC)
present(actionSheetVC, animated: true, completion: nil)

How to delete history of last 10 commands in shell?

history -c will clear all histories.

AngularJS: How can I pass variables between controllers?

I like to illustrate simple things by simple examples :)

Here is a very simple Service example:


angular.module('toDo',[])

.service('dataService', function() {

  // private variable
  var _dataObj = {};

  // public API
  this.dataObj = _dataObj;
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});

And here the jsbin

And here is a very simple Factory example:


angular.module('toDo',[])

.factory('dataService', function() {

  // private variable
  var _dataObj = {};

  // public API
  return {
    dataObj: _dataObj
  };
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});

And here the jsbin


If that is too simple, here is a more sophisticated example

Also see the answer here for related best practices comments

Marker in leaflet, click event

Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
{
  alert("hi. you clicked the marker at " + e.latlng);
}

How is the default max Java heap size determined?

On Windows, you can use the following command to find out the defaults on the system where your applications runs.

java -XX:+PrintFlagsFinal -version | findstr HeapSize

Look for the options MaxHeapSize (for -Xmx) and InitialHeapSize for -Xms.

On a Unix/Linux system, you can do

java -XX:+PrintFlagsFinal -version | grep HeapSize

I believe the resulting output is in bytes.

How to scroll to bottom in a ScrollView on activity startup

Try this

    final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
    scrollview.post(new Runnable() {
       @Override
       public void run() {
         scrollview.fullScroll(ScrollView.FOCUS_DOWN);
       }
    });

How do I send an HTML Form in an Email .. not just MAILTO

I actually use ASP C# to send my emails now, with something that looks like :

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form.Count > 0)
    {
        string formEmail = "";
        string fromEmail = "[email protected]";
        string defaultEmail = "[email protected]";

        string sendTo1 = "";

        int x = 0;

        for (int i = 0; i < Request.Form.Keys.Count; i++)
        {
            formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
            formEmail += ": " + Request.Form[i] + "<br/>";
            if (Request.Form.Keys[i] == "Email")
            {
                if (Request.Form[i].ToString() != string.Empty)
                {
                    fromEmail = Request.Form[i].ToString();
                }
                formEmail += "<br/>";
            }

        }
        System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
        SmtpClient smtpClient = new SmtpClient();

        try
        {
            myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
            myMsg.IsBodyHtml = true;
            myMsg.Body = formEmail;
            myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
            myMsg.Subject = "Sent using Gmail Smtp";
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");

            smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);

        }
        catch (Exception ee)
        {
            debug.Text += ee.Message;
        }
    }
}

This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.

How to automatically redirect HTTP to HTTPS on Apache servers?

Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1

How to check if type of a variable is string?

If you do not want to depend on external libs, this works both for Python 2.7+ and Python 3 (http://ideone.com/uB4Kdc):

# your code goes here
s = ["test"];
#s = "test";
isString = False;

if(isinstance(s, str)):
    isString = True;
try:
    if(isinstance(s, basestring)):
        isString = True;
except NameError:
    pass;

if(isString):
    print("String");
else:
    print("Not String");

Error in eval(expr, envir, enclos) : object not found

i use colname(train) = paste("A", colname(train)) and it turns out to the same problem as yours.

I finally figure out that randomForest is more stingy than rpart, it can't recognize the colname with space, comma or other specific punctuation.

paste function will prepend "A" and " " as seperator with each colname. so we need to avert the space and use this sentence instead:

colname(train) = paste("A", colname(train), sep = "")

this will prepend string without space.

Convert java.util.Date to String

One Line option

This option gets a easy one-line to write the actual date.

Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not logical to use it under Java8.

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

Need to find element in selenium by css

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector(".ban.hot") has 5 matching nodes

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

Option 1: Using list items' index (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes

Example:

driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes
  • Not the native selector's way

Example:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)

Limitations

  • Not for multilanguage sites
  • Only for XPath, not for Selenium's CssSelector

Example:

driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)

Limitations

  • Not stable enough if site's structure changes
  • Only for XPath, not CssSelector

Example:

driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)

Limitations

  • Only for XPath, not CssSelector
  • Low performance
  • Tricky XPath

Example:

driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));

YouTube URL in Video Tag

The most straight forward answer to this question is: You can't.

Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/> element.

There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.

Java, How do I get current index/key in "for each" loop

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness).

However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything displayed in a normal web browser.

Some things to note:

  • You must have the Python version of Selenium RC installed for this to work, and you must have set up Selenium properly. Also this is just a template crawler. You could get much crazier and more advanced with things but I just wanted to show the basic idea. As the code stands now you will be doing two requests for any given url. One request is made by Scrapy and the other is made by Selenium. I am sure there are ways around this so that you could possibly just make Selenium do the one and only request but I did not bother to implement that and by doing two requests you get to crawl the page with Scrapy too.

  • This is quite powerful because now you have the entire rendered DOM available for you to crawl and you can still use all the nice crawling features in Scrapy. This will make for slower crawling of course but depending on how much you need the rendered DOM it might be worth the wait.

    from scrapy.contrib.spiders import CrawlSpider, Rule
    from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
    from scrapy.selector import HtmlXPathSelector
    from scrapy.http import Request
    
    from selenium import selenium
    
    class SeleniumSpider(CrawlSpider):
        name = "SeleniumSpider"
        start_urls = ["http://www.domain.com"]
    
        rules = (
            Rule(SgmlLinkExtractor(allow=('\.html', )), callback='parse_page',follow=True),
        )
    
        def __init__(self):
            CrawlSpider.__init__(self)
            self.verificationErrors = []
            self.selenium = selenium("localhost", 4444, "*chrome", "http://www.domain.com")
            self.selenium.start()
    
        def __del__(self):
            self.selenium.stop()
            print self.verificationErrors
            CrawlSpider.__del__(self)
    
        def parse_page(self, response):
            item = Item()
    
            hxs = HtmlXPathSelector(response)
            #Do some XPath selection with Scrapy
            hxs.select('//div').extract()
    
            sel = self.selenium
            sel.open(response.url)
    
            #Wait for javscript to load in Selenium
            time.sleep(2.5)
    
            #Do some crawling of javascript created content with Selenium
            sel.get_text("//div")
            yield item
    
    # Snippet imported from snippets.scrapy.org (which no longer works)
    # author: wynbennett
    # date  : Jun 21, 2011
    

Reference: http://snipplr.com/view/66998/

How to get the Full file path from URI

I had a hard time trying to figure this out on Xamarin. From the suggestions above I came up with this solution.

private string getRealPathFromURI(Android.Net.Uri contentUri)
{
    string filename = "";
    string thepath = "";
    Android.Net.Uri filePathUri;
    ICursor cursor = this.ContentResolver.Query(contentUri, null, null, null, null);

    if (cursor.MoveToFirst())
    {
        int column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
        filePathUri = Android.Net.Uri.Parse(cursor.GetString(column_index));
        filename = filePathUri.LastPathSegment;
        thepath = filePathUri.Path;
    }

    return thepath;
}

TypeError: $(...).autocomplete is not a function

In my exprience I added two Jquery libraries in my file.The versions were jquery 1.11.1 and 2.1.Suddenly I took out 2.1 Jquery from my code. Then ran it and was working for me well. After trying out the first answer. please check out your file like I said above.

How to create an integer-for-loop in Ruby?

x.times do |i|
    something(i+1)
end

awk without printing newline

awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls

print will insert a newline by default. You dont want that to happen, hence use printf instead.

Find and replace in file and overwrite file doesn't work, it empties the file

And the ed answer:

printf "%s\n" '1,$s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' w q | ed index.html

To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.

Rename a table in MySQL

According to mysql docs: "to rename TEMPORARY tables, RENAME TABLE does not work. Use ALTER TABLE instead."

So this is the most portable method:

ALTER TABLE `old_name` RENAME `new_name`;

Can you force a React component to rerender without calling setState?

In order to accomplish what you are describing please try this.forceUpdate().

Check if a string is a palindrome

If you just need to detect a palindrome, you can do it with a regex, as explained here. Probably not the most efficient approach, though...

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

How to set UTF-8 encoding for a PHP file

Html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />

vs Php:

<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />

Git: Installing Git in PATH with GitHub client for Windows

To get this to work I had to combine many of the above answers, to anyone who this might help here is my much simpler process.

If you have Windows 10 just start typing "edit environmental..." and it'll pop up right away. Click path and Edit… then paste the ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd at the end of the path already there, don't forget the ; to separate your new github path from the current path.

You do not need the guid but if you want to know how to find it open bash, type git --man-path

Regular expression for address field validation

Regex is a very bad choice for this kind of task. Try to find a web service or an address database or a product which can clean address data instead.

Related:

Convert java.util.Date to java.time.LocalDate

What's wrong with this 1 simple line?

new LocalDateTime(new Date().getTime()).toLocalDate();

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Write this in each "new activity" after you initialized your new intent->

Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();

Laravel 5 - How to access image uploaded in storage within View?

One option would be to create a symbolic link between a subfolder in your storage directory and public directory.

For example

ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars

This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.

Different between parseInt() and valueOf() in java?

From this forum:

parseInt() returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.

Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Converting JSON data to Java object

Oddly, the only decent JSON processor mentioned so far has been GSON.

Here are more good choices:

  • Jackson (Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
  • Flex-JSON -- highly configurable serialization

EDIT (Aug/2013):

One more to consider:

  • Genson -- functionality similar to Jackson, aimed to be easier to configure by developer

How can I find the dimensions of a matrix in Python?

Suppose you have a which is an array. to get the dimensions of an array you should use shape.

import numpy as np a = np.array([[3,20,99],[-13,4.5,26],[0,-1,20],[5,78,-19]])
a.shape

The output of this will be (4,3)

Reorder / reset auto increment primary key

I had the same doubts, but could not make any changes on the table, I decided doing the following having seen my ID did not exceed the maximum number setted in the variable @count:

SET @count = 40000000;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

ALTER TABLE `users` AUTO_INCREMENT = 1;

The solution takes, but it's safe and it was necessary because my table owned foreign keys with data in another table.

ng serve not detecting file changes automatically

I discovered that the dist/ folder in the project was owned by root. That is why sudo ng serve does see the changes when ng serve does not.

I removed the dist/ folder sudo rm -R dist/ and rebuild it as current user by starting the dev server ng serve and all worked again.

Get current date in Swift 3?

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

15.09.2016

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

Configuring ObjectMapper in Spring

In Spring Boot 2.2.x you need to configure it like this:

@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.build()
}

Kotlin:

@Bean
fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()

Query grants for a table in postgres

I already found it:

SELECT grantee, privilege_type 
FROM information_schema.role_table_grants 
WHERE table_name='mytable'