Programs & Examples On #Python install

How to get a responsive button in bootstrap 3

<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>

We can use btn-block for automatic responsive.

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

Dealing with HTTP content in HTTPS pages

Sometimes like in facebook apps we can not have non-secure contents in secure page. also we can not make local those contents. for example an app which will load in iFrame is not a simple content and we can not make it local.

I think we should never load http contents in https, also we should not fallback https page to http version to prevent error dialog.

the only way which will ensure user's security is to use https version of all contents, http://web.archive.org/web/20120502131549/http://developers.facebook.com/blog/post/499/

PHP - get base64 img string decode and save as jpg (resulting empty image )

$data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAADICAYAAAAQj4UaAAAcNUlEQVR4nO3dwW4cR37H8d8jzBsMXyACX4Aw7yawPBhIsDqs3kAEcolPGuQinbI6BMneLCRZ57AwJARLW8hhRcU8xA6QoaVsHGC9kVZrIVl7LYkJVootyf8cukcckjNV1T3VU1Xd3w/wBwSSmq4ecrrr3/WvKgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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jtAACgn2xL6Z7mf11m8gGgW29GfvbEaAcAAH1kYzXfMX3V+FnqswYAAACQlE3WlHxcSn2mAAAAALJgO6pW1eki8fie+QYAAAAAzrCx3JsFNo0XqiY8M98DAAAAwDJ2ccXRkJ7tTwAAAACgY0uXm53Iv7wrIx4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADrMZ1OR5999tnlzz777ApBEARBEARBZBSXp9Mp+yX1yXQ6HR0dHU2Pjo6MIAiCIAiCIDKMKUlIj0yn070M/qgIgiAIgiAIYmlMp9O91P1mREICQhAEQRAEQeQeJCA9Mp1OR9Pp9Cj1HxVBEARBEARBLIrpdHpECVbP1EnI3nQ6nRAEQRAEQRBERrE3JfkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhuv/ATiSIPBj5ipCAAAAAElFTkSuQmCC';

$data = str_replace('data:image/png;base64,', '', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

$file = 'images/'.rand() . '.png';

$success = file_put_contents($file, $data);

$data = base64_decode($data); 

$source_img = imagecreatefromstring($data);

$rotated_img = imagerotate($source_img, 90, 0); 

$file = 'images/'. rand(). '.png';

$imageSave = imagejpeg($rotated_img, $file, 10);

imagedestroy($source_img);

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

How do you fix the "element not interactable" exception?

For the html code:

test.html

<button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>

the below python code worked for me. You can just try it.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()

Convert UTC date time to local date time

I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:

getTimezoneDate = function ( e ) {

    function p(s) { return (s < 10) ? '0' + s : s; }        

    var t = new Date(0);
    t.setUTCSeconds(e);

    var d = p(t.getDate()), 
        m = p(t.getMonth()+1), 
        Y = p(t.getFullYear()),
        H = p(t.getHours()), 
        i = p(t.getMinutes()), 
        s = p(t.getSeconds());

    d =  [d, m, Y].join('/') + ' ' + [H, i, s].join(':');

    return d;

};

Circular (or cyclic) imports in Python

If you do import foo (inside bar.py) and import bar (inside foo.py), it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.

The problem is when instead you do from foo import abc (inside bar.py) and from bar import xyz (inside foo.py). Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.

How do I wait for an asynchronously dispatched block to finish?

There’s also SenTestingKitAsync that lets you write code like this:

- (void)testAdditionAsync {
    [Calculator add:2 to:2 block^(int result) {
        STAssertEquals(result, 4, nil);
        STSuccess();
    }];
    STFailAfter(2.0, @"Timeout");
}

(See objc.io article for details.) And since Xcode 6 there’s an AsynchronousTesting category on XCTest that lets you write code like this:

XCTestExpectation *somethingHappened = [self expectationWithDescription:@"something happened"];
[testedObject doSomethigAsyncWithCompletion:^(BOOL succeeded, NSError *error) {
    [somethingHappened fulfill];
}];
[self waitForExpectationsWithTimeout:1 handler:NULL];

Dealing with multiple Python versions and PIP?

for Blender:

/usr/bin $ python3.7 -m pip install irc

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

You can make it in just 1 line if you change maps order in @erickson's solution:

mapWithNotSoImportantValues.putAll( mapWithImportantValues );

In this case you replace values in mapWithNotSoImportantValues with value from mapWithImportantValues with the same keys.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:

In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.

So Hibernate as well behaves like Ashish Agarwal stated above for JPA:

OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER

(see JPA 2.1 Spec)

Add CSS box shadow around the whole DIV

Just use the below code. It will shadow surround the entire DIV

-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);

Hope this will work

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

JOptionPane - input dialog box program

One solution is to actually use an integer array instead of separate test strings:

You could loop parse the response from JOptionPane.showInputDialog into the individual elements of the array.

Arrays.sort could be used to sort them to allow you to pick out the 2 highest values.

The average can be easily calculated then by adding these 2 values & dividing by 2.

int[] testScore = new int[3];

for (int i = 0; i < testScore.length; i++) {
   testScore[i] = Integer.parseInt(JOptionPane.showInputDialog("Please input mark for test " + i + ": "));
}

Arrays.sort(testScore);
System.out.println("Average: " + (testScore[1] + testScore[2])/2.0);

What's the scope of a variable initialized in an if statement?

Yes, they're in the same "local scope", and actually code like this is common in Python:

if condition:
  x = 'something'
else:
  x = 'something else'

use(x)

Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.

In other words, Python does not have block-level scopes. Be careful, though, with examples such as

if False:
    x = 3
print(x)

which would clearly raise a NameError exception.

Get week number (in the year) from a date PHP

Today, using PHP's DateTime objects is better:

<?php
$ddate = "2012-10-18";
$date = new DateTime($ddate);
$week = $date->format("W");
echo "Weeknummer: $week";

It's because in mktime(), it goes like this:

mktime(hour, minute, second, month, day, year);

Hence, your order is wrong.

<?php
$ddate = "2012-10-18";
$duedt = explode("-", $ddate);
$date  = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]);
$week  = (int)date('W', $date);
echo "Weeknummer: " . $week;
?>

How can I make setInterval also work when a tab is inactive in Chrome?

For me it's not important to play audio in the background like for others here, my problem was that I had some animations and they acted like crazy when you were in other tabs and coming back to them. My solution was putting these animations inside if that is preventing inactive tab:

if (!document.hidden){ //your animation code here }

thanks to that my animation was running only if tab was active. I hope this will help someone with my case.

Dynamic button click event handler

You can use AddHandler to add a handler for any event.

For example, this might be:

AddHandler theButton.Click, AddressOf Me.theButton_Click

How do I perform a JAVA callback between classes?

I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.

first define a generic callback:

public interface ITypedCallback<T> {
    void execute(T type);
}

create a new ITypedCallback instance on ServerConnections instantiation:

public Server(int _address) {
    serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
    });
}

call the execute methode on the callback object.

public class ServerConnections implements Runnable {

    private ITypedCallback<Socket> callback;

    public ServerConnections(ITypedCallback<Socket> _callback) {
        callback = _callback;
    }

    @Override
    public void run() {   
        try {
            mainSocket = new ServerSocket(serverPort);
            while (true) {
                callback.execute(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

btw: I didn't check if it's 100% correct, directly coded it here.

Python: Find index of minimum item in list of floats

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

What about:

Dynamically grab the #hash

<script>
var urlhash = window.location.hash, //get the hash from url
    txthash = urlhash.replace("#", ""); //remove the #
    //alert(txthash);
</script>

<?php
$hash = "<script>document.writeln(txthash);</script>";
echo $hash;
?>

To make it more fluent:

Full Example using just Javascript and PHP

<script>
var urlhash = window.location.hash,  //get the hash from url
txthash = urlhash.replace("#", "");  //remove the #

function changehash(a,b){
   window.location.hash = b; //add hash to url
   //alert(b); //alert to test
   location.reload(); //reload page to show the current hash
}
</script>

<?php $hash = "<script>document.writeln(txthash);</script>";?>

<a onclick="changehash(this,'#hash1')" style="text-decoration: underline;cursor: pointer;" >Change to #hash1</a><br/>
<a onclick="changehash(this,'#hash2')" style="text-decoration: underline;cursor: pointer;">Change to #hash2</a><br/> 

<?php echo "This is the current hash: " . $hash; ?> 

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

It helped me to follow instructions in here:

https://packaging.python.org/guides/installing-using-linux-tools/

Debian/Ubuntu

Python 2:

sudo apt install python-pip

Python 3:

sudo apt install python3-venv python3-pip

Appending a vector to a vector

a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));

Capture iOS Simulator video for App Preview

You should use QuickTime in Yosemite to connect and record the screen of your iOS devices.

iPhone Portrait

When you finished the recording, you can use iMovie to edit the video. When you're working on an iPhone Portrait App Preview, the resolution must be 1080x1920 but iMovie can only export in 16:9 (1920x1080).

One solution would be to imported the recorded video with the resolution 1080x1920 and rotate it 90 degree. Then export the movie at 1920x1080 and rotate the exported video back 90 degrees using ffmpeg and the following command

ffmpeg -i Landscape.mp4 -vf "transpose=1" Portrait.mp4

iPad

The iPad is a little bit trickier because it requires a resolution of 1200x900 (4:3) but iMovie only exports in 16:9.

Here is what I've done.

  1. Record the movie on iPad Air in Landscape (1200x900, 4:3)
  2. Import into iMovie and export as 1920x1080, 16:9 (iPadLandscape16_9-1920x1080.mp4)
  3. Remove left and right black bars to a video with 1440x1080. The width of one bar is 240

    ffmpeg -i iPadLandscape16_9-1920x1080.mp4 -filter:v "crop=1440:1080:240:0" -c:a copy iPadLandscape4_3-1440x1080.mp4
    
  4. Scale down movie to 1220x900

    ffmpeg -i iPadLandscape4_3-1440x1080.mp4 -filter:v scale=1200:-1 -c:a copy iPadLandscape4_3-1200x900.mp4
    

Taken from my answer on the Apple Developer Forum

What is the difference between a strongly typed language and a statically typed language?

What is the difference between a strongly typed language and a statically typed language?

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.

There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that

  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.

For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because

  • Amateurs often conflate them with "static" and "dynamic".

  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.

  • Professionals can't agree on exactly what the terms mean.

  • Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".

Does one imply the other?

On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:

  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.

  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.

Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.

Converting map to struct

You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:

func FillStruct(data map[string]interface{}, result interface{}) {
    t := reflect.ValueOf(result).Elem()
    for k, v := range data {
        val := t.FieldByName(k)
        val.Set(reflect.ValueOf(v))
    }
}

Working sample: http://play.golang.org/p/PYHz63sbvL

Sending commands and strings to Terminal.app with Applescript

Here's another way, but with the advantage that it launches Terminal, brings it to the front, and creates only one window.

I like this when I want to be neatly presented with the results of my script.

tell application "Terminal"
    activate
    set shell to do script "echo 1" in window 1
    do script "echo 2" in shell
    do script "echo 3" in shell
end tell

Angular - res.json() is not a function

Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7. But the application is large and need to change res.json() in a lot of places. So I did this to have the new module with back support.

return this.http.get(this.BASE_URL + url)
      .toPromise()
      .then(data=>{
        let res = {'results': JSON.stringify(data),
        'json': ()=>{return data;}
      };
       return res; 
      })
      .catch(error => {
        return Promise.reject(error);
      });

Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

jQuery get an element by its data-id

This worked for me, in my case I had a button with a data-id attribute:

$("a").data("item-id");

Fiddle

How do I use popover from Twitter Bootstrap to display an image?

simple with generated links :) html:

<span class='preview' data-image-url="imageUrl.png" data-container="body" data-toggle="popover" data-placement="top" >preview</span>

js:

$('.preview').popover({
    'trigger':'hover',
    'html':true,
    'content':function(){
        return "<img src='"+$(this).data('imageUrl')+"'>";
    }
});

http://jsfiddle.net/A4zHC/

Exiting out of a FOR loop in a batch file?

you do not need a seperate batch file to exit a loop using exit /b if you are using call instead of goto like

call :loop

echo loop finished

goto :eof

:loop
FOR /L %%I IN (1,1,10) DO (
    echo %%I
    IF %%I==5 exit /b
)

in this case, the "exit /b" will exit the 'call' and continue from the line after 'call' So the output is this:

1
2
3
4
5
loop finished

How to remove all non-alpha numeric characters from a string in MySQL?

the alphanum function (self answered) have a bug, but I don't know why. For text "cas synt ls 75W140 1L" return "cassyntls75W1401", "L" from the end is missing some how.

Now I use

delimiter //
DROP FUNCTION IF EXISTS alphanum //
CREATE FUNCTION alphanum(prm_strInput varchar(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE v_char VARCHAR(1);
  DECLARE v_parseStr VARCHAR(255) DEFAULT ' ';
WHILE (i <= LENGTH(prm_strInput) )  DO
  SET v_char = SUBSTR(prm_strInput,i,1);
  IF v_char REGEXP  '^[A-Za-z0-9]+$' THEN 
        SET v_parseStr = CONCAT(v_parseStr,v_char);  
  END IF;
  SET i = i + 1;
END WHILE;
RETURN trim(v_parseStr);
END
//

(found on google)

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

The declaration of that method is:

public T cast(Object o)

This can also be used for array types. It would look like this:

final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

case-insensitive matching in xpath?

You mentioned that PHP solutions were acceptable, and PHP does offer a way to accomplish this even though it only supports XPath v1.0. You can extend the XPath support to allow PHP function calls.

$xpathObj = new DOMXPath($docObj);
$xpathObj->registerNamespace('php','http://php.net/xpath'); // (required)
$xpathObj->registerPhpFunctions("strtolower"); // (leave empty to allow *any* PHP function)
$xpathObj->query('//CD[php:functionString("strtolower",@title) = "empire burlesque"]');

See the PHP registerPhpFunctions documentation for more examples. It basically demonstrates that "php:function" is for boolean evaluation and "php:functionString" is for string evaluation.

Convert Java string to Time, NOT Date

java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());

Optimal way to concatenate/aggregate strings

Update: Ms SQL Server 2017+, Azure SQL Database

You can use: STRING_AGG.

Usage is pretty simple for OP's request:

SELECT id, STRING_AGG(name, ', ') AS names
FROM some_table
GROUP BY id

Read More

Well my old non-answer got rightfully deleted (left in-tact below), but if anyone happens to land here in the future, there is good news. They have implimented STRING_AGG() in Azure SQL Database as well. That should provide the exact functionality originally requested in this post with native and built in support. @hrobky mentioned this previously as a SQL Server 2016 feature at the time.

--- Old Post: Not enough reputation here to reply to @hrobky directly, but STRING_AGG looks great, however it is only available in SQL Server 2016 vNext currently. Hopefully it will follow to Azure SQL Datababse soon as well..

How to install pip for Python 3 on Mac OS X?

Install Python3 on mac

1. brew install python3
2. curl https://bootstrap.pypa.io/get-pip.py | python3
3. python3

Use pip3 to install modules

1. pip3 install ipython
2. python3 -m IPython

:)

What is a software framework?

A lot of good answers already, but let me see if I can give you another viewpoint.

Simplifying things by quite a bit, you can view a framework as an application that is complete except for the actual functionality. You plug in the functionality and PRESTO! you have an application.

Consider, say, a GUI framework. The framework contains everything you need to make an application. Indeed you can often trivially make a minimal application with very few lines of source that does absolutely nothing -- but it does give you window management, sub-window management, menus, button bars, etc. That's the framework side of things. By adding your application functionality and "plugging it in" to the right places in the framework you turn this empty app that does nothing more than window management, etc. into a real, full-blown application.

There are similar types of frameworks for web apps, for server-side apps, etc. In each case the framework provides the bulk of the tedious, repetitive code (hopefully) while you provide the actual problem domain functionality. (This is the ideal. In reality, of course, the success of the framework is highly variable.)

I stress again that this is the simplified view of what a framework is. I'm not using scary terms like "Inversion of Control" and the like although most frameworks have such scary concepts built-in. Since you're a beginner, I thought I'd spare you the jargon and go with an easy simile.

CURL and HTTPS, "Cannot resolve host"

Maybe a DNS issue?

Try your URL against this code:

$_h = curl_init();
curl_setopt($_h, CURLOPT_HEADER, 1);
curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, 'YOUR_URL' );
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );

var_dump(curl_exec($_h));
var_dump(curl_getinfo($_h));
var_dump(curl_error($_h)); 

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

How to use componentWillMount() in React Hooks?

This is the way how I simulate constructor in functional components using the useRef hook:

function Component(props) {
    const willMount = useRef(true);
    if (willMount.current) {
        console.log('This runs only once before rendering the component.');
        willMount.current = false;        
    }

    return (<h1>Meow world!</h1>);
}

Here is the lifecycle example:

function RenderLog(props) {
    console.log('Render log: ' + props.children);
    return (<>{props.children}</>);
}

function Component(props) {

    console.log('Body');
    const [count, setCount] = useState(0);
    const willMount = useRef(true);

    if (willMount.current) {
        console.log('First time load (it runs only once)');
        setCount(2);
        willMount.current = false;
    } else {
        console.log('Repeated load');
    }

    useEffect(() => {
        console.log('Component did mount (it runs only once)');
        return () => console.log('Component will unmount');
    }, []);

    useEffect(() => {
        console.log('Component did update');
    });

    useEffect(() => {
        console.log('Component will receive props');
    }, [count]);


    return (
        <>
        <h1>{count}</h1>
        <RenderLog>{count}</RenderLog>
        </>
    );
}
[Log] Body
[Log] First time load (it runs only once)
[Log] Body
[Log] Repeated load
[Log] Render log: 2
[Log] Component did mount (it runs only once)
[Log] Component did update
[Log] Component will receive props

Of course Class components don't have Body steps, it's not possible to make 1:1 simulation due to different concepts of functions and classes.

executing shell command in background from script

Building off of ngoozeff's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:

cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
  • &>/dev/null sets the command’s stdout and stderr to /dev/null instead of inheriting them from the parent process.
  • & makes the shell run the command in the background.
  • disown removes the “current” job, last one stopped or put in the background, from under the shell’s job control.

In some shells you can also use &! instead of & disown; they both have the same effect. Bash doesn’t support &!, though.

Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}" rather than "${cmd}":

cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;

If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.

Here's a function for it:

#!/bin/bash

# Run a command in the background.
_evalBg() {
    eval "$@" &>/dev/null & disown;
}

cmd="google-chrome";
_evalBg "${cmd}";

Also, see: Running bash commands in the background properly

jQuery AJAX cross domain

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function
  • now I can read .xml document in IE and Firefox. Other browsers I did not test.
  • response document can be plain/text, xml, json or anything else

Here is an example jQuery ajax call with some debug sysouts.

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

If you are running MYSQL through XAMPP:

  1. Open XAMPP mysql configuration file (on OSX):

    /Applications/XAMPP/etc/my.cnf

  2. Copy the socket path:

    socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

  3. Open rails project's database configuration file: myproject/config/database.yml

  4. Add the socket config to the development database config:

-->

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: difiuri_falcioni
  pool: 5
  username: root
  password:
  host: localhost
  socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
  1. Restart rails server

Enjoy :)

Excel function to make SQL-like queries on worksheet data?

If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools

Example, function BS_SQL("SELECT ..."):

enter image description here

Define preprocessor macro through CMake?

To do this for a specific target, you can do the following:

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.

Pass C# ASP.NET array to Javascript array

I came up with this similar situation and I resolved it quiet easily.Here is what I did. Assuming you already have the value in array at your aspx.cs page.

1)Put a hidden field in your aspx page and us the hidden field ID to store the array value.

 HiddenField2.Value = string.Join(",", myarray);

2)Now that the hidden field has the value stored, just separated by commas. Use this hidden field in JavaScript like this. Simply create an array in JavaScript and then store the value in that array by removing the commas.

var hiddenfield2 = new Array();
hiddenfield2=document.getElementById('<%=HiddenField2.ClientID%>').value.split(',');

This should solve your problem.

C# Double - ToString() formatting with two decimal places but no rounding

This is working for me

string prouctPrice = Convert.ToDecimal(String.Format("{0:0.00}", Convert.ToDecimal(yourString))).ToString();

Disabling browser caching for all browsers from ASP.NET

See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input> elements -- in other words, use autocomplete="off".

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

Greyscale Background Css Images

You don't need to use complicated coding really!

Greyscale Hover:

-webkit-filter: grayscale(100%);

Greyscale "Hover-out":

-webkit-filter: grayscale(0%);


I simply made my css class have a separate hover class and added in the second greyscale. It's really simple if you really don't like complexity.

socket.error: [Errno 48] Address already in use

You can allow the server to reuse an address with allow_reuse_address.

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()

How can I define colors as variables in CSS?

The 'Less' Ruby Gem for CSS looks awesome.

http://lesscss.org/

When to use malloc for char pointers

Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

How do I finish the merge after resolving my merge conflicts?

How do I finish the merge after resolving my merge conflicts?

With Git 2.12 (Q1 2017), you will have the more natural command:

git merge --continue

See commit c7d227d (15 Dec 2016) by Jeff King (peff).
See commit 042e290, commit c261a87, commit 367ff69 (14 Dec 2016) by Chris Packham (cpackham).
(Merged by Junio C Hamano -- gitster -- in commit 05f6e1b, 27 Dec 2016)

See 2.12 release notes.

merge: add '--continue' option as a synonym for 'git commit'

Teach 'git merge' the --continue option which allows 'continuing' a merge by completing it.
The traditional way of completing a merge after resolving conflicts is to use 'git commit'.
Now with commands like 'git rebase' and 'git cherry-pick' having a '--continue' option adding such an option to 'git merge' presents a consistent UI.

SQL query to find record with ID not in another table

Try this

SELECT ID, Name 
FROM   Table1 
WHERE  ID NOT IN (SELECT ID FROM Table2)

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

Using Linq to get the last N elements of a collection?

I am surprised that no one has mentioned it, but SkipWhile does have a method that uses the element's index.

public static IEnumerable<T> TakeLastN<T>(this IEnumerable<T> source, int n)
{
    if (source == null)
        throw new ArgumentNullException("Source cannot be null");

    int goldenIndex = source.Count() - n;
    return source.SkipWhile((val, index) => index < goldenIndex);
}

//Or if you like them one-liners (in the spirit of the current accepted answer);
//However, this is most likely impractical due to the repeated calculations
collection.SkipWhile((val, index) => index < collection.Count() - N)

The only perceivable benefit that this solution presents over others is that you can have the option to add in a predicate to make a more powerful and efficient LINQ query, instead of having two separate operations that traverse the IEnumerable twice.

public static IEnumerable<T> FilterLastN<T>(this IEnumerable<T> source, int n, Predicate<T> pred)
{
    int goldenIndex = source.Count() - n;
    return source.SkipWhile((val, index) => index < goldenIndex && pred(val));
}

How do I compile C++ with Clang?

Open a Terminal window and navigate to your project directory. Run these sets of commands, depending on which compiler you have installed:

To compile multiple C++ files using clang++:

$ clang++ *.cpp 
$ ./a.out 

To compile multiple C++ files using g++:

$ g++ -c *.cpp 
$ g++ -o temp.exe *.o
$ ./temp.exe

Create a string and append text to it

Concatenate with & operator

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.


Concatenate with String.Concat()

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

How to check if a number is a power of 2

Improving the answer of @user134548, without bits arithmetic:

public static bool IsPowerOfTwo(ulong n)
{
    if (n % 2 != 0) return false;  // is odd (can't be power of 2)

    double exp = Math.Log(n, 2);
    if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power
    return Math.Pow(2, exp) == n;
}

This works fine for:

IsPowerOfTwo(9223372036854775809)

Regex in JavaScript for validating decimal numbers

 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }

This is the function which will take decimal number with any number of decimal places and without any decimal places.

Thanks ... :)

Failed to load resource: net::ERR_INSECURE_RESPONSE

Your resource probably use a self-signed SSL certificate over HTTPS protocol. Chromium, so Google Chrome block by default this kind of resource considered unsecure.

You can bypass this this way :

  • Assuming your frame's URL is https://www.domain.com, open a new tab in chrome and go to https://www.domain.com.
  • Chrome will ask you to accept the SSL certificate. Accept it.
  • Then, if you reload your page with your frame, you could see that now it works

The problem as you can guess, is that each visitor of your website has to do this task to access your frame.

You can notice that chrome will block your URL for each navigation session, while chrome can memorise for ever that you trust this domain.

If your frame can be accessed by HTTP rather than HTTPS, I suggest you to use it, so this problem will be solved.

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

Gson library in Android Studio

Add following dependency or download Gson jar file

implementation 'com.google.code.gson:gson:2.8.6'

Follow github repo for documentation and more.

Express.js req.body undefined

Looks like the body-parser is no longer shipped with express. We may have to install it separately.

var express    = require('express')
var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!

Refer to the git page https://github.com/expressjs/body-parser for more info and examples.

Can I mask an input text in a bat file?

Up to XP and Server 2003, you can make use of another included tool (VBScript) - the following two scripts do the job you want.

First, getpwd.cmd:

@echo off
<nul: set /p passwd=Password: 
for /f "delims=" %%i in ('cscript /nologo getpwd.vbs') do set passwd=%%i
echo.

Then, getpwd.vbs:

Set oScriptPW = CreateObject("ScriptPW.Password")
strPassword = oScriptPW.GetPassword()
Wscript.StdOut.WriteLine strPassword

The getpwd.vbs simply uses the password object to input the password from the user and then print it to standard output (the next paragraph will explain why that doesn't show up in the terminal).

The getpwd.cmd command script is a bit trickier but it basically works as follows.

The effect of the "<nul: set /p passwd=Password: " command is to output the prompt with no trailing newline character - it's a sneaky way to emulate the "echo -n" command from the bash shell. It sets passwd to an empty string as an irrelevant side effect and doesn't wait for input since it's taking its input from the nul: device.

The "for /f "delims=" %%i in ('cscript /nologo getpwd.vbs') do set passwd=%%i" statement is the trickiest bit. It runs the VBScript with no Microsoft "advertising", so that the only line output is the password (from the VBscript "Wscript.StdOut.WriteLine strPassword".

Setting the delimiters to nothing is required to capture an entire input line with spaces, otherwise you just get the first word. The "for ... do set ..." bit sets passwd to be the actual password output from the VBScript.

Then we echo a blank line (to terminate the "Password: " line) and the password will be in the passwd environment variable after the code has run.


Now, as mentioned, scriptpw.dll is available only up to XP/2003. In order to rectify this, you can simply copy the scriptpw.dll file from the Windows\System32 folder of an XP/2003 system to the Winnt\System32 or Windows\System32 folder on your own system. Once the DLL has been copied, you will need to register it by running:

regsvr32 scriptpw.dll

To successfully register the DLL on Vista and later, you will need administrator privileges. I haven't examined the legality of such a move so cave lector.


If you're not overly keen on trying to track down and register older DLL files (for convenience or legal reasons), there is another way. Later versions of Windows (the ones that don't have the required DLL) should have Powershell available to you.

And, in fact, you really should consider upgrading your scripts to use it fully since it's a much more capable scripting language than cmd.exe. However, if you want to keep the bulk of your code as cmd.exe scripts (such as if you have a lot of code that you don't want to convert), you can use the same trick.

First, modify the cmd script so it calls Powershell rather than CScript:

@echo off
for /f "delims=" %%i in ('powershell -file getpwd.ps1') do set passwd=%%i

The Powershell script is equally simple:

$password = Read-Host "Enter password" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto($password)
echo $password

although with some marshalling to get the actual password text.

Remember that, to run local unsigned Powershell scripts on your machine, you may need to modify the execution policy from the (draconian, though very safe) default, with something like:

set-executionpolicy remotesigned

from within Powershell itself.

Numpy how to iterate over columns of array?

for c in np.hsplit(array, array.shape[1]):
    some_fun(c)

How to randomize Excel rows

Perhaps the whole column full of random numbers is not the best way to do it, but it seems like probably the most practical as @mariusnn mentioned.

On that note, this stomped me for a while with Office 2010, and while generally answers like the one in lifehacker work,I just wanted to share an extra step required for the numbers to be unique:

  1. Create a new column next to the list that you're going to randomize
  2. Type in =rand() in the first cell of the new column - this will generate a random number between 0 and 1
  3. Fill the column with that formula. The easiest way to do this may be to:

    • go down along the new column up until the last cell that you want to randomize
    • hold down Shift and click on the last cell
    • press Ctrl+D
  4. Now you should have a column of identical numbers, even though they are all generated randomly.

    Random numbers... that are the same...

    The trick here is to recalculate them! Go to the Formulas tab and then click on Calculate Now (or press F9).

    Actually random numbers!

    Now all the numbers in the column will be actually generated randomly.

  5. Go to the Home tab and click on Sort & Filter. Choose whichever order you want (Smallest to Largest or Largest to Smallest) - whichever one will give you a random order with respect to the original order. Then click OK when the Sort Warning prompts you to Expand the selection.

  6. Your list should be randomized now! You can get rid of the column of random numbers if you want.

Are 64 bit programs bigger and faster than 32 bit versions?

Regardless of the benefits, I would suggest that you always compile your program for the system's default word size (32-bit or 64-bit), since if you compile a library as a 32-bit binary and provide it on a 64-bit system, you will force anyone who wants to link with your library to provide their library (and any other library dependencies) as a 32-bit binary, when the 64-bit version is the default available. This can be quite a nuisance for everyone. When in doubt, provide both versions of your library.

As to the practical benefits of 64-bit... the most obvious is that you get a bigger address space, so if mmap a file, you can address more of it at once (and load larger files into memory). Another benefit is that, assuming the compiler does a good job of optimizing, many of your arithmetic operations can be parallelized (for example, placing two pairs of 32-bit numbers in two registers and performing two adds in single add operation), and big number computations will run more quickly. That said, the whole 64-bit vs 32-bit thing won't help you with asymptotic complexity at all, so if you are looking to optimize your code, you should probably be looking at the algorithms rather than the constant factors like this.

EDIT:
Please disregard my statement about the parallelized addition. This is not performed by an ordinary add statement... I was confusing that with some of the vectorized/SSE instructions. A more accurate benefit, aside from the larger address space, is that there are more general purpose registers, which means more local variables can be maintained in the CPU register file, which is much faster to access, than if you place the variables in the program stack (which usually means going out to the L1 cache).

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

        combo1.DisplayMember = "Text";
        combo1.ValueMember = "Value";   
        combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
        dynamic item = combo1.Items[combo1.SelectedIndex];
        var itemValue = item.Value;
        var itemText = item.Text;

Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

ASP.NET MVC ActionLink and post method

You can't use an ActionLink because that just renders an anchor <a> tag.
You can use a jQuery AJAX post.
Or just call the form's submit method with or without jQuery (which would be non-AJAX), perhaps in the onclick event of whatever control takes your fancy.

Select a row from html table and send values onclick of a button

You can access the first element adding the following code to the highlight function

$(this).find(".selected td:first").html()

Working Code:JSFIDDLE

Mockito How to mock and assert a thrown exception?

Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

Reverse a string without using reversed() or [::-1]?

I created different versions of how to reverse a string in python in my repo: https://github.com/fedmich/Python-Codes/tree/master/Reverse%20a%20String

You can do it by using list-comprehension or lambda technique:

# Reverse a string without using reverse() function
s = 'Federico';
li = list( s )  #convert string to list

ret = [ li[i-1] for i in xrange(len(li),0,-1)  ]    #1 liner lambda
print ( "".join( ret ) )

or by doing a backward for loop

# Reverse a string without using reverse() function
s = 'Federico';
r = []

length = len(s)
for i in xrange(length,0,-1):
    r.append( s[ i - 1] )

print ( "".join(r) )

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

How to make 'submit' button disabled?

in Angular 2.x.x , 4, 5 ...

<form #loginForm="ngForm">
    <input type="text" required> 
    <button  type="submit"  [disabled]="loginForm.form.invalid">Submit</button>
</form>

How can I fill a div with an image while keeping it proportional?

The only way I achieved the "best case" scenario described, was putting the image as a background:

<div class="container"></div>?
.container {
    width: 150px;
    height: 100px;
    background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}?

find -exec with multiple commands

A find+xargs answer.

The example below finds all .html files and creates a copy with the .BAK extension appended (e.g. 1.html > 1.html.BAK).

Single command with multiple placeholders

find . -iname "*.html" -print0 | xargs -0 -I {} cp -- "{}" "{}.BAK"

Multiple commands with multiple placeholders

find . -iname "*.html" -print0 | xargs -0 -I {} echo "cp -- {} {}.BAK ; echo {} >> /tmp/log.txt" | sh

# if you need to do anything bash-specific then pipe to bash instead of sh

This command will also work with files that start with a hyphen or contain spaces such as -my file.html thanks to parameter quoting and the -- after cp which signals to cp the end of parameters and the beginning of the actual file names.

-print0 pipes the results with null-byte terminators.


for xargs the -I {} parameter defines {} as the placeholder; you can use whichever placeholder you like; -0 indicates that input items are null-separated.

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

The Process described by Igor and CharlesB Works to me, since IDE's like NetBeans and Eclipse permit specify the location of the JDK, even software like Apache Tomcat (the ZIP Distribution) use BASH - FILES to set it up (then specify the JDK location using relatives URI).
I Have a USB-HardDisk With NetBeans, Eclipse, Apache Tomcat working with a JDK in "portable mode".
I Had a way to extract a copy of the JDK from the installers files: Install it, Copy it in other place and then uninstall it. A dirty way to extract it, but was successfull.
The place to put EXTRA - LIBS was: %PLACE_WHERE_JDK_ARE%\jre\lib\ext

Run react-native on android emulator

I had a similar problem, and after spending so much time and lots of searching about this issue the only trick worked for me:

  1. Please Install the Required SDKs as shown in this figure

Configure Required SDKs Configure Required SDKs

  1. If You have already installed it, so you must have to update the following SDKs:
    • Android SDK Tool (update it to latest version)
    • Android SDK Platform-tools (update it to latest version)
    • Android SDK Build-tools (update it to latest version)
    • Android Support Repository under Extra folder (update it to latest version)
  2. You Must have at least Installed the Same version Android API as the installed Android SDK Build-tools & Android SDK Platform-tools version as shown in the Configure Required SDKs figure above.

Note: Local Maven repository for Support Libraries which is listed as the SDK requirement in the official docs of React-native is now named as Android Support Repository in the SDK Manager .

Bash script to run php script

A previous poster said..

If you have PHP installed as a command line tool… your shebang (#!) line needs to look like this: #!/usr/bin/php

While this could be true… just because you can type in php does NOT necessarily mean that's where php is going to be... /usr/bin/php is A common location… but as with any shebang… it needs to be tailored to YOUR env.

a quick way to find out WHERE YOUR particular executable is located on your $PATH, try.. ?which -a php ENTER, which for me looks like..

php is /usr/local/php5/bin/php
php is /usr/bin/php
php is /usr/local/bin/php
php is /Library/WebServer/CGI-Executables/php

The first one is the default i'd get if I just typed in php at a command prompt… but I can use any of them in a shebang, or directly… You can also combine the executable name with env, as is often seen, but I don't really know much about / trust that. XOXO.

Use multiple custom fonts using @font-face?

I use this method in my css file

@font-face {
  font-family: FontName1;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
  font-family: FontName2;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
  font-family: FontName3;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

The short form(a += 1) has the option to modify a in-place , instead of creating a new object representing the sum and rebinding it back to the same name(a = a + 1).So,The short form(a += 1) is much efficient as it doesn't necessarily need to make a copy of a unlike a = a + 1.

Also even if they are outputting the same result, notice they are different because they are separate operators: + and +=

MySql Query Replace NULL with Empty String in Select

Some of these built in functions should work:

Coalesce
Is Null
IfNull

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

Using VBA to get extended file attributes

I was finally able to get this to work for my needs.

The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.

https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.

The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.

Private Sub MySubNamek()
Dim objShell  As Object 'Shell
Dim objFolder As Object 'Folder

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")

If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
        For i = 0 To 288
           szItem = objFolder.GetDetailsOf(objFolderItem, i)
           Debug.Print i & " - " & szItem
       Next
Set objFolderItem = Nothing
End If

Set objFolder = Nothing
Set objShell = Nothing
End Sub

Difference between Static methods and Instance methods

Instance method vs Static method

  1. Instance method can access the instance methods and instance variables directly.

  2. Instance method can access static variables and static methods directly.

  3. Static methods can access the static variables and static methods directly.

  4. Static methods can’t access instance methods and instance variables directly. They must use reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.

Why I get 'list' object has no attribute 'items'?

If you don't care about the type of the numbers you can simply use:

qs[0].values()

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Using "setInterval" & "clearInterval" fixes the problem:

function drawMarkers(map, markers) {
    var _this = this,
        geocoder = new google.maps.Geocoder(),
        geocode_filetrs;

    _this.key = 0;

    _this.interval = setInterval(function() {
        _this.markerData = markers[_this.key];

        geocoder.geocode({ address: _this.markerData.address }, yourCallback(_this.markerData));

        _this.key++;

        if ( ! markers[_this.key]) {
            clearInterval(_this.interval);
        }

    }, 300);
}

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

support FragmentPagerAdapter holds reference to old fragments

Just so you know...

Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.

I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).

The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.

I don't have a clean workaround. I used something like this:

  public void onSaveInstanceState(Bundle outState) {
    IFragmentListener listener = (IFragmentListener)getActivity();
    if (listener!= null)
    {
        if (!listener.isStillInTheAdapter(this.getAdapterItem()))
        {
            return; // return empty state.
        }

    }
    super.onSaveInstanceState(outState);

    // normal saving of state for flips and 
    // paging out of the activity follows
    ....
  }

An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.

Using "label for" on radio buttons

Either structure is valid and accessible, but the for attribute should be equal to the id of the input element:

<input type="radio" ... id="r1" /><label for="r1">button text</label>

or

<label for="r1"><input type="radio" ... id="r1" />button text</label>

The for attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +:

input[type="radio"]:checked+label {font-weight:bold;}

How to downgrade tensorflow, multiple versions possible?

Pip allows to specify the version

pip install tensorflow==1.1

How do I change the value of a global variable inside of a function

var a = 10;

myFunction(a);

function myFunction(a){
   window['a'] = 20; // or window.a
}

alert("Value of 'a' outside the function " + a); //outputs 20

With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.

How to call a SOAP web service on Android

Add Soap Libaray(ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar):

public static String Fn_Confirm_CollectMoney_Approval(

        HashMap < String, String > str1,
        HashMap < String, String > str2,
        HashMap < String, String > str3) {

    Object response = null;
    String METHOD_NAME = "CollectMoney";
    String NAMESPACE = "http://xxx/yyy/xxx";
    String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    String SOAP_ACTION = "";

    try {

        SoapObject RequestParent = new SoapObject(NAMESPACE, METHOD_NAME);

        SoapObject Request1 = new SoapObject(NAMESPACE, "req");

        PropertyInfo pi = new PropertyInfo();

        Set mapSet1 = (Set) str1.entrySet();

        Iterator mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            String keyValue = (String) mapEntry.getKey();

            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        mapSet1 = (Set) str3.entrySet();

        mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        SoapObject HeaderRequest = new SoapObject(NAMESPACE, "XXX");

        Set mapSet = (Set) str2.entrySet();

        Iterator mapIterator = mapSet.iterator();

        while (mapIterator.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            HeaderRequest.addProperty(pi);
        }

        Request1.addSoapObject(HeaderRequest);

        RequestParent.addSoapObject(Request1);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER10);

        soapEnvelope.dotNet = false;

        soapEnvelope.setOutputSoapObject(RequestParent);

        HttpTransportSE transport = new HttpTransportSE(URL, 120000);

        transport.debug = true;

        transport.call(SOAP_ACTION, soapEnvelope);

        response = (Object) soapEnvelope.getResponse();

        int cols = ((SoapObject) response).getPropertyCount();

        Object objectResponse = (Object) ((SoapObject) response)
                .getProperty("Resp");

        SoapObject subObject_Resp = (SoapObject) objectResponse;


        modelObject = new ResposeXmlModel();

        String MsgId = subObject_Resp.getProperty("MsgId").toString();


        modelObject.setMsgId(MsgId);

        String OrgId = subObject_Resp.getProperty("OrgId").toString();


        modelObject.setOrgId(OrgId);

        String ResCode = subObject_Resp.getProperty("ResCode").toString();


        modelObject.setResCode(ResCode);

        String ResDesc = subObject_Resp.getProperty("ResDesc").toString();


        modelObject.setResDesc(ResDesc);

        String TimeStamp = subObject_Resp.getProperty("TimeStamp")
                .toString();


        modelObject.setTimestamp(ResDesc);

        return response.toString();

    } catch (Exception ex) {

        ex.printStackTrace();

        return null;
    }

}

How to add a scrollbar to an HTML5 table?

HTML :

    <h1>&darr; SCROLL &darr;</h1>
<table class="blue">
  <thead>
    <tr>
      <th>Colonne 1</th>
      <th>Colonne 2</th>
      <th>Colonne 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
       <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
  </tbody>
</table>

<h1 class="scrollMore">&darr; SCROLL MORE &darr;</h1>
<table class="purple">
  <thead>
    <tr>
      <th>Colonne 1</th>
      <th>Colonne 2</th>
      <th>Colonne 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
       <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
       <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
  </tbody>
</table>
<h1 class="up scrollMore">&uarr; UP &uarr;</h1>

CSS:

body{
  font:1.2em normal Arial,sans-serif;
  color:#34495E;
}

h1{
  text-align:center;
  text-transform:uppercase;
  letter-spacing:-2px;
  font-size:2.5em;
  margin:20px 0;
}

.container{
  width:90%;
  margin:auto;
}

table{
  border-collapse:collapse;
  width:100%;
}

.blue{
  border:2px solid #1ABC9C;
}

.blue thead{
  background:#1ABC9C;
}

.purple{
  border:2px solid #9B59B6;
}

.purple thead{
  background:#9B59B6;
}

thead{
  color:white;
}

th,td{
  text-align:center;
  padding:5px 0;
}

tbody tr:nth-child(even){
  background:#ECF0F1;
}

tbody tr:hover{
background:#BDC3C7;
  color:#FFFFFF;
}

.fixed{
  top:0;
  position:fixed;
  width:auto;
  display:none;
  border:none;
}

.scrollMore{
  margin-top:600px;
}

.up{
  cursor:pointer;
}

JS (jQuery):

;(function($) {
   $.fn.fixMe = function() {
      return this.each(function() {
         var $this = $(this),
            $t_fixed;
         function init() {
            $this.wrap('<div class="container" />');
            $t_fixed = $this.clone();
            $t_fixed.find("tbody").remove().end().addClass("fixed").insertBefore($this);
            resizeFixed();
         }
         function resizeFixed() {
            $t_fixed.find("th").each(function(index) {
               $(this).css("width",$this.find("th").eq(index).outerWidth()+"px");
            });
         }
         function scrollFixed() {
            var offset = $(this).scrollTop(),
            tableOffsetTop = $this.offset().top,
            tableOffsetBottom = tableOffsetTop + $this.height() - $this.find("thead").height();
            if(offset < tableOffsetTop || offset > tableOffsetBottom)
               $t_fixed.hide();
            else if(offset >= tableOffsetTop && offset <= tableOffsetBottom && $t_fixed.is(":hidden"))
               $t_fixed.show();
         }
         $(window).resize(resizeFixed);
         $(window).scroll(scrollFixed);
         init();
      });
   };
})(jQuery);

$(document).ready(function(){
   $("table").fixMe();
   $(".up").click(function() {
      $('html, body').animate({
      scrollTop: 0
   }, 2000);
 });
});

For beginner programmer: If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head> 

Adding jQuery to Your Web Pages click here.

Reference: HERE

How to edit a text file in my terminal

Open the file again using vi. and then press " i " or press insert key ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

How to get current memory usage in android?

CAUTION: This answer measures memory usage/available of the DEVICE. This is NOT what is available to your app. To measure what your APP is doing, and is PERMITTED to do, Use android developer's answer.


Android docs - ActivityManager.MemoryInfo

  1. parse /proc/meminfo command. You can find reference code here: Get Memory Usage in Android

  2. use below code and get current RAM:

    MemoryInfo mi = new MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    double availableMegs = mi.availMem / 0x100000L;
    
    //Percentage can be calculated for API 16+
    double percentAvail = mi.availMem / (double)mi.totalMem * 100.0;
    

Explanation of the number 0x100000L

1024 bytes      == 1 Kibibyte 
1024 Kibibyte   == 1 Mebibyte

1024 * 1024     == 1048576
1048576         == 0x100000

It's quite obvious that the number is used to convert from bytes to mebibyte

P.S: we need to calculate total memory only once. so call point 1 only once in your code and then after, you can call code of point 2 repetitively.

How do I make text bold in HTML?

It’s just <b> instead of <bold>:

Some <b>text</b> that I want bolded.

Note that <b> just changes the appearance of the text. If you want to render it bold because you want to express a strong emphasis, you should better use the <strong> element.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

  1. To closed ideas,
  2. To remove all folder and file C:/Users/UserName/.m2/org/*,
  3. Open ideas and update Maven project,(right click on project -> maven->update maven project)
  4. After that update the project.

How to copy data from one HDFS to another HDFS?

DistCp (distributed copy) is a tool used for copying data between clusters. It uses MapReduce to effect its distribution, error handling and recovery, and reporting. It expands a list of files and directories into input to map tasks, each of which will copy a partition of the files specified in the source list.

Usage: $ hadoop distcp <src> <dst>

example: $ hadoop distcp hdfs://nn1:8020/file1 hdfs://nn2:8020/file2

file1 from nn1 is copied to nn2 with filename file2

Distcp is the best tool as of now. Sqoop is used to copy data from relational database to HDFS and vice versa, but not between HDFS to HDFS.

More info:

There are two versions available - runtime performance in distcp2 is more compared to distcp

What is the difference between a candidate key and a primary key?

Think of a table of vehicles with an integer Primary Key.

The registration number would be a candidate key.

In the real world registration numbers are subject change so it depends somewhat on the circumstances what might qualify as a candidate key.

Is there a way to get colored text in GitHubflavored Markdown?

As an alternative to rendering a raster image, you can embed a SVG:

https://gist.github.com/CyberShadow/95621a949b07db295000

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

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

How do I create a link to add an entry to a calendar?

The links in Dave's post are great. Just to put a few technical details about the google links into an answer here on SO:

Google Calendar Link

<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=Example%20Event&dates=20131124T010000Z/20131124T020000Z&details=Event%20Details%20Here&location=123%20Main%20St%2C%20Example%2C%20NY">Add to gCal</a>

the parameters being:

  • action=TEMPLATE (required)
  • text (url encoded name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time - the button generator will let you leave the endtime blank, but you must have one or it won't work.)
    • to use the user's timezone: 20131208T160000/20131208T180000
    • to use global time, convert to UTC, then use 20131208T160000Z/20131208T180000Z
    • all day events, you can use 20131208/20131209 - note that the button generator gets it wrong. You must use the following date as the end date for a one day all day event, or +1 day to whatever you want the end date to be.
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)

Update Feb 2018:

Here's a new link structure that seems to support the new google version of google calendar w/o requiring API interaction:

https://calendar.google.com/calendar/r/eventedit?text=My+Custom+Event&dates=20180512T230000Z/20180513T030000Z&details=For+details,+link+here:+https://example.com/tickets-43251101208&location=Garage+Boston+-+20+Linden+Street+-+Allston,+MA+02134

New base url: https://calendar.google.com/calendar/r/eventedit

New parameters:

  • text (name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time)
    • an event w/ start/end times: 20131208T160000/20131208T180000
    • all day events, you can use 20131208/20131209 - end date must be +1 day to whatever you want the end date to be.
  • ctz (timezone such as America/New_York - leave blank to use the user's default timezone. Highly recommended to include this in almost all situations. For example, a reminder for a video conference: if three people in different timezones clicked this link and set a reminder for their "own" Tuesday at 10:00am, this would not work out well.)
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)
  • add (comma separated list of emails - adds guests to your new event)

Notes:

  • the old url structure above now redirects here
  • supports https
  • deals w/ timezones better
  • accepts + for space in addition to %20 (urlencode vs rawurlencode in php - both work)

creating a table in ionic

In Ionic 2 there's a easier way to do that. See the Ionic Docs.

It is more or less like the following:

<ion-grid>
  <ion-row>
    <ion-col>
      1 of 3
    </ion-col>
    <ion-col>
      2 of 3
    </ion-col>
    <ion-col>
      3 of 3
    </ion-col>
  </ion-row>
</ion-grid>

How to get the mobile number of current sim card in real device?

I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?

Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...

Add permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Import:

import android.telephony.TelephonyManager;

Use the below code:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

         // get IMEI
         imei = tm.getDeviceId();

         // get SimSerialNumber
         simSerialNumber = tm.getSimSerialNumber();

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

How do you remove Subversion control for a folder?

You can use "svn export" for creating a copy of that folder without svn data, or you can add that folder to ignore list

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

How do I get a file extension in PHP?

A quick fix would be something like this.

// Exploding the file based on the . operator
$file_ext = explode('.', $filename);

// Count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count = count($file_ext);

// Minus 1 to make the offset correct
$cnt = $file_ext_count - 1;

// The variable will have a value pdf as per the sample file name mentioned above.
$file_extension = $file_ext[$cnt];

Accessing MVC's model property from Javascript

try this: (you missed the single quotes)

var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';

"Gradle Version 2.10 is required." Error

In my case the problem was indeed in the distributionURL in gradle-wrapper.properties file and Android Studio auto-fixed inserting

distributionUrl=https://services.gradle.org/distributions/gradle-4.0-20170417000025+0000-all.zip

But this was a wrong URL. The correct one is

distributionUrl=https://services.gradle.org/distributions-snapshots/gradle-4.0-20170417000025+0000-all.zip

Apparently the url changed in gradle's API but not in Android Studio so fixing it by hand solved the problem for me.

List<Object> and List<?>

Why cant I do this:

List<Object> object = new List<Object>();

You can't do this because List is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List include ArrayList, LinkedList etc.

Here is how one would create an instance of ArrayList:

List<Object> object = new ArrayList<Object>();

I have a method that returns a List<?>, how would I turn that into a List<Object>

Show us the relevant code and I'll update the answer.

Efficient SQL test query or validation query that will work across all (or most) databases

How about

SELECT user()

I use this before.MySQL, H2 is OK, I don't know others.

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

Pad with leading zeros

You can do this with a string datatype. Use the PadLeft method:

var myString = "1";
myString = myString.PadLeft(myString.Length + 5, '0');

000001

In where shall I use isset() and !empty()

If you have a $_POST['param'] and assume it's string type then

isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'

is identical to

!empty($_POST['param'])

C# Timer or Thread.Sleep

I required a thread to fire once every minute (see question here) and I've now used a DispatchTimer based on the answers I received.

The answers provide some references which you might find useful.

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

What is correct media query for IPad Pro?

Note that there are multiple iPad Pros, each with a different Viewports: When emulating an iPad Pro via the Chrome developer tools, the iPad Pro (12.9") is the default option. If you want to emulate one of the other iPad Pros (10.5" or 9.7") with a different viewport, you'll need to add a custom emulated device with the correct specs.

You can search devices, viewports, and their respective CSS media queries at: http://vizdevices.yesviz.com/devices.php.

For instance, the iPad Pro (12.9") would have the following media queries:

/* Landscape */ 
@media only screen and (min-width: 1366px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-width: 1024px) and (orientation: portrait) { /* Your Styles... */ }

Whereas the iPad Pro (10.5") will have:

/* Landscape */ 
@media only screen and (min-device-width: 1112px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-device-width: 834px) and (orientation: portrait) { /* Your Styles... */ }

How to get the full url in Express?

Here is a great way to add a function you can call on the req object to get the url

  app.use(function(req, res, next) {
    req.getUrl = function() {
      return req.protocol + "://" + req.get('host') + req.originalUrl;
    }
    return next();
  });

Now you have a function you can call on demand if you need it.

Get filename from input [type='file'] using jQuery

You can access to the properties you want passing an argument to your callback function (like evt), and then accessing the files with it (evt.target.files[0].name) :

$("document").ready(function(){
  $("main").append('<input type="file" name="photo" id="upload-photo"/>');
  $('#upload-photo').on('change',function(evt) {
    alert(evt.target.files[0].name);
  });
});

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

In my case increasing mem by setting MAVEN_OPTS helped:

set MAVEN_OPTS=-Xmx1024m

Object creation on the stack/heap?

  1. Object* o; o = new Object();

  2. Object* o = new Object();

Both these statement creates the object in the heap memory since you are creating the object using "new".

To be able to make the object creation happen in the stack, you need to follow this:

Object o;
Object *p = &o;

I want to use CASE statement to update some records in sql server 2005

This is also an alternate use of case-when...

UPDATE [dbo].[JobTemplates]
SET [CycleId] = 
    CASE [Id]
        WHEN 1376 THEN 44   --ACE1 FX1
        WHEN 1385 THEN 44   --ACE1 FX2
        WHEN 1574 THEN 43   --ACE1 ELEM1
        WHEN 1576 THEN 43   --ACE1 ELEM2
        WHEN 1581 THEN 41   --ACE1 FS1
        WHEN 1585 THEN 42   --ACE1 HS1
        WHEN 1588 THEN 43   --ACE1 RS1
        WHEN 1589 THEN 44   --ACE1 RM1
        WHEN 1590 THEN 43   --ACE1 ELEM3
        WHEN 1591 THEN 43   --ACE1 ELEM4
        WHEN 1595 THEN 44   --ACE1 SSTn     
        ELSE 0  
     END
WHERE
    [Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)

I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:

SELECT
     [Id]
    ,[QueueId]
    ,[BaseDimensionId]
    ,[ElastomerTypeId]
    ,CASE [CycleId]
        WHEN  29 THEN 44
        WHEN  30 THEN 43
        WHEN  31 THEN 43
        WHEN 101 THEN 41
        WHEN 102 THEN 43
        WHEN 116 THEN 42
        WHEN 120 THEN 44
        WHEN 127 THEN 44
        WHEN 129 THEN 44
        ELSE    0
     END                AS [CycleId]
INTO
    ##ACE1_PQPANominals_1
FROM 
    [dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
    [QueueId] = 3
ORDER BY 
    [BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)

UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET 
    [CycleId] = X.[CycleId]
FROM
    [dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
    SELECT  
        MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
    FROM 
        ##ACE1_PQPANominals_1
    GROUP BY    
        [QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
) AS X
ON
    [dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)

How to interpolate variables in strings in JavaScript, without concatenation?

If you like to write CoffeeScript you could do:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript actually IS javascript, but with a much better syntax.

For an overview of CoffeeScript check this beginner's guide.

How do you post data with a link

You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>

Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:

isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']

And in the streeview.php make links like that:

<a href="house.php?houseVar=$houseNum"></a>

Or something else. I just don't know your files and what inside it.

How do I enable php to work with postgresql?

Try this:

Uncomment the following in php.ini by removing the ";"

;extension=php_pgsql.dll

Use the following code to connect to a postgresql database server:

pg_connect("host=localhost dbname=dbname user=username password=password")
    or die("Can't connect to database".pg_last_error());

Turn off constraints temporarily (MS SQL)

And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.

ALTER TABLE foo CHECK CONSTRAINT ALL

or

ALTER TABLE foo CHECK CONSTRAINT FK_something

then you can run back in and do an update against any checked columns like so:

UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc

And any errors at that point will be due to failure to meet constraints.

StringIO in Python3

In my case I have used:

from io import StringIO

How can I pass POST parameters in a URL?

Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

Adding a Method to an Existing Object Instance

Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:

Especially note how adding the binding function as a class method works, but the referencing scope is incorrect.

#!/usr/bin/python -u
import types
import inspect

## dynamically adding methods to a unique instance of a class


# get a list of a class's method type attributes
def listattr(c):
    for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:
        print m[0], m[1]

# externally bind a function as a method of an instance of a class
def ADDMETHOD(c, method, name):
    c.__dict__[name] = types.MethodType(method, c)

class C():
    r = 10 # class attribute variable to test bound scope

    def __init__(self):
        pass

    #internally bind a function as a method of self's class -- note that this one has issues!
    def addmethod(self, method, name):
        self.__dict__[name] = types.MethodType( method, self.__class__ )

    # predfined function to compare with
    def f0(self, x):
        print 'f0\tx = %d\tr = %d' % ( x, self.r)

a = C() # created before modified instnace
b = C() # modified instnace


def f1(self, x): # bind internally
    print 'f1\tx = %d\tr = %d' % ( x, self.r )
def f2( self, x): # add to class instance's .__dict__ as method type
    print 'f2\tx = %d\tr = %d' % ( x, self.r )
def f3( self, x): # assign to class as method type
    print 'f3\tx = %d\tr = %d' % ( x, self.r )
def f4( self, x): # add to class instance's .__dict__ using a general function
    print 'f4\tx = %d\tr = %d' % ( x, self.r )


b.addmethod(f1, 'f1')
b.__dict__['f2'] = types.MethodType( f2, b)
b.f3 = types.MethodType( f3, b)
ADDMETHOD(b, f4, 'f4')


b.f0(0) # OUT: f0   x = 0   r = 10
b.f1(1) # OUT: f1   x = 1   r = 10
b.f2(2) # OUT: f2   x = 2   r = 10
b.f3(3) # OUT: f3   x = 3   r = 10
b.f4(4) # OUT: f4   x = 4   r = 10


k = 2
print 'changing b.r from {0} to {1}'.format(b.r, k)
b.r = k
print 'new b.r = {0}'.format(b.r)

b.f0(0) # OUT: f0   x = 0   r = 2
b.f1(1) # OUT: f1   x = 1   r = 10  !!!!!!!!!
b.f2(2) # OUT: f2   x = 2   r = 2
b.f3(3) # OUT: f3   x = 3   r = 2
b.f4(4) # OUT: f4   x = 4   r = 2

c = C() # created after modifying instance

# let's have a look at each instance's method type attributes
print '\nattributes of a:'
listattr(a)
# OUT:
# attributes of a:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FD88>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FD88>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FD88>>

print '\nattributes of b:'
listattr(b)
# OUT:
# attributes of b:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FE08>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FE08>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FE08>>
# f1 <bound method ?.f1 of <class __main__.C at 0x000000000237AB28>>
# f2 <bound method ?.f2 of <__main__.C instance at 0x000000000230FE08>>
# f3 <bound method ?.f3 of <__main__.C instance at 0x000000000230FE08>>
# f4 <bound method ?.f4 of <__main__.C instance at 0x000000000230FE08>>

print '\nattributes of c:'
listattr(c)
# OUT:
# attributes of c:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002313108>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002313108>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002313108>>

Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.

def y(self, x):
    pass
d = C()
for i in range(1,5):
    ADDMETHOD(d, y, 'f%d' % i)
print '\nattributes of d:'
listattr(d)
# OUT:
# attributes of d:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002303508>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002303508>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002303508>>
# f1 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f2 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f3 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f4 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>

How do you set the EditText keyboard to only consist of numbers on Android?

I think you used somehow the right way to show the number only on the keyboard so better try the given line with xml in your edit text and it will work perfectly so here the code is-

  android:inputType="number"

In case any doubt you can again ask to me i'll try to completely sort out your problem. Thanks

How to modify list entries during for loop?

Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.

You can use list comprehension:

l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]

or just do the C-style for loop:

for index, item in enumerate(l):
    l[index] = item.strip()

Bootstrap button drop-down inside responsive table not visible because of scroll

This worked for me in Bootstrap 4 since it has different breakpoints than v3:

@media (min-width: 992px) {
    .table-responsive {
        overflow: inherit;
    }
}

How to select a dropdown value in Selenium WebDriver using Java

You can use following methods to handle drop down in selenium.

  1. driver.selectByVisibleText("Text");
  2. driver.selectByIndex(1);
  3. driver.selectByValue("prog");

For more details you can refer http://www.codealumni.com/handle-drop-selenium-webdriver/ this post.

It will definately help you a lot in resolving your queries.

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

Set opacity of background image without affecting child elements

If you have to set the opacity only to the bullet, why don't you set the alpha channel directly into the image? By the way I don't think there is a way to set the opacity to a background image via css without changing the opacity of the whole element (and its children too).

"replace" function examples

Be aware that the third parameter (value) in the examples given above: the value is a constant (e.g. 'Z' or c(20,30)).

Defining the third parameter using values from the data frame itself can lead to confusion.

E.g. with a simple data frame such as this (using dplyr::data_frame):

tmp <- data_frame(a=1:10, b=sample(LETTERS[24:26], 10, replace=T))

This will create somthing like this:

       a     b
   (int) (chr)
1      1     X
2      2     Y
3      3     Y
4      4     X
5      5     Z

..etc

Now suppose you want wanted to do, was to multiply the values in column 'a' by 2, but only where column 'b' is "X". My immediate thought would be something like this:

with(tmp, replace(a, b=="X", a*2))

That will not provide the desired outcome, however. The a*2 will defined as a fixed vector rather than a reference to the 'a' column. The vector 'a*2' will thus be

[1]  2  4  6  8 10 12 14 16 18 20

at the start of the 'replace' operation. Thus, the first row where 'b' equals "X", the value in 'a' will be placed by 2. The second time, it will be replaced by 4, etc ... it will not be replaced by two-times-the-value-of-a in that particular row.

Javascript Drag and drop for touch devices

For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:

Add a couple of globals:

var clickms = 100;
var lastTouchDown = -1;

Then modify the switch statement from the original to this:

var d = new Date();
switch(event.type)
{
    case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
    case "touchmove": type="mousemove"; lastTouchDown = -1; break;        
    case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
    default: return;
}

You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.

Windows Forms - Enter keypress activates submit button?

Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

git: 'credential-cache' is not a git command

A similar error is 'credential-wincred' is not a git command

The accepted and popular answers are now out of date...

wincred is for the project git-credential-winstore which is no longer maintained.

It was replaced by Git-Credential-Manager-for-Windows maintained by Microsoft open source.

Download the release as zip file from link above and extract contents to

\cygwin\usr\libexec\git-core

(or \cygwin64\usr\libexec\git-core as it may be)

Then enable it, (by setting the global .gitconfig) - execute:

git config --global credential.helper manager

How to use

No further config is needed.

It works [automatically] when credentials are needed.

For example, when pushing to Azure DevOps, it opens a window and initializes an oauth2 flow to get your token.

ref:

How to split a delimited string into an array in awk?

I know this is kind of old question, but I thought maybe someone like my trick. Especially since this solution not limited to a specific number of items.

# Convert to an array
_ITEMS=($(echo "12|23|11" | tr '|' '\n'))

# Output array items
for _ITEM in "${_ITEMS[@]}"; do
  echo "Item: ${_ITEM}"
done

The output will be:

Item: 12
Item: 23
Item: 11

Reload chart data via JSON with Highcharts

EDIT: The response down below is more correct!

https://stackoverflow.com/a/8408466/387285

http://www.highcharts.com/ref/#series-object

HTML:

<SELECT id="list">
<OPTION VALUE="A">Data Set A
<OPTION VALUE="B">Data Set B
</SELECT>
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>

Javascript:

var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    },
    series: []
};

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'
    } 

    var chart = new Highcharts.Chart(options);    
});

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

Hope this helps! John

EDIT:

Check this out, its from something I've worked on in the past:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);
    }
});

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

Convert all data frame character columns to factors

Working with dplyr

library(dplyr)

df <- data.frame(A = factor(LETTERS[1:5]),
                 B = 1:5, C = as.logical(c(1, 1, 0, 0, 1)),
                 D = letters[1:5],
                 E = paste(LETTERS[1:5], letters[1:5]),
                 stringsAsFactors = FALSE)

str(df)

we get:

'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: chr  "a" "b" "c" "d" ...
 $ E: chr  "A a" "B b" "C c" "D d" ...

Now, we can convert all chr to factors:

df <- df%>%mutate_if(is.character, as.factor)
str(df)

And we get:

'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: chr  "a" "b" "c" "d" ...
 $ E: chr  "A a" "B b" "C c" "D d" ...

Let's provide also other solutions:

With base package:

df[sapply(df, is.character)] <- lapply(df[sapply(df, is.character)], 
                                                           as.factor)

With dplyr 1.0.0

df <- df%>%mutate(across(where(is.factor), as.character))

With purrr package:

library(purrr)

df <- df%>% modify_if(is.factor, as.character) 

Curl command line for consuming webServices?

Posting a string:

curl -d "String to post" "http://www.example.com/target"

Posting the contents of a file:

curl -d @soap.xml "http://www.example.com/target"

Find all special characters in a column in SQL Server 2008

The following transact SQL script works for all languages (international). The solution is not to check for alphanumeric but to check for not containing special characters.

DECLARE @teststring nvarchar(max)
SET @teststring = 'Test''Me'
SELECT 'IS ALPHANUMERIC: ' + @teststring
WHERE @teststring NOT LIKE '%[-!#%&+,./:;<=>@`{|}~"()*\\\_\^\?\[\]\'']%' {ESCAPE '\'}

Remove a child with a specific attribute, in SimpleXML for PHP

Even though SimpleXML doesn't have a detailed way to remove elements, you can remove elements from SimpleXML by using PHP's unset(). The key to doing this is managing to target the desired element. At least one way to do the targeting is using the order of the elements. First find out the order number of the element you want to remove (for example with a loop), then remove the element:

$target = false;
$i = 0;
foreach ($xml->seg as $s) {
  if ($s['id']=='A12') { $target = $i; break; }
  $i++;
}
if ($target !== false) {
  unset($xml->seg[$target]);
}

You can even remove multiple elements with this, by storing the order number of target items in an array. Just remember to do the removal in a reverse order (array_reverse($targets)), because removing an item naturally reduces the order number of the items that come after it.

Admittedly, it's a bit of a hackaround, but it seems to work fine.

Catch browser's "zoom" event in JavaScript

I'm using this piece of JavaScript to react to Zoom "events".
It polls the window width. (As somewhat suggested on this page (which Ian Elliott linked to): http://novemberborn.net/javascript/page-zoom-ff3 [archive])

Tested with Chrome, Firefox 3.6 and Opera, not IE.

Regards, Magnus

var zoomListeners = [];

(function(){
  // Poll the pixel width of the window; invoke zoom listeners
  // if the width has been changed.
  var lastWidth = 0;
  function pollZoomFireEvent() {
    var widthNow = jQuery(window).width();
    if (lastWidth == widthNow) return;
    lastWidth = widthNow;
    // Length changed, user must have zoomed, invoke listeners.
    for (i = zoomListeners.length - 1; i >= 0; --i) {
      zoomListeners[i]();
    }
  }
  setInterval(pollZoomFireEvent, 100);
})();

Updating the list view when the adapter data changes

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Since the only missing example is the ANDROID example, I'll add it. This technique uses a custom AsyncTask that should be declared inside your Activity class.

private class UploadFile extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // set a status bar or show a dialog to the user here
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // progress[0] is the current status (e.g. 10%)
        // here you can update the user interface with the current status
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    private String uploadFile() {

        String responseString = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://example.com/upload-file");

        try {
            AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
                new ProgressListener() {
                    @Override
                        public void transferred(long num) {
                            // this trigger the progressUpdate event
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
            });

            File myFile = new File("/my/image/path/example.jpg");

            ampEntity.addPart("fileFieldName", new FileBody(myFile));

            totalSize = ampEntity.getContentLength();
            httpPost.setEntity(ampEntity);

            // Making server call
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                responseString = EntityUtils.toString(httpEntity);
            } else {
                responseString = "Error, http status: "
                        + statusCode;
            }

        } catch (Exception e) {
            responseString = e.getMessage();
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        // if you want update the user interface with upload result
        super.onPostExecute(result);
    }

}

So, when you want to upload your file just call:

new UploadFile().execute();

ValueError: invalid literal for int () with base 10

Please test this function (split()) on a simple file. I was facing the same issue and found that it was because split() was not written properly (exception handling).

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

if path.exists(Score_file):
      try : 
         with open(Score_file , "rb") as prev_Scr:

            return Unpickler(prev_Scr).load()

    except EOFError : 

        return dict() 

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final").

When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.

Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.

libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)

This is for play 2.2.x. In previous versions there were some differences in the build files.

Restrict varchar() column to specific values?

You want a check constraint.

CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

You want something like:

ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
    CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))

You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

Why extend the Android Application class?

I see that this question is missing an answer. I extend Application because I use Bill Pugh Singleton implementation (see reference) and some of my singletons need context. The Application class looks like this:

public class MyApplication extends Application {

    private static final String TAG = MyApplication.class.getSimpleName();

    private static MyApplication sInstance;

    @Contract(pure = true)
    @Nullable
    public static Context getAppContext() {
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() called");
        sInstance = this;
    }
}

And the singletons look like this:

public class DataManager {

    private static final String TAG = DataManager.class.getSimpleName();

    @Contract(pure = true)
    public static DataManager getInstance() {
        return InstanceHolder.INSTANCE;
    }

    private DataManager() {
        doStuffRequiringContext(MyApplication.getAppContext());
    }

    private static final class InstanceHolder {
        @SuppressLint("StaticFieldLeak")
        private static final DataManager INSTANCE = new DataManager();
    }
}

This way I don't need to have a context every time I'm using a singleton and get lazy synchronized initialization with minimal amount of code.

Tip: updating Android Studio singleton template saves a lot of time.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

    protected String toCamelCase(CaseFormat caseFormat, String... words){
        if (words.length  == 0){
          throw new IllegalArgumentException("Word list is empty!");
        }

        String firstWord = words[0];
        String [] restOfWords = Arrays.copyOfRange(words, 1, words.length);

        StringBuffer buffer = new StringBuffer();
        buffer.append(firstWord);
        Arrays.asList(restOfWords).stream().forEach(w->buffer.append("_"+ w.toUpperCase()));

        return CaseFormat.UPPER_UNDERSCORE.to(caseFormat, buffer.toString());

    }

Object Dump JavaScript

function mydump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') {  
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { 
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += mydump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { 
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

Error:Cause: unable to find valid certification path to requested target

Most of the times when I face this issue. I remove replace https with http. It solves the issue.

How can I get the current contents of an element in webdriver

I know when you said "contents" you didn't mean this, but if you want to find all the values of all the attributes of a webelement this is a pretty nifty way to do that with javascript in python:

everything = b.execute_script(
    'var element = arguments[0];'
    'var attributes = {};'
    'for (index = 0; index < element.attributes.length; ++index) {'
    '    attributes[element.attributes[index].name] = element.attributes[index].value };'
    'var properties = [];'
    'properties[0] = attributes;'
    'var element_text = element.textContent;'
    'properties[1] = element_text;'
    'var styles = getComputedStyle(element);'
    'var computed_styles = {};'
    'for (index = 0; index < styles.length; ++index) {'
    '    var value_ = styles.getPropertyValue(styles[index]);'
    '    computed_styles[styles[index]] = value_ };'
    'properties[2] = computed_styles;'
    'return properties;', element)

you can also get some extra data with element.__dict__.

I think this is about all the data you'd ever want to get from a webelement.

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

Nesting optgroups in a dropdownlist/select

I have written a beautiful, nested select. Maybe it will help you.

https://jsfiddle.net/nomorepls/tg13w5r7/1/

_x000D_
_x000D_
function on_change_select(e) {
  alert(e.value, e.title, e.option, e.select);
}

$(document).ready(() => {
  // NESTED SELECT

  $(document).on('click', '.nested-cell', function() {
    $(this).next('div').toggle('medium');
  });

  $(document).on('change', 'input[name="nested-select-hidden-radio"]', function() {
    const parent = $(this).closest(".nested-select");
    const value = $(this).attr('value');
    const title = $(this).attr('title');
    const executer = parent.attr('executer');
    if (executer) {
      const event = new Object();
      event.value = value;
      event.title = title;
      event.option = $(this);
      event.select = parent;
      window[executer].apply(null, [event]);
    }
    parent.attr('value', value);
    parent.parent().slideToggle();
    const button = parent.parent().prev();
    button.toggleClass('active');
    button.addClass('selected');
    button.children('.nested-select-title').html(title);
  });

  $(document).on('click', '.nested-select-button', function() {
    const button = $(this);
    let select = button.parent().children('.nested-select-wrapper');

    if (!button.hasClass('active')) {
      select = select.detach();
      if (button.height() + button.offset().top + $(window).height() * 0.4 > $(window).height()) {
        select.insertBefore(button);
        select.css('margin-top', '-44vh');
        select.css('top', '0');
      } else {
        select.insertAfter(button);
        select.css('margin-top', '');
        select.css('top', '40px');
      }
    }
    select.slideToggle();
    button.toggleClass('active');
  });
});
_x000D_
.container {
  width: 200px;
  position: relative;
  top: 0;
  left: 0;
  right: 0;
  height: auto;
}

.nested-select-box {
  font-family: Arial, Helvetica, sans-serif;
  display: block;
  position: relative;
  width: 100%;
  height: fit-content;
  cursor: pointer;
  color: #2196f3;
  height: 40px;
  font-size: small;
  /* z-index: 2000; */
}

.nested-select-box .nested-select-button {
  border: 1px solid #2196f3;
  position: absolute;
  width: calc(100% - 20px);
  padding: 0 10px;
  min-height: 40px;
  word-wrap: break-word;
  margin: 0 auto;
  overflow: hidden;
}

.nested-select-box.danger .nested-select-button {
  border: 1px solid rgba(250, 33, 33, 0.678);
}

.nested-select-box .nested-select-button .nested-select-title {
  padding-right: 25px;
  padding-left: 25px;
  width: calc(100% - 50px);
  margin: auto;
  height: fit-content;
  text-align: center;
  vertical-align: middle;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.nested-select-box .nested-select-button.selected .nested-select-title {
  bottom: unset;
  top: 5px;
}

.nested-select-box .nested-select-button .nested-select-title-icon {
  position: absolute;
  height: 20px;
  width: 20px;
  top: 10px;
  bottom: 10px;
  right: 7px;
  transition: all 0.5s ease 0s;
}

.nested-select-box .nested-select-button.active .nested-select-title-icon {
  -moz-transform: scale(-1, -1);
  -o-transform: scale(-1, -1);
  -webkit-transform: scale(-1, -1);
  transform: scale(-1, -1);
}

.nested-select-box .nested-select-button .nested-select-title-icon::before,
.nested-select-box .nested-select-button .nested-select-title-icon::after {
  content: "";
  background-color: #2196f3;
  position: absolute;
  width: 70%;
  height: 2px;
  transition: all 0.5s ease 0s;
  top: 9px;
}

.nested-select-box .nested-select-button .nested-select-title-icon::before {
  transform: rotate(45deg);
  left: -1.6px;
}

.nested-select-box .nested-select-button .nested-select-title-icon::after {
  transform: rotate(-45deg);
  left: 7px;
}

.nested-select-box .nested-select-wrapper {
  width: 100%;
  top: 40px;
  position: relative;
  border: 1px solid #2196f3;
  background: #ffffff;
  z-index: 2005;
  opacity: 1;
}

.nested-select {
  font-family: Arial, Helvetica, sans-serif;
  display: inline-block;
  overflow-y: scroll;
  max-height: 40vh;
  width: calc(100% - 10px);
  padding: 5px;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.nested-select::-webkit-scrollbar {
  display: none;
}

.nested-select a,
.nested-select span {
  padding: 0 5px;
  border-radius: 3px;
  cursor: pointer;
  text-align: start;
}

.nested-select a:hover {
  background-color: #62b2f3;
  color: #ffffff;
}

.nested-select span:hover {
  background-color: #c4c4c4;
  color: #ffffff;
}

.nested-select input[type="radio"] {
  display: none;
}

.nested-select input[type="radio"]+span {
  display: block;
}

.nested-select input[type="radio"]:checked+span {
  background-color: #2196f3;
  color: #ffffff;
}

.nested-select div {
  margin-left: 15px;
}

.nested-select label>span:before,
.nested-select a:before {
  content: "\2022";
  margin-right: 5px;
}

.nested-select a {
  display: block;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="nested-select-box w-100">
    <div class="nested-select-button">
      <p class="nested-select-title">
        Account
      </p>
      <span class="nested-select-title-icon"></span>
    </div>
    <div class="nested-select-wrapper" style="display: none;">
      <div class="nested-select" executer="on_change_select">

        <label>
        <input title="Accounting and legal services" value="1565142000000891539" type="radio" name="nested-select-hidden-radio">
        <span>Accounting and legal services</span>
      </label>



        <label>
        <input title="Advertising agencies" value="1565142000000891341" type="radio" name="nested-select-hidden-radio">
        <span>Advertising agencies</span>
      </label>



        <a class="nested-cell">Advertising And Marketing</a>
        <div>



          <label>
          <input title="Advertising agencies" value="1565142000000891341" type="radio" name="nested-select-hidden-radio">
          <span>Advertising agencies</span>
        </label>



          <a class="nested-cell">Adwords - traffic</a>
          <div>



            <label>
            <input title="Adwords - traffic: Charters and general search" value="1565142000003929177" type="radio" name="nested-select-hidden-radio">
            <span>Adwords - traffic: Charters and general search</span>
          </label>



            <label>
            <input title="Adwords - traffic: Distance course" value="1565142000007821291" type="radio" name="nested-select-hidden-radio">
            <span>Adwords - traffic: Distance course</span>
          </label>



            <label>
            <input title="Adwords - traffic: Events" value="1565142000003929189" type="radio" name="nested-select-hidden-radio">
            <span>Adwords - traffic: Events</span>
          </label>



            <label>
            <input title="Adwords - traffic: Practices" value="1565142000003929165" type="radio" name="nested-select-hidden-radio">
            <span>Adwords - traffic: Practices</span>
          </label>



            <label>
            <input title="Adwords - traffic: Sailing tours" value="1565142000003929183" type="radio" name="nested-select-hidden-radio">
            <span>Adwords - traffic: Sailing tours</span>
          </label>



            <label>
            <input title="Adwords - traffic: Theoretical courses" value="1565142000003929171" type="radio" name="nested-select-hidden-radio">
            <span>Adwords - traffic: Theoretical courses</span>
          </label>



          </div>



          <label>
          <input title="Branded products" value="1565142000000891533" type="radio" name="nested-select-hidden-radio">
          <span>Branded products</span>
        </label>



          <label>
          <input title="Business cards" value="1565142000005438323" type="radio" name="nested-select-hidden-radio">
          <span>Business cards</span>
        </label>



          <a class="nested-cell">Facebook, Instagram - traffic</a>
          <div>



            <label>
            <input title="Facebook, Instagram - traffic: Charters and general search" value="1565142000003929145" type="radio" name="nested-select-hidden-radio">
            <span>Facebook, Instagram - traffic: Charters and general search</span>
          </label>



            <label>
            <input title="Facebook, Instagram - traffic: Distance course" value="1565142000007821285" type="radio" name="nested-select-hidden-radio">
            <span>Facebook, Instagram - traffic: Distance course</span>
          </label>



            <label>
            <input title="Facebook, Instagram - traffic: Events" value="1565142000003929157" type="radio" name="nested-select-hidden-radio">
            <span>Facebook, Instagram - traffic: Events</span>
          </label>



            <label>
            <input title="Facebook, Instagram - traffic: Practices" value="1565142000003929133" type="radio" name="nested-select-hidden-radio">
            <span>Facebook, Instagram - traffic: Practices</span>
          </label>



            <label>
            <input title="Facebook, Instagram - traffic: Sailing tours" value="1565142000003929151" type="radio" name="nested-select-hidden-radio">
            <span>Facebook, Instagram - traffic: Sailing tours</span>
          </label>



            <label>
            <input title="Facebook, Instagram - traffic: Theoretical courses" value="1565142000003929139" type="radio" name="nested-select-hidden-radio">
            <span>Facebook, Instagram - traffic: Theoretical courses</span>
          </label>



          </div>



          <label>
          <input title="Offline Advertising (posters, banners, partnerships)" value="1565142000000891377" type="radio" name="nested-select-hidden-radio">
          <span>Offline Advertising (posters, banners, partnerships)</span>
        </label>



          <label>
          <input title="Photos, video etc." value="1565142000000891371" type="radio" name="nested-select-hidden-radio">
          <span>Photos, video etc.</span>
        </label>



          <label>
          <input title="Prize fund" value="1565142000001404931" type="radio" name="nested-select-hidden-radio">
          <span>Prize fund</span>
        </label>



          <label>
          <input title="SEO" value="1565142000000891365" type="radio" name="nested-select-hidden-radio">
          <span>SEO</span>
        </label>



          <label>
          <input title="SMM Content creation (texts, copywriting)" value="1565142000000891389" type="radio" name="nested-select-hidden-radio">
          <span>SMM Content creation (texts, copywriting)</span>
        </label>



          <a class="nested-cell">YouTube</a>
          <div>



            <label>
            <input title="YouTube: travel expenses" value="1565142000008100163" type="radio" name="nested-select-hidden-radio">
            <span>YouTube: travel expenses</span>
          </label>



            <label>
            <input title="Youtube: video editing" value="1565142000008100157" type="radio" name="nested-select-hidden-radio">
            <span>Youtube: video editing</span>
          </label>



          </div>



        </div>

      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Binding an enum to a WinForms combo box, and then setting it

None of these worked for me, but this did (and it had the added benefit of being able to have a better description for the name of each enum). I'm not sure if it's due to .net updates or not, but regardless I think this is the best way. You'll need to add a reference to:

using System.ComponentModel;

enum MyEnum
{
    [Description("Red Color")]
    Red = 10,
    [Description("Blue Color")]
    Blue = 50
}

....

    private void LoadCombobox()
    {
        cmbxNewBox.DataSource = Enum.GetValues(typeof(MyEnum))
            .Cast<Enum>()
            .Select(value => new
            {
                (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
                value
            })
            .OrderBy(item => item.value)
            .ToList();
        cmbxNewBox.DisplayMember = "Description";
        cmbxNewBox.ValueMember = "value";
    }

Then when you want to access the data use these two lines:

        Enum.TryParse<MyEnum>(cmbxNewBox.SelectedValue.ToString(), out MyEnum proc);
        int nValue = (int)proc;

Is there an equivalent method to C's scanf in Java?

Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.

  • Use Integer.parseInt() to convert your string into Interger.
  • To print any string you can use System.out.println()

Example :

  int a;
  a = Integer.parseInt(args[0]);

and for Standard Input you can use codes like

  StdIn.readInt();
  StdIn.readString();

Response::json() - Laravel 5.1

You need to add use Response; facade in header at your file.

Only then you can successfully retrieve your data with

return Response::json($data);

Converting string to title case

Try this:

string myText = "a Simple string";

string asTitleCase =
    System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
    ToTitleCase(myText.ToLower());

As has already been pointed out, using TextInfo.ToTitleCase might not give you the exact results you want. If you need more control over the output, you could do something like this:

IEnumerable<char> CharsToTitleCase(string s)
{
    bool newWord = true;
    foreach(char c in s)
    {
        if(newWord) { yield return Char.ToUpper(c); newWord = false; }
        else yield return Char.ToLower(c);
        if(c==' ') newWord = true;
    }
}

And then use it like so:

var asTitleCase = new string( CharsToTitleCase(myText).ToArray() );

Jenkins Host key verification failed

Change to the jenkins user and run the command manually:

git ls-remote -h [email protected]:person/projectmarket.git HEAD

You will get the standard SSH warning when first connecting to a new host via SSH:

The authenticity of host 'bitbucket.org (207.223.240.181)' can't be established.
RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?

Type yes and press Enter. The host key for bitbucket.org will now be added to the ~/.ssh/known_hosts file and you won't get this error in Jenkins anymore.

Run Command Prompt Commands

Here is little simple and less code version. It will hide the console window too-

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.Start();

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

This actually works for me:

Per the README.SSO that comes with the jtdsd distribution:

In order for Single Sign On to work, jTDS must be able to load the native SPPI library ntlmauth.dll. Place this DLL anywhere in the system path (defined by the PATH system variable) and you're all set.

I placed it in my jre/bin folder

I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name.

jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local

What are .dex files in Android?

About the .dex File :

One of the most remarkable features of the Dalvik Virtual Machine (the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.

Dex file format:

 1. File Header
 2. String Table
 3. Class List
 4. Field Table
 5. Method Table
 6. Class Definition Table
 7. Field List
 8. Method List
 9. Code Header
10. Local Variable List

Android has documentation on the Dalvik Executable Format (.dex files). You can find out more over at the official docs: Dex File Format

.dex files are similar to java class files, but they were run under the Dalkvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.

You can decompile .dex using the dexdump tool which is provided in android-sdk.

There are also some Reverse Engineering Techniques to make a jar file or java class file from a .dex file.

Chrome ignores autocomplete="off"

I've just tried the following, and it appears to do the trick on Chrome 53 - it also disables the "Use password for:" drop down when entering the password field.

Simply set your password input type to text, and then add the onfocus handler (inline or via jQuery/vanilla JS) to set the type to password:

onfocus="this.setAttribute('type','password')"

Or even better:

onfocus="if(this.getAttribute('type')==='text') this.setAttribute('type','password')"

Why do I get permission denied when I try use "make" to install something?

The problem is frequently with 'secure' setup of mountpoints, such as /tmp

If they are mounted noexec (check with cat /etc/mtab and or sudo mount) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.

E.g. to remount temporarily:

 sudo mount -o remount,exec /tmp

Or to change permanently, remove noexec in /etc/fstab

Safest way to convert float to integer in python?

math.floor will always return an integer number and thus int(math.floor(some_float)) will never introduce rounding errors.

The rounding error might already be introduced in math.floor(some_large_float), though, or even when storing a large number in a float in the first place. (Large numbers may lose precision when stored in floats.)

Spring default behavior for lazy-init

The default behaviour is false:

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

I suggest reading up

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Add image to layout in ruby on rails

Anything in the public folder is accessible at the root path (/) so change your img tag to read:

<img src="/images/rss.jpg" alt="rss feed" />

If you wanted to use a rails tag, use this:

<%= image_tag("rss.jpg", :alt => "rss feed") %>

How to use format() on a moment.js duration?

I use:

var duration = moment.duration("09:30");
var str = moment(duration._data).format("HH:mm");

And I get "09:30" in var str.

How do I center this form in css?

_x000D_
_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
form {_x000D_
    width:90%;_x000D_
    background-color: #c0d7f8;_x000D_
}
_x000D_
<body>_x000D_
  <form>_x000D_
    <input type="text" value="abc">_x000D_
  </form>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Convert float64 column to int64 in Pandas

consider using

df['column name'].astype('Int64')

nan will be changed to NaN

How to query data out of the box using Spring data JPA by both Sort and Pageable?

 public List<Model> getAllData(Pageable pageable){
       List<Model> models= new ArrayList<>();
       modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
       return models;
   }