Programs & Examples On #Rawurl

Get value from SimpleXMLElement Object

For me its easier to use arrays than objects,

So, I convert an Xml-Object,

$xml = simplexml_load_file('xml_file.xml');    
$json_string = json_encode($xml);    
$result_array = json_decode($json_string, TRUE);

urlencode vs rawurlencode?

One practical reason to choose one over the other is if you're going to use the result in another environment, for example JavaScript.

In PHP urlencode('test 1') returns 'test+1' while rawurlencode('test 1') returns 'test%201' as result.

But if you need to "decode" this in JavaScript using decodeURI() function then decodeURI("test+1") will give you "test+1" while decodeURI("test%201") will give you "test 1" as result.

In other words the space (" ") encoded by urlencode to plus ("+") in PHP will not be properly decoded by decodeURI in JavaScript.

In such cases the rawurlencode PHP function should be used.

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

How to handle the `onKeyPress` event in ReactJS?

You need to call event.persist(); this method on your keyPress event. Example:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes

Thanks & Regards

P.S: React Version : 16.13.1

Work on a remote project with Eclipse via SSH

I had the same problem 2 years ago and I solved it in the following way:

1) I build my projects with makefiles, not managed by eclipse 2) I use a SAMBA connection to edit the files inside Eclipse 3) Building the project: Eclipse calles a "local" make with a makefile which opens a SSH connection to the Linux Host. On the SSH command line you can give parameters which are executed on the Linux host. I use for that parameter a makeit.sh shell script which call the "real" make on the linux host. The different targets for building you can give also by parameters from the local makefile --> makeit.sh --> makefile on linux host.

PHP + MySQL transactions examples

As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:

// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)

$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this

// note: this is meant for InnoDB tables. won't work with MyISAM tables.

try {

    $conn->autocommit(FALSE); // i.e., start transaction

    // assume that the TABLE groups has an auto_increment id field
    $query = "INSERT INTO groups (name) ";
    $query .= "VALUES ('$group_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    $group_id = $conn->insert_id; // last auto_inc id from *this* connection

    $query = "INSERT INTO group_membership (group_id,name) ";
    $query .= "VALUES ('$group_id','$member_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    // our SQL queries have been successful. commit them
    // and go back to non-transaction mode.

    $conn->commit();
    $conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {

    // before rolling back the transaction, you'd want
    // to make sure that the exception was db-related
    $conn->rollback(); 
    $conn->autocommit(TRUE); // i.e., end transaction   
}

Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.

How do I quickly rename a MySQL database (change schema name)?

I did it this way: Take backup of your existing database. It will give you a db.zip.tmp and then in command prompt write following

"C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin\mysql.exe" -h localhost -u root -p[password] [new db name] < "C:\Backups\db.zip.tmp"

How to install a package inside virtualenv?

Sharing what has worked for me in both Ubuntu and Windows. This is for python3. To do for python2, replace "3" with "2":

Ubuntu

pip install virtualenv --user
virtualenv -p python3 /tmp/VIRTUAL
source /tmp/VIRTUAL/bin/activate
which python3

To install any package: pip install package

To get out of the virtual environment: deactivate

To activate again: source /tmp/VIRTUAL/bin/activate

Full explanation here.

Windows

(Assuming you have MiniConda installed and are in the Start Menu > Anaconda > Anaconda Terminal)

conda create -n VIRTUAL python=3  
activate VIRTUAL

To install any package: pip install package or conda install package

To get out of the virtual environment: deactivate

To activate again: activate VIRTUAL

Full explanation here.

Set a button group's width to 100% and make buttons equal width?

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="btn-group btn-block">_x000D_
  <button type="button" data-toggle="dropdown" class="btn btn-default btn-xs  btn-block  dropdown-toggle">Actions <span class="caret"></span>_x000D_
<span class="sr-only">Toggle Dropdown</span></button><ul role="menu" class="dropdown-menu"><li><a href="#">Action one</a></li><li class="divider"></li><li><a href="#" >Action Two</a></li></ul></div>
_x000D_
_x000D_
_x000D_

Dynamic height for DIV

Set both to auto:

height: auto;
width: auto;

Making it:

#products
{
    height: auto;
    width: auto;
    padding:5px; margin-bottom:8px;
    border: 1px solid #EFEFEF;
}

How to make CSS3 rounded corners hide overflow in Chrome/Opera

Here look at how I done it; Jsfiddle

With the Code I put in, I managed to get it working on Webkit (Chrome/Safari) and Firefox. I don't know if it works with the latest version of Opera. Yes it does work under the latest version of Opera.

#wrapper {
  width: 300px; height: 300px;
  border-radius: 100px;
  overflow: hidden;
  position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
}

#box {
  width: 300px; height: 300px;
  background-color: #cde;
  border-radius: 100px;
  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  -o-border-radius: 100px;
}

Django - filtering on foreign key properties

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

How to run bootRun with spring profile via gradle task

For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts:

tasks.register("bootRunDev") {
    group = "application"
    description = "Runs this project as a Spring Boot application with the dev profile"
    doFirst {
        tasks.bootRun.configure {
            systemProperty("spring.profiles.active", "dev")
        }
    }
    finalizedBy("bootRun")
}

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

How to determine the screen width in terms of dp or dip at runtime in Android?

I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.

For future references:

Configuration configuration = yourActivity.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.

See Configuration class reference

Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

GitHub: invalid username or password

https://[email protected]/eurydyce/MDANSE.git is not an ssh url, it is an https one (which would require your GitHub account name, instead of 'git').

Try to use ssh://[email protected]:eurydyce/MDANSE.git or just [email protected]:eurydyce/MDANSE.git

git remote set-url origin [email protected]:eurydyce/MDANSE.git

The OP Pellegrini Eric adds:

That's what I did in my ~/.gitconfig file that contains currently the following entries [remote "origin"] [email protected]:eurydyce/MDANSE.git

This should not be in your global config (the one in ~/).
You could check git config -l in your repo: that url should be declared in the local config: <yourrepo>/.git/config.

So make sure you are in the repo path when doing the git remote set-url command.


As noted in Oliver's answer, an HTTPS URL would not use username/password if two-factor authentication (2FA) is activated.

In that case, the password should be a PAT (personal access token) as seen in "Using a token on the command line".

That applies only for HTTPS URLS, SSH is not affected by this limitation.

'App not Installed' Error on Android

I found that if I built my app with compileSdkVersion, buildToolsVersion, and targetSdkVersion all set to the default value of 30 in my build.gradle file, then the app would not install on my phone. However, if I changed them back down to version 29, it worked. What the issue turned out to be was that from SDK 30 onwards you need to select V2 jar signing. For more info see Why does the Android SDK 30 generate invalid APK files?

TypeScript, Looping through a dictionary

Shortest way to get all dictionary/object values:

Object.keys(dict).map(k => dict[k]);

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

Consider using the E.164 format. For full international support, you'd need a VARCHAR of 15 digits.

See Twilio's recommendation for more information on localization of phone numbers.

printf formatting (%d versus %u)

If I understand your question correctly, you need %p to show the address that a pointer is using, for example:

int main() {
    int a = 5;
    int *p = &a;
    printf("%d, %u, %p", p, p, p);

    return 0;
}

will output something like:

-1083791044, 3211176252, 0xbf66a93c

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.

Checkbox angular material checked by default

Set this in HTML:

    <div class="modal-body " [formGroup]="Form">
        <div class="">
            <mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="b"  [disabled]="true">  Display 2 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="c"  [disabled]="true">  Display 3 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="d"  [disabled]="true">  Display 4</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="e"  [disabled]="true"> Display 5 </mat-checkbox>
        </div>
    </div>

Changes in Ts file

this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});

Conditionvalidation in Ur Business logic

if(true){
this.Form.patch(a: true);
}

How to display an image from a path in asp.net MVC 4 and Razor view?

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>

How to trigger click on page load?

$(function(){

    $(selector).click();

});

Difference between multitasking, multithreading and multiprocessing?

Multitasking - This is basically multiprogramming in the context of a single-user interactive environment, in which the OS switches between several programs in main memory so as to give the illusion that several are running at once. Common scheduling algorithms used for multitasking are: Round-Robin, Priority Scheduling (multiple queues), Shortest-Process-Next.

MULTIPROCESSING is like the OS handling the different jobs in main memory in such a way that it gives its time to each and every job when other is busy for some task such as I/O operation. So as long as at least one job needs to execute, the cpu never sit idle. and here it is automatically handled by the OS,

PRINT statement in T-SQL

Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:

RAISERROR ('Your message', 0, 1) WITH NOWAIT

RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.

Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.

How do I create a simple Qt console application in C++?

You could fire an event into the quit() slot of your application even without connect(). This way, the event-loop does at least one turn and should process the events within your main()-logic:

#include <QCoreApplication>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication app( argc, argv );

    // do your thing, once

    QTimer::singleShot( 0, &app, &QCoreApplication::quit );
    return app.exec();
}

Don't forget to place CONFIG += console in your .pro-file, or set consoleApplication: true in your .qbs Project.CppApplication.

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

jquery: animate scrollLeft

You'll want something like this:


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

Asp.net 4.0 has not been registered

If ASP.NET 4.0 is not registered with IIS

*****Use this step if u cant access using run command*****

Go to

C Drive
-->>windows
-->>Microsoft.Net
-->>Framework
-->>v4.0.30319

(Choose whatever framework to register with IIS me selecting Framework 4)
-->>aspnet_regiis
(Double-click or right click & choose run as administrator)

HTML if image is not found

The usual way to handle this scenario is by setting the alt tag to something meaningful.

If you want a default image instead, then I suggest using a server-side technology to serve up your images, called using a similar format to:

<img src="ImageHandler.aspx?Img=Blue.jpg" alt="I am a picture" />

In the ImageHandler.aspx code, catch any file-not-found errors and serve up your default.jpg instead.

Calculate RSA key fingerprint

The fastest way if your keys are in an SSH agent:

$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin

Each key in the agent will be printed as:

4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)

WPF Check box: Check changed handling

I know this is an old question, but how about just binding to Command if using MVVM?

ex:

<CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>

For me it triggers on both Check and Uncheck.

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:

d = 1/norm(V)
V1 = V * d

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

ng-change get new value and original value

Also you can use

<select ng-change="updateValue(user, oldValue)"     
       ng-init="oldValue=0"
       ng-focus="oldValue=user.id"
       ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

How can I present a file for download from an MVC controller?

mgnoonan,

You can do this to return a FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

Multiple cases in switch statement

There is no syntax in C++ nor C# for the second method you mentioned.

There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.

Standardize data columns in R

The normalize function from the BBMisc package was the right tool for me since it can deal with NA values.

Here is how to use it:

Given the following dataset,

    ASR_API     <- c("CV",  "F",    "IER",  "LS-c", "LS-o")
    Human       <- c(NA,    5.8,    12.7,   NA, NA)
    Google      <- c(23.2,  24.2,   16.6,   12.1,   28.8)
    GoogleCloud <- c(23.3,  26.3,   18.3,   12.3,   27.3)
    IBM     <- c(21.8,  47.6,   24.0,   9.8,    25.3)
    Microsoft   <- c(29.1,  28.1,   23.1,   18.8,   35.9)
    Speechmatics    <- c(19.1,  38.4,   21.4,   7.3,    19.4)
    Wit_ai      <- c(35.6,  54.2,   37.4,   19.2,   41.7)
    dt     <- data.table(ASR_API,Human, Google, GoogleCloud, IBM, Microsoft, Speechmatics, Wit_ai)
> dt
   ASR_API Human Google GoogleCloud  IBM Microsoft Speechmatics Wit_ai
1:      CV    NA   23.2        23.3 21.8      29.1         19.1   35.6
2:       F   5.8   24.2        26.3 47.6      28.1         38.4   54.2
3:     IER  12.7   16.6        18.3 24.0      23.1         21.4   37.4
4:    LS-c    NA   12.1        12.3  9.8      18.8          7.3   19.2
5:    LS-o    NA   28.8        27.3 25.3      35.9         19.4   41.7

normalized values can be obtained like this:

> dtn <- normalize(dt, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
> dtn
   ASR_API      Human     Google GoogleCloud         IBM  Microsoft Speechmatics      Wit_ai
1:      CV         NA  0.3361245   0.2893457 -0.28468670  0.3247336  -0.18127203 -0.16032655
2:       F -0.7071068  0.4875320   0.7715885  1.59862532  0.1700986   1.55068347  1.31594762
3:     IER  0.7071068 -0.6631646  -0.5143923 -0.12409420 -0.6030768   0.02512682 -0.01746131
4:    LS-c         NA -1.3444981  -1.4788780 -1.16064578 -1.2680075  -1.24018782 -1.46198764
5:    LS-o         NA  1.1840062   0.9323361 -0.02919864  1.3762521  -0.15435044  0.32382788

where hand calculated method just ignores colmuns containing NAs:

> dt %>% mutate(normalizedHuman = (Human - mean(Human))/sd(Human)) %>% 
+ mutate(normalizedGoogle = (Google - mean(Google))/sd(Google)) %>% 
+ mutate(normalizedGoogleCloud = (GoogleCloud - mean(GoogleCloud))/sd(GoogleCloud)) %>% 
+ mutate(normalizedIBM = (IBM - mean(IBM))/sd(IBM)) %>% 
+ mutate(normalizedMicrosoft = (Microsoft - mean(Microsoft))/sd(Microsoft)) %>% 
+ mutate(normalizedSpeechmatics = (Speechmatics - mean(Speechmatics))/sd(Speechmatics)) %>% 
+ mutate(normalizedWit_ai = (Wit_ai - mean(Wit_ai))/sd(Wit_ai))
  ASR_API Human Google GoogleCloud  IBM Microsoft Speechmatics Wit_ai normalizedHuman normalizedGoogle
1      CV    NA   23.2        23.3 21.8      29.1         19.1   35.6              NA        0.3361245
2       F   5.8   24.2        26.3 47.6      28.1         38.4   54.2              NA        0.4875320
3     IER  12.7   16.6        18.3 24.0      23.1         21.4   37.4              NA       -0.6631646
4    LS-c    NA   12.1        12.3  9.8      18.8          7.3   19.2              NA       -1.3444981
5    LS-o    NA   28.8        27.3 25.3      35.9         19.4   41.7              NA        1.1840062
  normalizedGoogleCloud normalizedIBM normalizedMicrosoft normalizedSpeechmatics normalizedWit_ai
1             0.2893457   -0.28468670           0.3247336            -0.18127203      -0.16032655
2             0.7715885    1.59862532           0.1700986             1.55068347       1.31594762
3            -0.5143923   -0.12409420          -0.6030768             0.02512682      -0.01746131
4            -1.4788780   -1.16064578          -1.2680075            -1.24018782      -1.46198764
5             0.9323361   -0.02919864           1.3762521            -0.15435044       0.32382788

(normalizedHuman is made a list of NAs ...)

regarding the selection of specific columns for calculation, a generic method can be employed like this one:

data_vars <- df_full %>% dplyr::select(-ASR_API,-otherVarNotToBeUsed)
meta_vars <- df_full %>% dplyr::select(ASR_API,otherVarNotToBeUsed)
data_varsn <- normalize(data_vars, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
dtn <- cbind(meta_vars,data_varsn)

OpenCV - Saving images to a particular folder of choice

You can do it with OpenCV's function imwrite:

import cv2
cv2.imwrite('Path/Image.jpg', image_name)

Required attribute on multiple checkboxes with the same name?

You can make it with jQuery a less lines:

$(function(){

    var requiredCheckboxes = $(':checkbox[required]');

    requiredCheckboxes.change(function(){

        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        }

        else {
            requiredCheckboxes.attr('required', 'required');
        }
    });

});

With $(':checkbox[required]') you select all checkboxes with the attribute required, then, with the .change method applied to this group of checkboxes, you can execute the function you want when any item of this group changes. In this case, if any of the checkboxes is checked, I remove the required attribute for all of the checkboxes that are part of the selected group.

I hope this helps.

Farewell.

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Make an exception handler like this,

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

How do I remove a MySQL database?

If you are working in XAMPP and your query of drop database doesn't work then you can go to the operations tag where you find the column (drop the database(drop)), click that button and your database will be deleted.

What is private bytes, virtual bytes, working set?

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

ApiNotActivatedMapError for simple html page using google-places-api

To enable Api do this

  1. Go to API Manager
  2. Click on Overview
  3. Search for Google Maps JavaScript API(Under Google Maps APIs). Click on that
  4. You will find Enable button there. Click to enable API.

OR You can try this url: Maps JavaScript API

Hope this will solve the problem of enabling API.

Excel VBA App stops spontaneously with message "Code execution has been halted"

I have came across this issue few times during the development of one complex Excel VBA app. Sometimes Excel started to break VBA object quite randomly. And the only remedy was to reboot machine. After reboot, Excel usually started to act normally.

Soon I have found out that possible solution to this issue is to hit CTRL+Break once when macro is NOT running. Maybe this can help to you too.

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

demo - http://jsfiddle.net/victor_007/ywevz8ra/

added border for better view (testing)

more info about white-space

table{
    width:100%;
}
table td{
    white-space: nowrap;  /** added **/
}
table td:last-child{
    width:100%;
}

_x000D_
_x000D_
    table {_x000D_
      width: 100%;_x000D_
    }_x000D_
    table td {_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    table td:last-child {_x000D_
      width: 100%;_x000D_
    }
_x000D_
<table border="1">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

How to get http headers in flask?

from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']

Change the image source on rollover using jQuery

$('img').mouseover(function(){
  var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
  $(this).attr("src", newSrc); 
});
$('img').mouseout(function(){
  var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
  $(this).attr("src", newSrc); 
});

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

Combining CSS Pseudo-elements, ":after" the ":last-child"

You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.

li:last-child:before { content: "and "; }

li:last-child:after { content: "."; }

This works swimmingly. CSS is kind of amazing.

Change value of input onchange?

for jQuery we can use below:

by input name:

$('input[name="textboxname"]').val('some value');

by input class:

$('input[type=text].textboxclass').val('some value');

by input id:

$('#textboxid').val('some value');

Inner text shadow with CSS

I'm using it from this site, also it looks good. Have a look at it Inner shadow

How to remove the default link color of the html hyperlink 'a' tag?

<style>
a {
color:      ;
}
</style>

This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.

How to capitalize the first letter of text in a TextView in an Android Application

You can add Apache Commons Lang in Gradle like compile 'org.apache.commons:commons-lang3:3.4'

And use WordUtils.capitalizeFully(name)

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

javascript return true or return false when and how to use it?

returning true or false indicates that whether execution should continue or stop right there. So just an example

<input type="button" onclick="return func();" />

Now if func() is defined like this

function func()
{
 // do something
return false;
}

the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

Convert DataTable to List<T>

  1. IEnumerable<DataRow> rows = dataTable.AsEnumerable(); (System.Data.DataSetExtensions.dll)
  2. IEnumerable<DataRow> rows = dataTable.Rows.OfType<DataRow>(); (System.Core.dll)

Using Python's ftplib to get a directory listing, portably

Try to use ftp.nlst(dir).

However, note that if the folder is empty, it might throw an error:

files = []

try:
    files = ftp.nlst()
except ftplib.error_perm, resp:
    if str(resp) == "550 No files found":
        print "No files in this directory"
    else:
        raise

for f in files:
    print f

The process cannot access the file because it is being used by another process (File is created but contains nothing)

using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine(message);
}

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

How to set the Default Page in ASP.NET?

If using IIS 7 or IIS 7.5 you can use

<system.webServer>
    <defaultDocument>
        <files>
            <clear />
            <add value="CreateThing.aspx" />
        </files>
    </defaultDocument>
</system.webServer>

https://docs.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/

How do I select between the 1st day of the current month and current day in MySQL?

I found myself here after needing this same query for some Business Intelligence Queries I'm running on an e-commerce store. I wanted to add my solution as it may be helpful to others.

set @firstOfLastLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)))-1 DAY);
set @lastOfLastLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH));
set @firstOfLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)))-1 DAY);
set @lastOfLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH));
set @firstOfMonth = DATE_ADD(@lastOfLastMonth, INTERVAL 1 DAY);
set @today = CURRENT_DATE;

Today is 2019-10-08 so the output looks like

@firstOfLastLastMonth = '2019-08-01'
@lastOfLastLastMonth = '2019-08-31'
@firstOfLastMonth = '2019-09-01'
@lastOfLastMonth = '2019-09-30'
@firstOfMonth = '2019-10-01'
@today = '2019-10-08'

How to draw a filled triangle in android canvas?

You need remove path.moveTo after first initial.

Path path = new Path();
path.moveTo(point1_returned.x, point1_returned.y);
path.lineTo(point2_returned.x, point2_returned.y);
path.lineTo(point3_returned.x, point3_returned.y);
path.lineTo(point1_returned.x, point1_returned.y);
path.close();

How to analyse the heap dump using jmap in java

If you use Eclipse as your IDE I would recommend the excellent eclipse plugin memory analyzer

Another option is to use JVisualVM, it can read (and create) heap dumps as well, and is shipped with every JDK. You can find it in the bin directory of your JDK.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.

In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.

build.gradle

android {

    // [...]

    defaultConfig {

        // [...]

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // add the schema location to the source sets
    // used by Room, to test migrations
    sourceSets {
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }

    // [...]
}

Get Month name from month number

You want GetAbbreviatedMonthName

Apply pandas function to column to create multiple new columns?

Building off of user1827356 's answer, you can do the assignment in one pass using df.merge:

df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})), 
    left_index=True, right_index=True)

    textcol  feature1  feature2
0  0.772692  1.772692 -0.227308
1  0.857210  1.857210 -0.142790
2  0.065639  1.065639 -0.934361
3  0.819160  1.819160 -0.180840
4  0.088212  1.088212 -0.911788

EDIT: Please be aware of the huge memory consumption and low speed: https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/ !

How to read until EOF from cin in C++

You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.

#include <string>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>

int main()
{
// don't skip the whitespace while reading
  std::cin >> std::noskipws;

// use stream iterators to copy the stream to a string
  std::istream_iterator<char> it(std::cin);
  std::istream_iterator<char> end;
  std::string results(it, end);

  std::cout << results;
}

What is the purpose of XSD files?

Before understanding the XSD(XML Schema Definition) let me explain;

What is schema?

for example; emailID: peter#gmail

You can identify the above emailID is not valid because there is no @, .com or .net or .org.

We know the email schema it looks like [email protected].

Conclusion: Schema does not validate the data, It does the validation of structure.

XSD is actually one of the implementation of XML Schema. others we have

We use XSD to validate XML data.

moment.js 24h format

You can use

 moment("15", "hh").format('LT') 

to convert the time to 12 hours format like this 3:00 PM

Is it possible to import a whole directory in sass using @import?

This feature will never be part of Sass. One major reason is import order. In CSS, the files imported last can override the styles stated before. If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity. By keeping a list of imports (as you did in your example), you're being explicit with import order. This is essential if you want to be able to confidently override styles that are defined in another file or write mixins in one file and use them in another.

For a more thorough discussion, view this closed feature request here:

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Run an Ansible task only when the variable contains a specific string

If variable1 is a string, and you are searching for a substring in it, this should work:

when: '"value" in variable1'

if variable1 is an array or dict instead, in will search for the exact string as one of its items.

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Java LinkedHashMap get first or last entry

Can you try doing something like (to get the last entry):

linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];

ListView inside ScrollView is not scrolling on Android

The best solution is to use NestedScrollVew with RecyclerView or if you want to go with Listview then you can add header and footer view to this. For example:

View footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.outofoffice_footer_view, null, false);
infoListView.addFooterView(footerView);

c# datagridview doubleclick on row with FullRowSelect

In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:

    private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(e.RowIndex.ToString());
    }

Detect key input in Python

You could make a little Tkinter app:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

How to create JSON Object using String?

In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

(Android API 19-27. Kotlin 1.2.50)

How do I find the CPU and RAM usage using PowerShell?

Get-WmiObject Win32_Processor | Select LoadPercentage | Format-List

This gives you CPU load.

Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average

Getting Google+ profile picture url with user_id

Google had changed their policy so the old way for getting the Google profile image will not work now, which was

https://plus.google.com/s2/photos/profile/(user_id)?sz=150

New Way for doing this is

Request URL

https://www.googleapis.com/plus/v1/people/115950284...320?fields=image&key={YOUR_API_KEY}

That will give the Google profile image url in json format as given below

Response :

{
    "image": 
    {
         "url": "https://lh3.googleusercontent.com/-OkM...AANA/ltpH4BFZ2as/photo.jpg?sz=50"
    }
}

More parameters can be found to send with URL which you may need from here

For more detail you can also check the given question where I have answered for same type of problem How to get user image through user id in Google plus?

Is the size of C "int" 2 bytes or 4 bytes?

The only guarantees are that char must be at least 8 bits wide, short and int must be at least 16 bits wide, and long must be at least 32 bits wide, and that sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long) (same is true for the unsigned versions of those types).

int may be anywhere from 16 to 64 bits wide depending on the platform.

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

What is a tracking branch?

TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".

So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.

In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".

It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.

Let's rephrase your question to this:

What is a "Remote-tracking-branch?"

The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.


To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).

The following is an introduction/overview, but you might find this excellent article also informative.


WHAT GIT IS, AND WHAT IT'S FOR

A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.

A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.

The basic idea is to create a book so we can easily look backwards in time,

  • to compare past times, with now, or other moments in time, and
  • to re-create the past.

When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.


SNAPSHOTS AND TRACKING

tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)

In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.

Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.

Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.

One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.

For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.

This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.


COMMITS

A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:

  • an address or fixed place where we can find this commit, similar to its page number,
  • one snapshot of your project (of your file directory tree) at a given moment in time,
  • a caption or comment saying what the snapshot is of, or for,
  • the date and time of that snapshot,
  • who took the snapshot, and finally,
  • one, or more, links backwards in time to previous, related snapshots like to yesterday's snapshot, or to our parent or parents. In other words "links" are similar to pointers to the page numbers of other, older photos of myself, or when I am born to my immediate parents.

A commit is the most important part of a well organized photo album.


THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES

Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.

The git family tree structure is modeled on our own, human family trees.

In what follows to help understand links in a simple way, I'll refer to:

  • a parent-commit as simply a "parent", and
  • a child-commit as simply a "child" or "children" if plural.

You should understand this instinctively, as it is based on the tree of life:

  • A parent might have one or more children pointing back in time at them, and
  • children always have one or more parents they point to.

Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.

  • With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.

  • With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.

Line diagram of a simple, single parent chain linking backwards in time:

(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)

BRANCHES

branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)

A git branch also refers to two things:

  • a name given to a growing tip, (an identifier), and
  • the actual branch in the graph of links between commits.

More than one child pointing --at a--> parent, is what git calls "branching".

NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.

The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".

In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.

Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)

ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.

The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)

(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)

So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".

So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.

The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".

The master branch always exists.

Line diagram of: Commit1 with 2 children (or what we call a git "branch"):

                parent      children

                        +-- Commit <-- Commit <-- Commit (Branch named 'Tom')
                       /
                      v
(older) ... <-- Commit1 <-- Commit                       (Branch named 'master')    

Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.

So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.


MERGING

Children have one or more parents.

  • With just one parent this is just a simple parent <-- child commit.

  • With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.

Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):

                parents     child

           ... <-- Commit
                        v
                         \
(older) ... <-- Commit1 <-- Commit2  

REMOTE

This word is also used to mean 2 different things:

  • a remote repository, and
  • the local alias name for a remote repository, i.e. a name which points using a URL to a remote repository.

remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)

(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.

A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)

You can setup multiple remotes if you want to pull or push to multiple remote repositories.

Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).

origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)

Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.

upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia

upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)

This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.

REMOTE TRACKING BRANCH

A remote-tracking-branch is first, just a branch name, like any other branch name.

It points at a local growing tip, i.e. a recent commit in your local git repository.

But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.

remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)

Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.

Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.


TRACKING IN ACTION

First we begin tracking a file with git.

enter image description here

Here are the basic commands involved with file tracking:

$ mkdir mydir &&  cd mydir &&  git init             # create a new git repository

$ git branch                                        # this initially reports no branches
                                                    #  (IMHO this is a bug!)

$ git status -bs       # -b = branch; -s = short    # master branch is empty
## No commits yet on master

# ...
$ touch foo                                         # create a new file

$ vim foo                                           # modify it (OPTIONAL)


$ git add         foo; commit -m 'your description'  # start tracking foo 
$ git rm  --index foo; commit -m 'your description'  # stop  tracking foo 
$ git rm          foo; commit -m 'your description'  # stop  tracking foo & also delete foo

REMOTE TRACKING IN ACTION

$ git pull    # Essentially does:  get fetch; git merge    # to update our clone

There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.

Is there an Eclipse plugin to run system shell in the Console?

I really like StartExplorer but it is a contextual launcher rather than in - IDE shell so not sure if that is what you want

How do I get the current date in JavaScript?

The Shortest Answer is: new Date().toJSON().slice(0,10)

Targeting only Firefox with CSS

CSS support has binding to javascript, as a side note.

_x000D_
_x000D_
if (CSS.supports("( -moz-user-select:unset )")) {_x000D_
    console.log("FIREFOX!!!")_x000D_
}
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/CSS/Mozilla_Extensions

Tomcat 7: How to set initial heap size correctly?

You must not use =. Simply use this:

export CATALINA_OPTS="-Xms512M -Xmx1024M"

How to convert SQL Server's timestamp column to datetime format

Using cast you can get date from a timestamp field:

SELECT CAST(timestamp_field AS DATE) FROM tbl_name

How to clean up R memory (without the need to restart my PC)?

There is only so much you can do with rm() and gc(). As suggested by Gavin Simpson, even if you free the actual memory in R, Windows often won't reclaim it until you close R or it is needed because all the apparent Windows memory fills up.

This usually isn't a problem. However, if you are running large loops this can sometimes lead to fragmented memory in the long term, such that even if you free the memory and restart R - the fragmented memory may prevent you allocating large chunks of memory. Especially if other applications were allocated fragmented memory while you were running R. rm() and gc() may delay the inevitable, but more RAM is better.

Downgrade npm to an older version

Just replace @latest with the version number you want to downgrade to. I wanted to downgrade to version 3.10.10, so I used this command:

npm install -g [email protected]

If you're not sure which version you should use, look at the version history. For example, you can see that 3.10.10 is the latest version of npm 3.

jQuery Show-Hide DIV based on Checkbox Value

`Display

$('#cbxShowHide').click(function(){ this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show });`

Excluding directory when creating a .tar.gz file

Try removing the last / at the end of the directory path to exclude

tar -pczf MyBackup.tar.gz /home/user/public_html/ --exclude "/home/user/public_html/tmp" 

Forbidden :You don't have permission to access /phpmyadmin on this server

Edit file: sudo nano /etc/httpd/conf.d/phpMyAdmin.conf and replace yours with following:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   <IfModule mod_authz_core.c>
     # Apache 2.4
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
   </IfModule>
</Directory>

Restart Apache: service httpd restart

(phpMyAdmin v4.0.10.8)

Explanation of the UML arrows

Here's some explanations from the Visual Studio 2015 docs:

UML Class Diagrams: Reference: https://msdn.microsoft.com/library/dd409437%28VS.140%29.aspx

UML class diagram

5: Association: A relationship between the members of two classifiers.

5a: Aggregation: An association representing a shared ownership relationship. The Aggregation property of the owner role is set to Shared.

5b: Composition: An association representing a whole-part relationship. The Aggregation property of the owner role is set to Composite.

9: Generalization: The specific classifier inherits part of its definition from the general classifier. The general classifier is at the arrow end of the connector. Attributes, associations, and operations are inherited by the specific classifier. Use the Inheritance tool to create a generalization between two classifiers.

Package diagram

13: Import: A relationship between packages, indicating that one package includes all the definitions of another.

14: Dependency: The definition or implementation of the dependent classifier might change if the classifier at the arrowhead end is changed.

Realization relationship

15: Realization: The class implements the operations and attributes defined by the interface. Use the Inheritance tool to create a realization between a class and an interface.

16: Realization: An alternative presentation of the same relationship. The label on the lollipop symbol identifies the interface.

UML Class Diagrams: Guidelines: http://msdn.microsoft.com/library/dd409416%28VS.140%29.aspx

Properties of an Association

Aggregation: This appears as a diamond shape at one end of the connector. You can use it to indicate that instances at the aggregating role own or contain instances of the other.

Is Navigable: If true for only one role, an arrow appears in the navigable direction. You can use this to indicate navigability of links and database relations in the software.


Generalization: Generalization means that the specializing or derived type inherits attributes, operations, and associations of the general or base type. The general type appears at the arrowhead end of the relationship.

Realization: Realization means that a class implements the attributes and operations specified by the interface. The interface is at the arrow end of the connector.

Let me know if you have more questions.

MySQL: Curdate() vs Now()

Just for the fun of it:

CURDATE() = DATE(NOW())

Or

NOW() = CONCAT(CURDATE(), ' ', CURTIME())

Does Hibernate create tables in the database automatically

add following property in your hibernate.cfg.xml file

<property name="hibernate.hbm2ddl.auto">update</property>

BTW, in your Entity class, you must define your @Id filed like this:

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
private long id;

if you use the following definition, it maybe not work:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

Getting cursor position in Python

If you're doing automation and want to get coordinates of where to click, simplest and shortest approach would be:

import pyautogui

while True:
    print(pyautogui.position())

This will track your mouse position and would keep on printing coordinates.

Rails: call another controller action from a controller

The logic you present is not MVC, then not Rails, compatible.

  • A controller renders a view or redirect

  • A method executes code

From these considerations, I advise you to create methods in your controller and call them from your action.

Example:

 def index
   get_variable
 end

 private

 def get_variable
   @var = Var.all
 end

That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.

Vocabulary is extremely important that's why I insist much.

How to specify legend position in matplotlib in graph coordinates

According to the matplotlib legend documentation:

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

Thus, one could use:

plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y) position.

What is the difference between "px", "dip", "dp" and "sp"?

Pixels(px) – corresponds to actual pixels on the screen. This is used if you want to give in terms of absolute pixels for width or height.

Density-independent Pixels (dp or dip) – an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

Scale-independent Pixels(sp) – this is like the dp unit, but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user’s preference.

Always use dp and sp only. sp for font sizes and dp for everything else. It will make UI compatible for Android devices with different densities. You can learn more about pixel and dp from https://www.google.com/design/spec/layout/units-measurements.html#units-measurements-density-independent-pixels-dp-

Source url:- http://www.androidtutorialshub.com/what-is-the-difference-between-px-dp-dip-sp-on-android/

Perform a Shapiro-Wilk Normality Test

You failed to specify the exact columns (data) to test for normality. Use this instead

shapiro.test(heisenberg$HWWIchg)

PHP check if url parameter exists

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

Change your first line to

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}

How can I run a windows batch file but hide the command window?

If you write an unmanaged program and use CreateProcess API then you should initialize lpStartupInfo parameter of the type STARTUPINFO so that wShowWindow field of the struct is SW_HIDE and not forget to use STARTF_USESHOWWINDOW flag in the dwFlags field of STARTUPINFO. Another method is to use CREATE_NO_WINDOW flag of dwCreationFlags parameter. The same trick work also with ShellExecute and ShellExecuteEx functions.

If you write a managed application you should follows advices from http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx: initialize ProcessStartInfo with CreateNoWindow = true and UseShellExecute = false and then use as a parameter of . Exactly like in case of you can set property WindowStyle of ProcessStartInfo to ProcessWindowStyle.Hidden instead or together with CreateNoWindow = true.

You can use a VBS script which you start with wcsript.exe. Inside the script you can use CreateObject("WScript.Shell") and then Run with 0 as the second (intWindowStyle) parameter. See http://www.robvanderwoude.com/files/runnhide_vbs.txt as an example. I can continue with Kix, PowerShell and so on.

If you don't want to write any program you can use any existing utility like CMDOW /RUN /HID "c:\SomeDir\MyBatch.cmd", hstart /NOWINDOW /D=c:\scripts "c:\scripts\mybatch.bat", hstart /NOCONSOLE "batch_file_1.bat" which do exactly the same. I am sure that you will find much more such kind of free utilities.

In some scenario (for example starting from UNC path) it is important to set also a working directory to some local path (%SystemRoot%\system32 work always). This can be important for usage any from above listed variants of starting hidden batch.

RS256 vs HS256: What's the difference?

Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.

  • RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).

  • HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.

If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.

Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.

Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.

The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json, which contains the public key (or keys) of the account.

If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.

Create two threads, one display odd & other even numbers

package com.example;

public class MyClass  {
    static int mycount=0;
    static Thread t;
    static Thread t2;
    public static void main(String[] arg)
    {
        t2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " even \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>25)
                    System.exit(0);
                run();
            }
        });
        t=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " odd \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>26)
                    System.exit(0);
                run();
            }
        });
        t.start();
        t2.start();
    }
}

How do I download a file from the internet to my linux server with Bash

Using wget

wget -O /tmp/myfile 'http://www.google.com/logo.jpg'

or curl:

curl -o /tmp/myfile 'http://www.google.com/logo.jpg'

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

Why dividing two integers doesn't get a float?

Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.

EDIT: my answer makes me think of the classic old man saying "when I was your age..."

Run .jar from batch-file

Just the same way as you would do in command console. Copy exactly those commands in the batch file.

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

POST data to a URL in PHP

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

Jquery array.push() not working

another workaround:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. so example, if .each is used:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;

updating nodejs on ubuntu 16.04

Run these commands:

sudo apt-get update
sudo apt-get install build-essential libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
source ~/.profile
nvm ls-remote
nvm install v9.10.1
nvm use v9.10.1
node -v

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

How can I make a menubar fixed on the top while scrolling

The postition:absolute; tag positions the element relative to it's immediate parent. I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work. Therefore, to pull off the facebook floating menu, the position:fixed; tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.

Please see CSS postion attribute documentation when you can :)

Converting a UNIX Timestamp to Formatted Date String

$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);

This should work to.

"git checkout <commit id>" is changing branch to "no branch"

This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>

git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD

jQuery datepicker years shown

i think this may work as well

$(function () {
    $(".DatepickerInputdob").datepicker({
        dateFormat: "d M yy",
        changeMonth: true,
        changeYear: true,
        yearRange: '1900:+0',
        defaultDate: '01 JAN 1900'
    });

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

The common name in the certicate for api.evercam.io is for *.herokuapp.com and there are no alternative subject names in the certificate. This means, that the certificate for api.evercam.io does not match the hostname and therefore the certificate verification fails. Same as true for www.evercam.io, e.g. try https://www.evercam.io with a browser and you get the error message, that the name in the certificate does not match the hostname.

So it is a problem which needs to be fixed by evercam.io. If you don't care about security, man-in-the-middle attacks etc you might disable verification of the certificate (curl --insecure), but then you should ask yourself why you use https instead of http at all.

How to filter Android logcat by application?

On the left in the logcat view you have the "Saved Filters" windows. Here you can add a new logcat filter by Application Name (for example, com.your.package)

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

In my case and while installing VS 2015 on Windows7 64x SP1, I experienced the same so tried to cancel and download/install the KBKB2999226 separately and for some reason the standalone update installer also get stuck searching for updates.

enter image description here

Here what I did:

  1. When the VS installer stuck at the KB2999226 update I clicked cancel.
  2. Installer took me back to confirm cancellation, waited for a while then opened the windows task manager and ended the process of wuse.exe (windows standalone update installer)
  3. On the VS installer clicked "No" to return to installation process. The process was completed without errors.

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

Java JSON serialization - best practice

As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.

But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.

Android Studio is slow (how to speed up)?

I just want to share my case:

  1. if you need play-store library, don't compile all of it, just compile library that you need. example: if you only need maps library instead of compile 'com.google.android.gms:play-services:9.0.2' do this compile 'com.google.android.gms:play-services-maps:9.0.2' on your gradle
  2. Dont use OpenJDK for the java, I use java 7 oracle and it works well. if yout need to change default java do this on linux terminal sudo update-alternatives --config java and pick the number

I'm using ubuntu 32bit 4GB RAM. that's all the issue I ever encounter with AS.

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

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

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

How to use OUTPUT parameter in Stored Procedure

There are a several things you need to address to get it working

  1. The name is wrong its not @ouput its @code
  2. You need to set the parameter direction to Output.
  3. Don't use AddWithValue since its not supposed to have a value just you Add.
  4. Use ExecuteNonQuery if you're not returning rows

Try

SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());

What is the difference between HTTP status code 200 (cache) vs status code 304?

HTTP 304 is "not modified". Your web server is basically telling the browser "this file hasn't changed since the last time you requested it." Whereas an HTTP 200 is telling the browser "here is a successful response" - which should be returned when it's either the first time your browser is accessing the file or the first time a modified copy is being accessed.

For more info on status codes check out http://en.wikipedia.org/wiki/List_of_HTTP_status_codes.

Include headers when using SELECT INTO OUTFILE?

an example from my database table name sensor with colums (id,time,unit)

select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM sensor

Firebug like plugin for Safari browser

Why do you want to use Firebug if Safari already comes with great Developer tools? :)

As Matt said, you can enable them from the preferences menu.

Here you will find an overview, summarized, of the Safari's Web inspector, and how to use it:

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

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

You should use this request:

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

How to select a div element in the code-behind page?

You have make div as server control using following code,

<div class="tab-pane active" id="portlet_tab1" runat="server">

then this div will be accessible in code behind.

Create a root password for PHPMyAdmin

I just faced the mysql user password problem - ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO) - when I tried to do a do-release-upgrade on my operational system. So I corrected it in 2 steps.

Firstly, as I did not had access on phpmyadmin, so I followed the "Recover MySQL root password" step on the tutorial mensioned by ThoKra: https://www.howtoforge.com/setting-changing-resetting-mysql-root-passwords

Secondly, with one of the users that I know the password, I made some password changes to the others users through phpmyadmin itself according to SonDang's information.

How do I create a foreign key in SQL Server?

If you want to create two table's columns into a relationship by using a query try the following:

Alter table Foreign_Key_Table_name add constraint 
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references 
Another_Table_name(Another_Table_Column_name)

Pass a javascript variable value into input type hidden value

Hidden Field :

<input type="hidden" name="year" id="year">

Script :

<script type="text/javascript">
     var year = new Date();
     document.getElementById("year").value=(year.getFullYear());
</script>

Absolute Positioning & Text Alignment

position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;

Is there a Python equivalent of the C# null-coalescing operator?

Here's a function that will return the first argument that isn't None:

def coalesce(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

# Prints "banana"
print coalesce(None, "banana", "phone", None)

reduce() might needlessly iterate over all the arguments even if the first argument is not None, so you can also use this version:

def coalesce(*arg):
  for el in arg:
    if el is not None:
      return el
  return None

How to convert a selection to lowercase or uppercase in Sublime Text

For others needing a key binding:

{ "keys": ["ctrl+="], "command": "upper_case" },
{ "keys": ["ctrl+-"], "command": "lower_case" }

Reload an iframe with jQuery

If you are cross-domain, simply setting the src back to the same url will not always trigger a reload, even if the location hash changes.

Ran into this problem while manually constructing Twitter button iframes, which wouldn't refresh when I updated the urls.

Twitter like buttons have the form: .../tweet_button.html#&_version=2&count=none&etc=...

Since Twitter uses the document fragment for the url, changing the hash/fragment didn't reload the source, and the button targets didn't reflect my new ajax-loaded content.

You can append a query string parameter for force the reload (eg: "?_=" + Math.random() but that will waste bandwidth, especially in this example where Twitter's approach was specifically trying to enable caching.

To reload something which only changes with hash tags, you need to remove the element, or change the src, wait for the thread to exit, then assign it back. If the page is still cached, this shouldn't require a network hit, but does trigger the frame reload.

 var old = iframe.src;
 iframe.src = '';
 setTimeout( function () {
    iframe.src = old;
 }, 0);

Update: Using this approach creates unwanted history items. Instead, remove and recreate the iframe element each time, which keeps this back() button working as expected. Also nice not to have the timer.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)

Multi-character constant warnings

Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:

int x = *(int*)"abcd";

Or a bit more specific:

int x = *(int32_t*)"abcd";

One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):

int x = ((union {char s[5]; int number;}){"abcd"}).number;

/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");

Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

As many people have stated, the solution is to use C++11 features to avoid finally blocks. One of the features is unique_ptr.

Here is Mephane's answer written using RAII patterns.

#include <vector>
#include <memory>
#include <list>
using namespace std;

class Foo
{
 ...
};

void DoStuff(vector<string> input)
{
    list<unique_ptr<Foo> > myList;

    for (int i = 0; i < input.size(); ++i)
    {
      myList.push_back(unique_ptr<Foo>(new Foo(input[i])));
    }

    DoSomeStuff(myList);
}

Some more introduction to using unique_ptr with C++ Standard Library containers is here

Spring Boot - Cannot determine embedded database driver class for database type NONE

The same to @Anas. I can run it in Eclipse, but when i use "java -jar ..." run it, it giving me this error. Then i find my java build path is wrong, it missing the folder “src/main/resources”, so, the application can't find application.properties. When i add the “src/main/resources” folder in java build path, it worked.

And, you need add "@PropertySource({"application.properties"})" in your Application class.

Screenshot-1

Screenshot-2

Throw HttpResponseException or return Request.CreateErrorResponse?

Another case for when to use HttpResponseException instead of Response.CreateResponse(HttpStatusCode.NotFound), or other error status code, is if you have transactions in action filters and you want the transactions to be rolled back when returning an error response to the client.

Using Response.CreateResponse will not roll the transaction back, whereas throwing an exception will.

Dynamic SQL results into temp table in SQL Stored procedure

You can define a table dynamically just as you are inserting into it dynamically, but the problem is with the scope of temp tables. For example, this code:

DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE #T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO #T1 (Col1) VALUES ('This will not work.')
SELECT * FROM #T1

will return with the error "Invalid object name '#T1'." This is because the temp table #T1 is created at a "lower level" than the block of executing code. In order to fix, use a global temp table:

DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE ##T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO ##T1 (Col1) VALUES ('This will work.')
SELECT * FROM ##T1

Hope this helps, Jesse

Rotating a Div Element in jQuery

yeah you're not going to have much luck i think. Typically across the 3 drawing methods the major browsers use (Canvas, SVG, VML), text support is poor, I believe. If you want to rotate an image, then it's all good, but if you've got mixed content with formatting and styles, probably not.

Check out RaphaelJS for a cross-browser drawing API.

Converting pixels to dp

Preferably put in a Util.java class

public static float dpFromPx(final Context context, final float px) {
    return px / context.getResources().getDisplayMetrics().density;
}

public static float pxFromDp(final Context context, final float dp) {
    return dp * context.getResources().getDisplayMetrics().density;
}

.NET code to send ZPL to Zebra printers

The simplest solution is with copying files to shared printer.
Example in C#:

System.IO.File.Copy(inputFilePath, printerPath);

where:

  • inputFilePath - path to ZPL file (special extension is not required);
  • printerPath - path to shared(!) printer, for example: \127.0.0.1\zebraGX

How to uncheck a radio button?

Thanks Patrick, you made my day! It's mousedown you have to use. However I've improved the code so you can handle a group of radio buttons.

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());

Remove a cookie

If you want to delete the cookie completely from all your current domain then the following code will definitely help you.

unset($_COOKIE['hello']);
setcookie("hello", "", time() - 300,"/");

This code will delete the cookie variable completely from all your domain i.e; " / " - it denotes that cookie variable's value all set for all domain not just for current domain or path. time() - 300 denotes that it sets to a previous time so it will expire.

Thats how it's perfectly deleted.

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

Get Category name from Post ID

Use get_the_category() function.

$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);

HTML radio buttons allowing multiple selections

The name of the inputs must be the same to belong to the same group. Then the others will be automatically deselected when one is clicked.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

I've had a similar problem, but I wanted to use NDK version r9d due to project requirements.

In local.properties the path was set to ndk.dir=C\:\\Android\\ndk\\android-ndk-r9d but that lead to the problem:

No toolchains found in the NDK toolchains folder for ABI with prefix: [toolchain-name]

The solution was to:

  1. Install the newest NDK using sdk manager
  2. Copy the missing toolchain [toolchain-name] from the new ndk to the old. In my case from sdk\ndk-bundle\toolchains to \ndk\android-ndk-r9d\toolchains
  3. Repeat the process till all the required toolchains are there

It looks to me that the copied toolchains are not used, but for some reason it is needed to for them be there.

How to know if an object has an attribute in Python

hasattr() is the right answer. What I want to add is that hasattr() can also be used well in conjunction with assert (to avoid unnecessary if statements and make the code more readable):

assert hasattr(a, 'property'), 'object lacks property' 

As stated in another answer on SO: Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.

I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.

Here are essential parts of related functions in Start class look like:

ConfigureServices method:

    services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder
                                  .WithOrigins("http://localhost:4200")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  //.AllowCredentials()
                                  ;
                          });
    });

Configure method:

        app.UseCors(MyAllowSpecificOrigins);

Found this from:

Cleanest way to toggle a boolean variable in Java?

If you use Boolean NULL values and consider them false, try this:

static public boolean toggle(Boolean aBoolean) {
    if (aBoolean == null) return true;
    else return !aBoolean;
}

If you are not handing Boolean NULL values, try this:

static public boolean toggle(boolean aBoolean) {
   return !aBoolean;
}

These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.

Usage

boolean bTrue = true
boolean bFalse = false
boolean bNull = null

toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true

Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:

Boolean b = false
b = b.toggle() // == true

Convert MySql DateTime stamp into JavaScript's Date format

First you can give JavaScript's Date object (class) the new method 'fromYMD()' for converting MySQL's YMD date format into JavaScript format by splitting YMD format into components and using these date components:

Date.prototype.fromYMD=function(ymd)
{
  var t=ymd.split(/[- :]/); //split into components
  return new Date(t[0],t[1]-1,t[2],t[3]||0,t[4]||0,t[5]||0);
};

Now you can define your own object (funcion in JavaScript world):

function DateFromYMD(ymd)
{
  return (new Date()).fromYMD(ymd);
}

and now you can simply create date from MySQL date format;

var d=new DateFromYMD('2016-07-24');

How to replace a whole line with sed?

sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file

Detect Click into Iframe using JavaScript

Assumptions -

  1. Your script runs outside the iframe BUT NOT in the outermost window.top window. (For outermost window, other blur solutions are good enough)
  2. A new page is opened replacing the current page / a new page in a new tab and control is switched to new tab.

This works for both sourceful and sourceless iframes

var ifr = document.getElementById("my-iframe");
var isMouseIn;
ifr.addEventListener('mouseenter', () => {
    isMouseIn = true;
});
ifr.addEventListener('mouseleave', () => {
    isMouseIn = false;
});
window.document.addEventListener("visibilitychange", () => {
    if (isMouseIn && document.hidden) {
        console.log("Click Recorded By Visibility Change");
    }
});
window.addEventListener("beforeunload", (event) => {
    if (isMouseIn) {
        console.log("Click Recorded By Before Unload");
    }
});

If a new tab is opened / same page unloads and the mouse pointer is within the Iframe, a click is considered

Object cannot be cast from DBNull to other types

Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN

Actual Code which I faced error:

Before changed the code:

    if( ds.Tables[0].Rows[0][0] == null ) //   Which is not working

     {
            seqno  = 1; 
      }
    else
    {
          seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
     }

After changed the code:

   if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
        {
                    seqno  = 1; 
         }
            else
            {
                  seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
             }

Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.

Getting the filenames of all files in a folder

You could do it like that:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
  }
}

Do you want to only get JPEG files or all files?

How to change cursor from pointer to finger using jQuery?

How do you change your cursor to the finger (like for clicking on links) instead of the regular pointer?

This is very simple to achieve using the CSS property cursor, no jQuery needed.

You can read more about in: CSS cursor property and cursor - CSS | MDN

_x000D_
_x000D_
.default {_x000D_
  cursor: default;_x000D_
}_x000D_
.pointer {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<a class="default" href="#">default</a>_x000D_
_x000D_
<a class="pointer" href="#">pointer</a>
_x000D_
_x000D_
_x000D_

How to set the value of a hidden field from a controller in mvc

You need to write following code on controller suppose test is model, and Name, Address are field of this model.

public ActionResult MyMethod()
{
    Test test=new Test();
    var test.Name="John";
    return View(test);   
}

now use like like this on your view to give set value of hidden variable.

@model YourApplicationName.Model.Test

@Html.HiddenFor(m=>m.Name,new{id="hdnFlag"})

This will automatically set hidden value=john.

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

In Python how should I test if a variable is None, True or False

I would like to stress that, even if there are situations where if expr : isn't sufficient because one wants to make sure expr is True and not just different from 0/None/whatever, is is to be prefered from == for the same reason S.Lott mentionned for avoiding == None.

It is indeed slightly more efficient and, cherry on the cake, more human readable.

In [1]: %timeit (1 == 1) == True
38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]: %timeit (1 == 1) is True
33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Can promises have multiple arguments to onFulfilled?

Here is a CoffeeScript solution.

I was looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS

the answer of this guy Florian

promise = deferred.promise

promise.success = (fn) ->
  promise.then (data) ->
   fn(data.payload, data.status, {additional: 42})
  return promise

promise.error = (fn) ->
  promise.then null, (err) ->
    fn(err)
  return promise

return promise 

And to use it:

service.get().success (arg1, arg2, arg3) ->
    # => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
    # => err

How to link html pages in same or different folders?

use the relative path

main page might be: /index.html

secondary page: /otherFolder/otherpage.html

link would be like so:

<a href="/otherFolder/otherpage.html">otherpage</a>

Showing an image from an array of images - Javascript

Just as Diodeus said, you're comparing an Image to a HTMLDomObject. Instead compare their .src attribute:

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';

/* ... more images ... */

imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';

/*------------------------------------*/

function nextImage(element)
{
    var img = document.getElementById(element);

    for(var i = 0; i < imgArray.length;i++)
    {
        if(imgArray[i].src == img.src) // << check this
        {
            if(i === imgArray.length){
                document.getElementById(element).src = imgArray[0].src;
                break;
            }
            document.getElementById(element).src = imgArray[i+1].src;
            break;
        }
    }
}

Generics/templates in python?

Fortunately there has been some efforts for the generic programming in python . There is a library : generic

Here is the documentation for it: http://generic.readthedocs.org/en/latest/

It hasn't progress over years , but you can have a rough idea how to use & make your own library.

Cheers

AWS : The config profile (MyName) could not be found

Make sure you are in the correct VirtualEnvironment. I updated PyCharm and for some reason had to point my project at my VE again. Opening the terminal, I was not in my VE when attempting zappa update (and got this error). Restarting PyCharm, all back to normal.

Can Google Chrome open local links?

You can't link to file:/// from an HTML document that is not itself a file:/// for security reasons.

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

SQL string value spanning multiple lines in query

with your VARCHAR, you may also need to specify the length, or its usually good to

What about grabbing the text, making a sting of it, then putting it into the query witrh

String TableName = "ComplicatedTableNameHere";  
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere); 
String editTextString1 = editText1.getText().toString();  

BROKEN DOWN

String TableName = "ComplicatedTableNameHere";            
    //sets the table name as a string so you can refer to TableName instead of writing out your table name everytime

EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere); 
    //gets the text from your edit text fieldfield 
    //editText1 = your edit text name
    //EditTextIDhere = the id of your text field

String editTextString1 = editText1.getText().toString();  
    //sets the edit text as a string
    //editText1 is the name of the Edit text from the (EditText) we defined above
    //editTextString1 = the string name you will refer to in future

then use

       /* Insert data to a Table*/
       myDB.execSQL("INSERT INTO "
         + TableName
         + " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
         + " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");

Hope this helps some what...

NOTE each string is within

'"+stringname+"'

its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word

Return None if Dictionary key is not available

Use dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Not connecting to SQL Server over VPN

I was having this issue too with SQL Server 2017.

I'm on the same network as the server via VPN and can ping it. After being frustrated that no authentication method would work - I set up an SSH server on the SQL server - and I was able to connect normally. This confirmed the correct port wasn't being hit for some reason. I even created a new user accounts, domain accounts, firewall checks on both ends, etc...

The solution for me was: 1. Set Connection to strictly use TCP/IP on SSMS 2. Use a custom string to point to the default port (ex: Data Source=192.168.168.166,1433;)

All the other comments above haven't worked so far. It looks like it was mandatory to include the port (even though its default).

DOUBLE vs DECIMAL in MySQL

We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

How to get base url in CodeIgniter 2.*

You need to load the URL Helper in order to use base_url(). In your controller, do:

$this->load->helper('url');

Then in your view you can do:

echo base_url();

Running MSBuild fails to read SDKToolsPath

I had this same issue and had installed Windows SDK 7.0 and Windows SDK 7.1 which neither fixed the issue. The cause of the problem for me was that the offending class library was built with Target Framework of .NET Framework 2.0.

I changed it to .NET Framework 4.0 and worked locally and when checked in the Build server built it successfully.

How to identify numpy types in python?

To get the type, use the builtin type function. With the in operator, you can test if the type is a numpy type by checking if it contains the string numpy;

In [1]: import numpy as np

In [2]: a = np.array([1, 2, 3])

In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>

In [4]: 'numpy' in str(type(a))
Out[4]: True

(This example was run in IPython, by the way. Very handy for interactive use and quick tests.)

Blur or dim background when Android PopupWindow active

Maybe this repo will help for you:BasePopup

This is my repo, which is used to solve various problems of PopupWindow.

In the case of using the library, if you need to blur the background, just call setBlurBackgroundEnable(true).

See the wiki for more details.(Language in zh-cn)

BasePopup:wiki

How to set a value to a file input in HTML?

You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?

Open JQuery Datepicker by clicking on an image w/ no input field

To change the "..." when the mouse hovers over the calendar icon, You need to add the following in the datepicker options:

    showOn: 'button',
    buttonText: 'Click to show the calendar',
    buttonImageOnly: true, 
    buttonImage: 'images/cal2.png',

How to sum digits of an integer in java?

Sums all the digits regardless of number's size.

private static int sumOfAll(int num) {
    int sum = 0;

    if(num == 10) return 1;

    if(num > 10) {
        sum += num % 10;
        while((num = num / 10) >= 1) {
            sum += (num > 10) ? num%10 : num;
        }
    } else {
        sum += num;
    }
    return sum;
}

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

From Now() to Current_timestamp in Postgresql

Here is an example ...

select * from tablename where to_char(added_time, 'YYYY-MM-DD')  = to_char( now(), 'YYYY-MM-DD' )

added_time is a column name which I converted to char for match

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

How do I pass a method as a parameter in Python

Lots of good answers but strange that no one has mentioned using a lambda function.
So if you have no arguments, things become pretty trivial:

def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

method2(method1)

But say you have one (or more) arguments in method1:

def method1(param):
    return 'hello ' + str(param)

def method2(methodToRun):
    result = methodToRun()
    return result

Then you can simply invoke method2 as method2(lambda: method1('world')).

method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader

I find this much cleaner than the other answers mentioned here.

Should I always use a parallel stream when possible?

The Stream API was designed to make it easy to write computations in a way that was abstracted away from how they would be executed, making switching between sequential and parallel easy.

However, just because its easy, doesn't mean its always a good idea, and in fact, it is a bad idea to just drop .parallel() all over the place simply because you can.

First, note that parallelism offers no benefits other than the possibility of faster execution when more cores are available. A parallel execution will always involve more work than a sequential one, because in addition to solving the problem, it also has to perform dispatching and coordinating of sub-tasks. The hope is that you'll be able to get to the answer faster by breaking up the work across multiple processors; whether this actually happens depends on a lot of things, including the size of your data set, how much computation you are doing on each element, the nature of the computation (specifically, does the processing of one element interact with processing of others?), the number of processors available, and the number of other tasks competing for those processors.

Further, note that parallelism also often exposes nondeterminism in the computation that is often hidden by sequential implementations; sometimes this doesn't matter, or can be mitigated by constraining the operations involved (i.e., reduction operators must be stateless and associative.)

In reality, sometimes parallelism will speed up your computation, sometimes it will not, and sometimes it will even slow it down. It is best to develop first using sequential execution and then apply parallelism where

(A) you know that there's actually benefit to increased performance and

(B) that it will actually deliver increased performance.

(A) is a business problem, not a technical one. If you are a performance expert, you'll usually be able to look at the code and determine (B), but the smart path is to measure. (And, don't even bother until you're convinced of (A); if the code is fast enough, better to apply your brain cycles elsewhere.)

The simplest performance model for parallelism is the "NQ" model, where N is the number of elements, and Q is the computation per element. In general, you need the product NQ to exceed some threshold before you start getting a performance benefit. For a low-Q problem like "add up numbers from 1 to N", you will generally see a breakeven between N=1000 and N=10000. With higher-Q problems, you'll see breakevens at lower thresholds.

But the reality is quite complicated. So until you achieve experthood, first identify when sequential processing is actually costing you something, and then measure if parallelism will help.