Programs & Examples On #Shortest path

Shortest path problems are problems addressing finding the shortest path from a single source to a target source, usually in a graph.

Negative weights using Dijkstra's Algorithm

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

Why doesn't Dijkstra's algorithm work for negative weight edges?

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

How does a Breadth-First Search work when looking for Shortest Path?

Visiting this thread after some period of inactivity, but given that I don't see a thorough answer, here's my two cents.

Breadth-first search will always find the shortest path in an unweighted graph. The graph may be cyclic or acyclic.

See below for pseudocode. This pseudocode assumes that you are using a queue to implement BFS. It also assumes you can mark vertices as visited, and that each vertex stores a distance parameter, which is initialized as infinity.

mark all vertices as unvisited
set the distance value of all vertices to infinity
set the distance value of the start vertex to 0
if the start vertex is the end vertex, return 0
push the start vertex on the queue
while(queue is not empty)   
    dequeue one vertex (we’ll call it x) off of the queue
    if x is not marked as visited:
        mark it as visited
        for all of the unmarked children of x:
            set their distance values to be the distance of x + 1
            if the value of x is the value of the end vertex: 
                return the distance of x
            otherwise enqueue it to the queue
if here: there is no path connecting the vertices

Note that this approach doesn't work for weighted graphs - for that, see Dijkstra's algorithm.

Exists Angularjs code/naming conventions?

Check out this GitHub repository that describes best practices for AngularJS apps. It has naming conventions for different components. It is not complete, but it is community-driven so everyone can contribute.

C linked list inserting node at the end

I would like to mention the key before writing the code for your consideration.

//Key

temp= address of new node allocated by malloc function (member od alloc.h library in C )

prev= address of last node of existing link list.

next = contains address of next node

struct node {
    int data;
    struct node *next;
} *head;

void addnode_end(int a) {
    struct node *temp, *prev;
    temp = (struct node*) malloc(sizeof(node));
    if (temp == NULL) {
        cout << "Not enough memory";
    } else {
        node->data = a;
        node->next = NULL;
        prev = head;

        while (prev->next != NULL) {
            prev = prev->next;
        }

        prev->next = temp;
    }
}

How do I mock a static method that returns void with PowerMock?

You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources will throw the exception :

// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception

Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.

doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.


By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.

Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.

Hope that helps.

Regards

ICommand MVVM implementation

I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.

Teaser:

public class SampleViewModel: BaseViewModelStub
{
    public string Name { get; set; }

    [UiCommand]
    public void HelloWorld()
    {
        MessageBox.Show("Hello World!");
    }

    [UiCommand]
    public void Print()
    {
        MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
    }

    public bool CanPrint()
    {
        return !String.IsNullOrEmpty(Name);
    }
}

}

UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.

SQL statement to get column type

In vb60 you can do this:

Public Cn As ADODB.Connection
'open connection
Dim Rs As ADODB.Recordset
 Set Rs = Cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, UCase("Table"), UCase("field")))

'and sample (valRs is my function for rs.fields("CHARACTER_MAXIMUM_LENGTH").value):

 RT_Charactar_Maximum_Length = (ValRS(Rs, "CHARACTER_MAXIMUM_LENGTH"))
        rt_Tipo = (ValRS(Rs, "DATA_TYPE"))

HTML: how to force links to open in a new tab, not new window

It is possible!

This appears to override browser settings. Hope it works for you.

<script type="text/javascript">
// Popup window code
function newPopup(url) {
    popupWindow = window.open(url,'popUpWindow1','height=600,width=600,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>

<body>
  <a href="JavaScript:newPopup('http://stimsonstopmotion.wordpress.com');">Try me</a>
</body>

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

SUBSTRING may help for some cases, you can limit the size of the int.

SELECT CAST(SUBSTRING('X12312333333333', '([\d]{1,9})') AS integer);

Why fragments, and when to use fragments instead of activities?

I know this was already discussed to death, but I'd like to add some more points:

  • Frags can be used to populate Menus and can handle MenuItem clicks on their own. Thus giving futher modulation options for your Activities. You can do ContextualActionBar stuff and so on without your Activity knowing about it and can basically decouple it from the basic stuff your Activity handles (Navigation/Settings/About).

  • A parent Frag with child Frags can give you further options to modulize your components. E.g. you can easily swap Frags around, put new Frags inside a Pager or remove them, rearrange them. All without your Activity knowing anything about it just focusing on the higher level stuff.

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to find Oracle Service Name

Thanks to this thread (https://community.oracle.com/thread/473276)

select sys_context('userenv','service_name') from dual;

It can be executed with a regular user account, no need for sysdba rights

Truncate (not round off) decimal numbers in javascript

Number.prototype.trim = function(decimals) {
    var s = this.toString();
    var d = s.split(".");
    d[1] = d[1].substring(0, decimals);
    return parseFloat(d.join("."));
}

console.log((5.676).trim(2)); //logs 5.67

How to remove files that are listed in the .gitignore but still on the repository?

An easier way that works regardless of the OS is to do

git rm -r --cached .
git add .
git commit -m "Drop files from .gitignore"

You basically remove and re-add all files, but git add will ignore the ones in .gitignore.

Using the --cached option will keep files in your filesystem, so you won't be removing files from your disk.

Note: Some pointed out in the comments that you will lose the history of all your files. I tested this with git 2.27.0 on MacOS and it is not the case. If you want to check what is happening, check your git diff HEAD~1 before you push your commit.

How to delete session cookie in Postman?

Note that this answer applies only to the standalone Postman UI and not the Postman app/add-on for Chrome.

How to clear the cache in Postman (so that you are required to log in again when requesting a token, for example):

  • navigate to View: Show DevTools
  • navigate to the Application tab, then the Clear Storage view in the left menu
  • deselect all choices except Cache Storage, then click on ‘Clear site data’
  • restart Postman
  • you should now be prompted to log in again when requesting a new token

Oracle: is there a tool to trace queries, like Profiler for sql server?

I found an easy solution

Step1. connect to DB with an admin user using PLSQL or sqldeveloper or any other query interface

Step2. run the script bellow; in the S.SQL_TEXT column, you will see the executed queries

SELECT            
 S.LAST_ACTIVE_TIME,     
 S.MODULE,
 S.SQL_FULLTEXT, 
 S.SQL_PROFILE,
 S.EXECUTIONS,
 S.LAST_LOAD_TIME,
 S.PARSING_USER_ID,
 S.SERVICE                                                                       
FROM
 SYS.V_$SQL S, 
 SYS.ALL_USERS U
WHERE
 S.PARSING_USER_ID=U.USER_ID 
 AND UPPER(U.USERNAME) IN ('oracle user name here')   
ORDER BY TO_DATE(S.LAST_LOAD_TIME, 'YYYY-MM-DD/HH24:MI:SS') desc;

The only issue with this is that I can't find a way to show the input parameters values(for function calls), but at least we can see what is ran in Oracle and the order of it without using a specific tool.

Understanding inplace=True

When inplace=True is passed, the data is renamed in place (it returns nothing), so you'd use:

df.an_operation(inplace=True)

When inplace=False is passed (this is the default value, so isn't necessary), performs the operation and returns a copy of the object, so you'd use:

df = df.an_operation(inplace=False) 

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

You also need to annotate the method with @JavascriptInterface if your targetSdkVersion is >= 17 - because there is new security requirements in SDK 17, i.e. all javascript methods must be annotated with @JavascriptInterface. Otherwise you will see error like: Uncaught TypeError: Object [object Object] has no method 'processHTML' at null:1

File upload from <input type="file">

Try this small lib, works with Angular 5.0.0

Quickstart example with ng2-file-upload 1.3.0:

User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.

app.module.ts:

import {FileUploadModule} from "ng2-file-upload";

your.component.html:

...
  <button mat-button onclick="document.getElementById('myFileInputField').click()" >
    Select and upload file
  </button>
  <input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...

your.component.ts:

import {FileUploader} from 'ng2-file-upload';
...    
uploader: FileUploader;
...
constructor() {
   this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
   this.uploader.onErrorItem = item => {
       console.error("Failed to upload");
       this.clearUploadField();
   };
   this.uploader.onCompleteItem = (item, response) => {
       console.info("Successfully uploaded");
       this.clearUploadField();

       // (Optional) Parsing of response
       let responseObject = JSON.parse(response) as MyCustomClass;

   };

   // Asks uploader to start upload file automatically after selecting file
  this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}

private clearUploadField(): void {
    (<HTMLInputElement>window.document.getElementById('myFileInputField'))
    .value = "";
}

Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

Android: Proper Way to use onBackPressed() with Toast

You don't need a counter for back presses.

Just store a reference to the toast that is shown:

private Toast backtoast;

Then,

public void onBackPressed() {
    if(USER_IS_GOING_TO_EXIT) {
        if(backtoast!=null&&backtoast.getView().getWindowToken()!=null) {
            finish();
        } else {
            backtoast = Toast.makeText(this, "Press back to exit", Toast.LENGTH_SHORT);
            backtoast.show();
        }
    } else {
        //other stuff...
        super.onBackPressed();
    }
}

This will call finish() if you press back while the toast is still visible, and only if the back press would result in exiting the application.

Check if a string is a date value

This callable function works perfectly, returns true for valid date. Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):

function validateDate(isoDate) {

    if (isNaN(Date.parse(isoDate))) {
        return false;
    } else {
        if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
            return false;
        }
    }
    return true;
}

Does --disable-web-security Work In Chrome Anymore?

Check your windows task manager and make sure you kill all chrome processes before running the command.

Enabling/Disabling Microsoft Virtual WiFi Miniport

Microsoft Virtual WiFi Miniport should start and bind automatically to the underlying function driver. Try disabling and reenabling the AR9285 driver.

Is there a free GUI management tool for Oracle Database Express?

you can always use the web based management tool that comes with oracle express db.. have tried using it? you can access it through http://host:port/apex if i remember correctly...

Alternative solutions are Oracle SQL Developer, TOAD etc...

How to delete a workspace in Eclipse?

It's possible to remove the workspace in Eclipse without much complications. The options are available under Preferences->General->Startup and Shutdown->Workspaces.

Note that this does not actually delete the files from the system, it simply removes it from the list of suggested workspaces. It changes the org.eclipse.ui.ide.prefs file in Jon's answer from within Eclipse.

Access item in a list of lists

50 - List1[0][0] + List[0][1] - List[0][2]

List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

Is it because some culture format issue?

Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.

How can I make sure the result string is delimited by colon instead of dot?

I'd suggest specifying CultureInfo.InvariantCulture:

string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                CultureInfo.InvariantCulture);

Alternatively, you could just quote the time and date separators:

string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");

... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()        
    {
        DateTime now = DateTime.Now;
        CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
        Thread.CurrentThread.CurrentCulture = culture;
        Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
    }
} 

That produces output (on September 18th 2013) of:

11/12/1434 15:04:31.750

My guess is that your web service would be surprised by that!

I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:

string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)

How do I import a pre-existing Java project into Eclipse and get up and running?

In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'

Get the index of a certain value in an array in PHP

array_search should work fine, just tested this and it returns the keys as expected:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

jQuery checkbox checked state changed event

Bind to the change event instead of click. However, you will probably still need to check whether or not the checkbox is checked:

$(".checkbox").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

The main benefit of binding to the change event over the click event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change event. Redacted in comments

Also note that I've used this.checked instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.

Edit (see comments)

To get all checkboxes you have a couple of options. You can use the :checkbox pseudo-selector:

$(":checkbox")

Or you could use an attribute equals selector:

$("input[type='checkbox']")

How do I increase the RAM and set up host-only networking in Vagrant?

You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "4096"
end

This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "2048"
end

Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024] in your file, and adding the above code.

For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20" in your file toconfig.vm.network "private_network", ip: "199.188.44.20"

UINavigationBar custom back button without title

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Custom initialization
        self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];

    }
    return self; 
}

Just like Kyle Begeman does, you add the code above at your root view controller. All the sub view controller will be applied. Additionally, adding this in initWithCoder: method, you can apply the style for root view controllers in xib, storyboard or code based approaches.

Razor View throwing "The name 'model' does not exist in the current context"

I had the same issue, I created a new project and copied the web.config files as recommended in the answer by Gupta, but that didn't fix things for me. I checked answer by Alex and Liam, I thought this line must have been copied from the new web.config, but it looks like the new project itself didn't have this line (MVC5):

<add key="webpages:Version" value="3.0.0.0" />

Adding the line to the views/web.config file solved the issue for me.

Get current AUTO_INCREMENT value for any table

Query to check percentage "usage" of AUTO_INCREMENT for all tables of one given schema (except columns with type bigint unsigned):

SELECT 
  c.TABLE_NAME,
  c.COLUMN_TYPE,
  c.MAX_VALUE,
  t.AUTO_INCREMENT,
  IF (c.MAX_VALUE > 0, ROUND(100 * t.AUTO_INCREMENT / c.MAX_VALUE, 2), -1) AS "Usage (%)" 
FROM 
  (SELECT 
     TABLE_SCHEMA,
     TABLE_NAME,
     COLUMN_TYPE,
     CASE 
        WHEN COLUMN_TYPE LIKE 'tinyint(1)' THEN 127
        WHEN COLUMN_TYPE LIKE 'tinyint(1) unsigned' THEN 255
        WHEN COLUMN_TYPE LIKE 'smallint(%)' THEN 32767
        WHEN COLUMN_TYPE LIKE 'smallint(%) unsigned' THEN 65535
        WHEN COLUMN_TYPE LIKE 'mediumint(%)' THEN 8388607
        WHEN COLUMN_TYPE LIKE 'mediumint(%) unsigned' THEN 16777215
        WHEN COLUMN_TYPE LIKE 'int(%)' THEN 2147483647
        WHEN COLUMN_TYPE LIKE 'int(%) unsigned' THEN 4294967295
        WHEN COLUMN_TYPE LIKE 'bigint(%)' THEN 9223372036854775807
        WHEN COLUMN_TYPE LIKE 'bigint(%) unsigned' THEN 0
        ELSE 0
     END AS "MAX_VALUE" 
   FROM 
     INFORMATION_SCHEMA.COLUMNS
     WHERE EXTRA LIKE '%auto_increment%'
   ) c

   JOIN INFORMATION_SCHEMA.TABLES t ON (t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME)

WHERE
 c.TABLE_SCHEMA = 'YOUR_SCHEMA' 
ORDER BY
 `Usage (%)` DESC;

T-SQL Subquery Max(Date) and Joins

All other answers must work, but using your same syntax (and understanding why the error)

SELECT * FROM MyParts LEFT JOIN MyPrice ON MyParts.Partid = MyPrice.Partid WHERE 
MyPart.PriceDate = (SELECT MAX(MyPrice2.PriceDate) FROM MyPrice as MyPrice2 
WHERE MyPrice2.Partid =  MyParts.Partid)

Difference between `Optional.orElse()` and `Optional.orElseGet()`

I reached here for the problem Kudo mentioned.

I'm sharing my experience for others.

orElse, or orElseGet, that is the question:

static String B() {
    System.out.println("B()...");
    return "B";
}

public static void main(final String... args) {
    System.out.println(Optional.of("A").orElse(B()));
    System.out.println(Optional.of("A").orElseGet(() -> B()));
}

prints

B()...
A
A

orElse evaluates the value of B() interdependently of the value of the optional. Thus, orElseGet is lazy.

How do I fix a Git detached head?

Detached head means you are no longer on a branch, you have checked out a single commit in the history (in this case the commit previous to HEAD, i.e. HEAD^).

If you want to delete your changes associated with the detached HEAD

You only need to checkout the branch you were on, e.g.

git checkout master

Next time you have changed a file and want to restore it to the state it is in the index, don't delete the file first, just do

git checkout -- path/to/foo

This will restore the file foo to the state it is in the index.

If you want to keep your changes associated with the detached HEAD

  1. Run git branch tmp - this will save your changes in a new branch called tmp.
  2. Run git checkout master
  3. If you would like to incorporate the changes you made into master, run git merge tmp from the master branch. You should be on the master branch after running git checkout master.

int to unsigned int conversion

i=-62 . If you want to convert it to a unsigned representation. It would be 4294967234 for a 32 bit integer. A simple way would be to

num=-62
unsigned int n;
n = num
cout<<n;

4294967234

How to inject a Map using the @Value Spring Annotation?

Following worked for me:

SpingBoot 2.1.7.RELEASE

YAML Property (Notice value sourrounded by single quotes)

property:
   name: '{"key1": false, "key2": false, "key3": true}'

In Java/Kotlin annotate field with (Notice use of #) (For java no need to escape '$' with '\')

@Value("#{\${property.name}}")

How to get the date from the DatePicker widget in Android?

If you are using Kotlin, you can define an extension function for DatePicker:

fun DatePicker.getDate(): Date {
    val calendar = Calendar.getInstance()
    calendar.set(year, month, dayOfMonth)
    return calendar.time
}

Then, it's just: datePicker.getDate(). As if it had always existed.

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

Python: How to get values of an array at certain index positions?

Just index using you ind_pos

ind_pos = [1,5,7]
print (a[ind_pos]) 
[88 85 16]


In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]

In [56]: import numpy as np

In [57]: arr = np.array(a)

In [58]: ind_pos = [1,5,7]

In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

For everyone else who has no duplicate Listen directives and no running processes on the port: check that you don't accidentally include ports.conf twice in apache2.conf (as I did due to a bad merge).

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

How to extract text from an existing docx file using python-docx

I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my case it was due to adding requireSSL=true to httpcookies in webconfig which made the AntiForgeryToken stop working. Example:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>

To make both requireSSL=true and @Html.AntiForgeryToken() work I added this line inside the Application_BeginRequest in Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
  {
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
  }

xpath find if node exists

<xsl:if test="xpath-expression">...</xsl:if>

so for example

<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>

Cannot find or open the PDB file in Visual Studio C++ 2010

Working with VS 2013.
Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off

It will disable the display of modules loaded.

Encode URL in JavaScript?

The best answer is to use encodeURIComponent on values in the query string (and nowhere else).

However, I find that many APIs want to replace " " with "+" so I've had to use the following:

const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value

escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.

And as @Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.

Example:

const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;

Find the 2nd largest element in an array with minimum number of comparisons

The optimal algorithm uses n+log n-2 comparisons. Think of elements as competitors, and a tournament is going to rank them.

First, compare the elements, as in the tree

   |
  / \
 |   |
/ \ / \
x x x x

this takes n-1 comparisons and each element is involved in comparison at most log n times. You will find the largest element as the winner.

The second largest element must have lost a match to the winner (he can't lose a match to a different element), so he's one of the log n elements the winner has played against. You can find which of them using log n - 1 comparisons.

The optimality is proved via adversary argument. See https://math.stackexchange.com/questions/1601 or http://compgeom.cs.uiuc.edu/~jeffe/teaching/497/02-selection.pdf or http://www.imada.sdu.dk/~jbj/DM19/lb06.pdf or https://www.utdallas.edu/~chandra/documents/6363/lbd.pdf

How to shift a block of code left/right by one space in VSCode?

Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)

Search for cursorColumnSelectDown or cursorColumnSelectUp which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow

How can you print a variable name in python?

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

Left-pad printf with spaces

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

PostgreSQL ERROR: canceling statement due to conflict with recovery

It might be too late for the answer but we face the same kind of issue on the production. Earlier we have only one RDS and as the number of users increases on the app side, we decided to add Read Replica for it. Read replica works properly on the staging but once we moved to the production we start getting the same error.

So we solve this by enabling hot_standby_feedback property in the Postgres properties. We referred the following link

https://aws.amazon.com/blogs/database/best-practices-for-amazon-rds-postgresql-replication/

I hope it will help.

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

Create a custom callback in JavaScript

When calling the callback function, we could use it like below:

consumingFunction(callbackFunctionName)

Example:

// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
  console.log(unknown);
}

// This is a consuming function.
function getInfo(thenCallback) {
  // When we define the function we only know the data but not
  // the action. The action will be deferred until excecuting.
  var info = 'I know now';
  if (typeof thenCallback === 'function') {
    thenCallback(info);    
  }
}

// Start.
getInfo(callbackFunction); // I know now

This is the Codepend with full example.

Leaflet - How to find existing markers, and delete markers?

Have you tried layerGroup yet?

Docs here https://leafletjs.com/reference-1.2.0.html#layergroup

Just create a layer, add all marker to this layer, then you can find and destroy marker easily.

var markers = L.layerGroup()
const marker = L.marker([], {})
markers.addLayer(marker)

How can you export the Visual Studio Code extension list?

Open the Visual Studio Code console and write:

code --list-extensions (or code-insiders --list-extensions if Visual Studio Code insider is installed)

Then share the command line with colleagues:

code --install-extension {ext1} --install-extension {ext2} --install-extension {extN} replacing {ext1}, {ext2}, ... , {extN} with the extension you listed

For Visual Studio Code insider: code-insiders --install-extension {ext1} ...

If they copy/paste it in Visual Studio Code command-line terminal, they'll install the shared extensions.

More information on command-line-extension-management.

How to use ImageBackground to set background image for screen in react-native

Two options:

  1. Try setting width and height to width and height of the device screen
  2. Good old position absolute

Code for #2:

 render(){
    return(
        <View style={{ flex: 1 }}>
           <Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
           <Text>Hey look, image background</Text>
        </View>
    )
}

Edit: For option #2 you can experiment with resizeMode="stretch|cover"

Edit 2: Keep in mind that option #2 renders the image and then everything after that in this order, which means that some pixels are rendered twice, this might have a very small performance impact (usually unnoticeable) but just for your information

super() raises "TypeError: must be type, not classobj" for new-style class

The problem is that super needs an object as an ancestor:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

On closer examination one finds:

>>> type(myclass)
classobj

But:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

SOAP or REST for Web Services?

I am looking at the same, and i think, they are different tools for different problems.

Simple Object Access Protocol (SOAP) standard an XML language defining a message architecture and message formats, is used by Web services it contain a description of the operations. WSDL is an XML-based language for describing Web services and how to access them. will run on SMTP,HTTP,FTP etc. Requires middleware support, well defined mechanisam to define services like WSDL+XSD, WS-Policy SOAP will return XML based data SOAP provide standards for security and reliability

Representational State Transfer (RESTful) web services. they are second generation Web Services. RESTful web services, communicate via HTTP than SOAP-based services and do not require XML messages or WSDL service-API definitions. for REST no middleware is required only HTTP support is needed.WADL Standard, REST can return XML, plain text, JSON, HTML etc

It is easier for many types of clients to consume RESTful web services while enabling the server side to evolve and scale. Clients can choose to consume some or all aspects of the service and mash it up with other web-based services.

  1. REST uses standard HTTP so it is simplerto creating clients, developing APIs
  2. REST permits many different data formats like XML, plain text, JSON, HTML where as SOAP only permits XML.
  3. REST has better performance and scalability.
  4. Rest and can be cached and SOAP can't
  5. Built-in error handling where SOAP has No error handling
  6. REST is particularly useful PDA and other mobile devices.

REST is services are easy to integrate with existing websites.

SOAP has set of protocols, which provide standards for security and reliability, among other things, and interoperate with other WS conforming clients and servers. SOAP Web services (such as JAX-WS) are useful in handling asynchronous processing and invocation.

For Complex API's SOAP will be more usefull.

C dynamically growing array

I can use pointers, but I am a bit afraid of using them.

If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.

If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)

typedef struct {
  int *array;
  size_t used;
  size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
  a->array = malloc(initialSize * sizeof(int));
  a->used = 0;
  a->size = initialSize;
}

void insertArray(Array *a, int element) {
  // a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
  // Therefore a->used can go up to a->size 
  if (a->used == a->size) {
    a->size *= 2;
    a->array = realloc(a->array, a->size * sizeof(int));
  }
  a->array[a->used++] = element;
}

void freeArray(Array *a) {
  free(a->array);
  a->array = NULL;
  a->used = a->size = 0;
}

Using it is just as simple:

Array a;
int i;

initArray(&a, 5);  // initially 5 elements
for (i = 0; i < 100; i++)
  insertArray(&a, i);  // automatically resizes as necessary
printf("%d\n", a.array[9]);  // print 10th element
printf("%d\n", a.used);  // print number of elements
freeArray(&a);

how to use LIKE with column name

You're close.

The LIKE operator works with strings (CHAR, NVARCHAR, etc). so you need to concattenate the '%' symbol to the string...


MS SQL Server:

SELECT * FROM table1,table2 WHERE table1.x LIKE table2.y + '%'


Use of LIKE, however, is often slower than other operations. It's useful, powerful, flexible, but has performance considerations. I'll leave those for another topic though :)


EDIT:

I don't use MySQL, but this may work...

SELECT * FROM table1,table2 WHERE table1.x LIKE CONCAT(table2.y, '%')

Set default value of javascript object attributes

This seems to me the most simple and readable way of doing so:

let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}

options = Object.assign({}, default_options, options)

Object.assign() reference

How to set the JDK Netbeans runs on?

I had this message too because today i decided to relocate my different jdk in the same directory. I have decided to uninstall all through program manager of window. After that, of course i had the message below.

"Cannot locate java installation in specified jdkhome C:\Program Files (x86)\Java\jdk1.7.0_60 Do you want to try to use default version ?"

A new install of the jdk does not resolve the problem. Ok you can configure that in menu Tool > java platforms but in my case i had to fix my netbeans.conf

i had the line below

netbeans_jdkhome="C:\Program Files\Java\jdk1.7.0_60"

and i replace it by

netbeans_jdkhome="C:\devtools\Java\jdk1.8.0_25"

Android: How can I print a variable on eclipse console?

Window->Show View->Other…->Android->LogCat

Add a custom attribute to a Laravel / Eloquent model on load?

The last thing on the Laravel Eloquent doc page is:

protected $appends = array('is_admin');

That can be used automatically to add new accessors to the model without any additional work like modifying methods like ::toArray().

Just create getFooBarAttribute(...) accessor and add the foo_bar to $appends array.

Getting multiple selected checkbox values in a string in javascript and PHP

This is a variation to get all checked checkboxes in all_location_id without using an "if" statement

var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');

var aIds = [];

for(var x = 0, l = all_location_id.length; x < l;  x++)
{
    aIds.push(all_location_id[x].value);
}

var str = aIds.join(', ');

console.log(str);

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

How to show uncommitted changes in Git and some Git diffs in detail

I had a situation of git status showing changes, but git diff printing nothing, although there were changes in several lines. However:

$ git diff data.txt > myfile
$ cat myfile
<prints diff>

Git 2.20.1 on raspbian. Other commands like git checkout, git pull are printing to stdout without problems.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

How to export/import PuTTy sessions list?

For those of you who need to import Putty from offline registry file e.g. when you are recovering from crashed system or simply moving to a new machine and grabbing data off that old drive there is one more solution worth mentioning:

http://www.nirsoft.net/utils/registry_file_offline_export.html

This great and free console application will export the entire registry or only a specific registry key. In my case i simply copied the registry file from an old drive to the same directory as the exporter tool and then i used following command and syntax in CMD window run as administrator:

RegFileExport.exe NTUSER.DAT putty.reg "HKEY_CURRENT_USER\Software\SimonTatham"

After importing the .reg file and starting Putty everything was there. Simple and efficient.

Automatically plot different colored lines

Late to the party. I was looking into this myself and just found about this axes option called ColorOrder you can specify the colour order for the session or just for the figure and then just plot an array and let MATLAB automatically cycle through the colours specified.

see Changing the Default ColorOrder

example

set(0,'DefaultAxesColorOrder',jet(5))
A=rand(10,5);
plot(A);

IDENTITY_INSERT is set to OFF - How to turn it ON?

Add set off also

 SET IDENTITY_INSERT Genre ON

    INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

    SET IDENTITY_INSERT Genre  OFF

ContractFilter mismatch at the EndpointDispatcher exception

Also it might be useful for those who are doing this by coding. You need to add WebHttpBehavior() to your added service endpoint. Something like:

restHost.AddServiceEndpoint(typeof(IRestInterface), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); 

Take a look at : https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/calling-a-rest-style-service-from-a-wcf-service

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

Vertical alignment of text and icon in button

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

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

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

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

enter image description here

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

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

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

enter image description here

jQuery: how do I animate a div rotation?

As of now you still can't animate rotations with jQuery, but you can with CSS3 animations, then simply add and remove the class with jQuery to make the animation occur.

JSFiddle demo


HTML

<img src="http://puu.sh/csDxF/2246d616d8.png" width="30" height="30"/>

CSS3

img {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
transition-duration:0.4s;
}

.rotate {
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
transition-duration:0.4s;
}

jQuery

$(document).ready(function() {
    $("img").mouseenter(function() {
        $(this).addClass("rotate");
    });
    $("img").mouseleave(function() {
        $(this).removeClass("rotate");
    });
});

How to use mouseover and mouseout in Angular 6

Adding to what was already said.

if you want to *ngFor an element , and hide \ show elements in it, on hover, like you added in the comments, you should re-think the whole concept.

a more appropriate way to do it, does not involve angular at all. I would go with pure CSS instead, using its native :hover property.

something like:

App.Component.css

div span.only-show-on-hover {
    visibility: hidden;
}
div:hover span.only-show-on-hover  {
    visibility: visible;
}

App.Component.html

  <div *ngFor="let i of [1,2,3,4]" > hover me please.
    <span class="only-show-on-hover">you only see me when hovering</span>
  </div>

added a demo: https://stackblitz.com/edit/hello-angular-6-hvgx7n?file=src%2Fapp%2Fapp.component.html

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

We can eliminate the unnecessary file read/write by using text. My complete solution is the following:

proc1 = ['/bin/bash', '-c', 
  "/usr/bin/git ls-remote --heads ssh://repo_url.git"].execute()
proc2 = ['/bin/bash', '-c', 
  "/usr/bin/awk ' { gsub(/refs\\/heads\\//, \"\"); print \$2 }' "].execute()
all = proc1 | proc2

choices = all.text
return choices.split().toList();

MySQL SELECT statement for the "length" of the field is greater than 1

Try:

SELECT
    *
FROM
    YourTable
WHERE
    CHAR_LENGTH(Link) > x

Capturing mobile phone traffic on Wireshark

Packet Capture Android app implements a VPN that logs all network traffic on the Android device. You don't need to setup any VPN/proxy server on your PC. Does not needs root. Supports SSL decryption which tPacketCapture does not. It also includes a good log viewer.

jQuery - Check if DOM element already exists

if ($('#some_element').length === 0) {
    //If exists then do manipulations
}

What is the difference between Select and Project Operations

Project will effects Columns in the table while Select effects the Rows. on other hand Project is use to select the columns with specefic properties rather than Select the all of columns data

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.

Example:

myvar1 = userInput['param1']
myvar2 = userInput['param2']

to:

myvar = userInput

Set start value for column with autoincrement

Also note that you cannot normally set a value for an IDENTITY column. You can, however, specify the identity of rows if you set IDENTITY_INSERT to ON for your table. For example:

SET IDENTITY_INSERT Orders ON

-- do inserts here

SET IDENTITY_INSERT Orders OFF

This insert will reset the identity to the last inserted value. From MSDN:

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

Jonty, I'm struggling with this too.

I think there's a clue in here:

otool -L /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle:
    /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/libruby.1.dylib (compatibility version 1.8.0, current version 1.8.7)
    libmysqlclient.16.dylib (compatibility version 16.0.0, current version 16.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)

Notice the path to the dylib is, uh, rather short?

I'm trying to figure out where the gem install instructions are leaving off the dylib path, but it's slow going as I have never built a gem myself.

I'll post more if I find more!

Create a OpenSSL certificate on Windows

You can download a native OpenSSL for Windows, or you can always use Cygwin.

Comparing two dictionaries and checking how many (key, value) pairs are equal

Being late in my response is better than never!

Compare Not_Equal is more efficient than comparing Equal. As such two dicts are not equal if any key values in one dict is not found in the other dict. The code below takes into consideration that you maybe comparing default dict and thus uses get instead of getitem [].

Using a kind of random value as default in the get call equal to the key being retrieved - just in case the dicts has a None as value in one dict and that key does not exist in the other. Also the get != condition is checked before the not in condition for efficiency because you are doing the check on the keys and values from both sides at the same time.

def Dicts_Not_Equal(first,second):
    """ return True if both do not have same length or if any keys and values are not the same """
    if len(first) == len(second): 
        for k in first:
            if first.get(k) != second.get(k,k) or k not in second: return (True)
        for k in second:         
            if first.get(k,k) != second.get(k) or k not in first: return (True)
        return (False)   
    return (True)

Set a persistent environment variable from cmd.exe

:: Sets environment variables for both the current `cmd` window 
::   and/or other applications going forward.
:: I call this file keyz.cmd to be able to just type `keyz` at the prompt 
::   after changes because the word `keys` is already taken in Windows.

@echo off

:: set for the current window
set APCA_API_KEY_ID=key_id
set APCA_API_SECRET_KEY=secret_key
set APCA_API_BASE_URL=https://paper-api.alpaca.markets

:: setx also for other windows and processes going forward
setx APCA_API_KEY_ID     %APCA_API_KEY_ID%
setx APCA_API_SECRET_KEY %APCA_API_SECRET_KEY%
setx APCA_API_BASE_URL   %APCA_API_BASE_URL%

:: Displaying what was just set.
set apca

:: Or for copy/paste manually ...
:: setx APCA_API_KEY_ID     'key_id'
:: setx APCA_API_SECRET_KEY 'secret_key'
:: setx APCA_API_BASE_URL   'https://paper-api.alpaca.markets'

How to delete an app from iTunesConnect / App Store Connect

As per 2018 in App Store Connect. We can delete/remove application with following stats.

enter image description here

App Store Connect details for Remove an app

So, from now onwards we can delete our test applications too from app store connect.

enter image description here

Dynamically adding HTML form field using jQuery

something like so might work:

<script type="text/javascript">
$(document).ready(function(){
    var $input = $("<input name='myField' type='text'>");
    $('#section2').append($input);
});
</script>

<form>
    <div id="section1"><!-- some controls--></div>
    <div id="section2"><!-- for dynamic controls--></div>
</form>

Connect Device to Mac localhost Server?

Have your server listen on 0.0.0.0 instead of localhost.

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

Full Screen DialogFragment in Android

Try to use setStyle() in onCreate and override onCreateDialog make dialog without title

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme);        
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);        
    return dialog;
}

or just override onCreate() and setStyle fellow the code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);        
}

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

UIView frame, bounds and center

I think if you think it from the point of CALayer, everything is more clear.

Frame is not really a distinct property of the view or layer at all, it is a virtual property, computed from the bounds, position(UIView's center), and transform.

So basically how the layer/view layouts is really decided by these three property(and anchorPoint), and either of these three property won't change any other property, like changing transform doesn't change bounds.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

You can do this in the 'Conditional Formatting' tool in the Home tab of Excel 2010.

Assuming the existing rule is 'Use a formula to dtermine which cells to format':

Edit the existing rule, so that the 'Formula' refers to relative rows and columns (i.e. remove $s), and then in the 'Applies to' box, click the icon to make the sheet current and select the cells you want the formatting to apply to (absolute cell references are ok here), then go back to the tool panel and click Apply.

This will work assuming the relative offsets are appropriate throughout your desired apply-to range.

You can copy conditional formatting from one cell to another or a range using copy and paste-special with formatting only, assuming you do not mind copying the normal formats.

Trying to create a file in Android: open failed: EROFS (Read-only file system)

If anyone getting this in unit/instrumentation testing, make sure you call getFilesDir() on the app context, not the test context. i.e. use:

Context appContext = getInstrumentation().getTargetContext().getApplicationContext();

not

Context appContext = InstrumentationRegistry.getContext;

Get a list of distinct values in List

mcilist = (from mci in mcilist select mci).Distinct().ToList();

Please explain the exec() function and its family

Functions in the exec() family have different behaviours:

  • l : arguments are passed as a list of strings to the main()
  • v : arguments are passed as an array of strings to the main()
  • p : path/s to search for the new running program
  • e : the environment can be specified by the caller

You can mix them, therefore you have:

  • int execl(const char *path, const char *arg, ...);
  • int execlp(const char *file, const char *arg, ...);
  • int execle(const char *path, const char *arg, ..., char * const envp[]);
  • int execv(const char *path, char *const argv[]);
  • int execvp(const char *file, char *const argv[]);
  • int execvpe(const char *file, char *const argv[], char *const envp[]);

For all of them the initial argument is the name of a file that is to be executed.

For more information read exec(3) man page:

man 3 exec  # if you are running a UNIX system

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

In my case runat="server" was missing in the asp:content tag. I know it's stupid, but someone might have removed from the code in the build I got.

It worked for me. Someone may face the same thing. Hence shared.

Get url without querystring

Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.

Usage:

Uri uri = new Uri("http://www.somewhere.com?param1=foo&param2=bar");
string path = uri.Path();

The class:

using System;

namespace YourProject.Extensions
{
    public static class UriExtensions
    {
        public static string Path(this Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            return uri.GetLeftPart(UriPartial.Path);
        }
    }
}

How do I solve this "Cannot read property 'appendChild' of null" error?

Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.

How to implement a ConfigurationSection with a ConfigurationElementCollection

An easier alternative for those who would prefer not to write all that configuration boilerplate manually...

1) Install Nerdle.AutoConfig from NuGet

2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)

public interface IServiceConfiguration
{
    int Port { get; }
    ReportType ReportType { get; }
}

3) You'll need a type to hold the collection, e.g.

public interface IServiceCollectionConfiguration
{
    IEnumerable<IServiceConfiguration> Services { get; } 
}

4) Add the config section like so (note camelCase naming)

<configSections>
  <section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>

<serviceCollection>
  <services>
    <service port="6996" reportType="File" />
    <service port="7001" reportType="Other" />
  </services>
</serviceCollection>

5) Map with AutoConfig

var services = AutoConfig.Map<IServiceCollectionConfiguration>();

MySQL DROP all tables, ignoring foreign keys

Simple and clear (may be).

Might not be a fancy solution, but this worked me and saved my day.

Worked for Server version: 5.6.38 MySQL Community Server (GPL)

Steps I followed:

 1. generate drop query using concat and group_concat.
 2. use database
 3. disable key constraint check
 4. copy the query generated from step 1
 5. enable key constraint check
 6. run show table

MySQL shell

mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0;                                                                                                                                                   Query OK, 0 rows affected (0.00 sec)

// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)

mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW tables;
Empty set (0.01 sec)

mysql> 

enter image description here

How to read AppSettings values from a .json file in ASP.NET Core

In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration for simplicity's sake.

I keep JWT config in appsettings.json so my extension methods class looks as follows:

public static class ConfigurationExtensions
{
    public static string GetIssuerSigningKey(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
        return result;
    }

    public static string GetValidIssuer(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
        return result;
    }

    public static string GetValidAudience(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
        return result;
    }

    public static string GetDefaultPolicy(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Policies:Default");
        return result;
    }

    public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
    {
        var issuerSigningKey = configuration.GetIssuerSigningKey();
        var data = Encoding.UTF8.GetBytes(issuerSigningKey);
        var result = new SymmetricSecurityKey(data);
        return result;
    }

    public static string[] GetCorsOrigins(this IConfiguration configuration)
    {
        string[] result =
            configuration.GetValue<string>("App:CorsOrigins")
            .Split(",", StringSplitOptions.RemoveEmptyEntries)
            .ToArray();

        return result;
    }
}

It saves you a lot of lines and you just write clean and minimal code:

...
x.TokenValidationParameters = new TokenValidationParameters()
{
    ValidateIssuerSigningKey = true,
    ValidateLifetime = true,
    IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
    ValidAudience = _configuration.GetValidAudience(),
    ValidIssuer = _configuration.GetValidIssuer()
};

It's also possible to register IConfiguration instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:

var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();

You can do the same with MS Dependency Injection:

services.AddSingleton<IConfigurationRoot>(appConfiguration);

Change default text in input type="file"?

My solution...

HTML :

<input type="file" id="uploadImages" style="display:none;" multiple>

<input type="button" id="callUploadImages" value="Select">
<input type="button" id="uploadImagesInfo" value="0 file(s)." disabled>
<input type="button" id="uploadProductImages" value="Upload">

Jquery:

$('#callUploadImages').click(function(){

    $('#uploadImages').click();
});

$('#uploadImages').change(function(){

    var uploadImages = $(this);
    $('#uploadImagesInfo').val(uploadImages[0].files.length+" file(s).");
});

This is just evil :D

Getting user input

Use the following simple way to interactively get user data by a prompt as Arguments on what you want.

Version : Python 3.X

name = input('Enter Your Name: ')
print('Hello ', name)

How to Apply global font to whole HTML document

You should never use * + !important. What if you want to change font in some parts your HTML document? You should always use body without important. Use !important only if there is no other option.

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

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

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

The character encoding of the plain text document was not declared - mootool script

I got this error using Spring Boot (in Mozilla),

because I was just testing some basic controller -> service -> repository communication by directly returning some entities from the database to the browser (as JSON).

I forgot to put data in the database, so my method wasn't returning anything... and I got this error.

Now that I put some data in my db, it works fine (the error is removed). :D

Using FFmpeg in .net?

GPL-compiled ffmpeg can be used from non-GPL program (commercial project) only if it is invoked in the separate process as command line utility; all wrappers that are linked with ffmpeg library (including Microsoft's FFMpegInterop) can use only LGPL build of ffmpeg.

You may try my .NET wrapper for FFMpeg: Video Converter for .NET (I'm an author of this library). It embeds FFMpeg.exe into the DLL for easy deployment and doesn't break GPL rules (FFMpeg is NOT linked and wrapper invokes it in the separate process with System.Diagnostics.Process).

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

How to let an ASMX file output JSON

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).

Installing PDO driver on MySQL Linux server

  1. PDO stands for PHP Data Object.
  2. PDO_MYSQL is the driver that will implement the interface between the dataobject(database) and the user input (a layer under the user interface called "code behind") accessing your data object, the MySQL database.

The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)

But there are a few nuances to this which you might not be aware of.

First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.

You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.

And:

By implementing best practices while writing your code you will be much happier with the outcome.

Additional sources:

Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php

Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/

Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028

Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.

>

If we knew what the terminology really meant we wouldn't need to learn anything.

>

php REQUEST_URI

I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

Python 2: AttributeError: 'list' object has no attribute 'strip'

What you want to do is -

strtemp = ";".join(l)

The first line adds a ; to the end of MySpace so that while splitting, it does not give out MySpaceApple This will join l into one string and then you can just-

l1 = strtemp.split(";")

This works because strtemp is a string which has .split()

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

Dependency Injection vs Factory Pattern

You use dependency injection when you exactly know what type of objects you require at this point of time. While in case of factory pattern, you just delegate the process of creating objects to factory as you are unclear of what exact type of objects you require.

How can I push a specific commit to a remote, and not previous commits?

The simplest way to accomplish this is to use two commands.

First, get the local directory into the state that you want. Then,

$ git push origin +HEAD^:someBranch

removes the last commit from someBranch in the remote only, not local. You can do this a few times in a row, or change +HEAD^ to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use

$ git push origin someBranch

as normal to update the remote.

Passing ArrayList through Intent

if you using Generic Array List with Class instead of specific type like

EX:

private ArrayList<Model> aListModel = new ArrayList<Model>();

Here, Model = Class

Receiving Intent Like :

aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);

MUST REMEMBER:

Here Model-class must be implemented like: ModelClass implements Serializable

How to list all the files in a commit?

OK, there are couple of ways to show all files in a particular commit...

To reduce the info and show only names of the files which committed, you simply can add --name-only or --name-status flag..., these flags just show you the file names which are different from previous commits as you want...

So you can do git diff followed by --name-only, with two commit hashes after <sha0> <sha1>, something like below:

git diff --name-only 5f12f15 kag9f02 

I also create the below image to show all steps to go through in these situation:

git diff --name-only 5f12f15 kag9f02

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

If you just want to suppress warnings from a function, you can add an @ sign in front:

<?php @function_that_i_dont_want_to_see_errors_from(parameters); ?>

How do I paste multi-line bash codes into terminal and run it all at once?

In addition to backslash, if a line ends with | or && or ||, it will be continued on the next line.

Calculate age given the birth date in the format YYYYMMDD

Try this.

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

I believe the only thing that looked crude on your code was the substr part.

Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/

Why does checking a variable against multiple values with `OR` only check the first value?

The or operator returns the first operand if it is true, otherwise the second operand. So in your case your test is equivalent to if name == "Jesse".

The correct application of or would be:

if (name == "Jesse") or (name == "jesse"):

Using the rJava package on Win7 64 bit with R

The last question has an easy answer:

> .Machine$sizeof.pointer
[1] 8

Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.

EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/... On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)

Floating point exception

It's caused by n % x, when x is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.

General notes:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for q to be global.
  3. Don't return without a value in a non-void (int) function.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

How to write to a CSV line by line?

You could just write to the file as you would write any normal file.

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

How can I use a search engine to search for special characters?

duckduckgo.com doesn't ignore special characters, at least if the whole string is between ""

https://duckduckgo.com/?q=%22*222%23%22

How can I get list of values from dict?

There should be one - and preferably only one - obvious way to do it.

Therefore list(dictionary.values()) is the one way.

Yet, considering Python3, what is quicker?

[*L] vs. [].extend(L) vs. list(L)

small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())

print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())

print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

The result

  1. For small dictionaries * operator is quicker
  2. For big dictionaries where it matters list() is maybe slightly quicker

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

only 8.0.0 throw the exception, above 8.0 has remove the exception

8.0.0 throw the exception

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

If all else fails, as it had for me, try putting the commons-logging-x.y.z.jar in your Tomcat lib directory. It solved the problem! BTW, I am using Tomcat 6.

How to tell which disk Windows Used to Boot

That depends on your definition of which disk drive Windows used to boot. I can think of 3 different answers on a standard BIOS system (who knows what an EFI system does):

  1. The drive that contains the active MBR
  2. The active partition, with NTLDR (the system partition)
  3. The partition with Windows on it (the boot partition)

2 and 3 should be easy to find - I'm not so sure about 1. Though you can raw disk read to find an MBR, that doesn't mean it's the BIOS boot device this time or even next time (you could have multiple disks with MBRs).

You really can't even be sure that the PC was started from a hard drive - it's perfectly possible to boot Windows from a floppy. In that case, both 1 and 2 would technically be a floppy disk, though 3 would remain C:\Windows.

You might need to be a bit more specific in your requirements or goals.

Regular expression field validation in jQuery

From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/

/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i

Make sure to double up the @@ if you are using MVC Razor:

 /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i

Hungry for spaghetti?

How to remove specific element from an array using python

If you want to delete the index of array:

Use array_name.pop(index_no.)

ex:-

>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]

If you want to delete a particular string/element from the array then

>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']

PHP header redirect 301 - what are the implications?

Just a tip: using http_response_code is much easier to remember than writing the full header:

http_response_code(301);
header('Location: /option-a'); 
exit;

Toggle show/hide on click with jQuery

The toggle-event is deprecated in version 1.8, and removed in version 1.9

Try this...

$('#myelement').toggle(
   function () {
      $('#another-element').show("slide", {
          direction: "right"
      }, 1000);
   },
   function () {
      $('#another-element').hide("slide", {
          direction: "right"
      }, 1000);
});

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed, jQuery docs.

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element, jQuery docs

You toggle between visibility using show and hide with click. You can put condition on visibility if element is visible then hide else show it. Note you will need jQuery UI to use addition effects with show / hide like direction.

Live Demo

$( "#myelement" ).click(function() {     
    if($('#another-element:visible').length)
        $('#another-element').hide("slide", { direction: "right" }, 1000);
    else
        $('#another-element').show("slide", { direction: "right" }, 1000);        
});

Or, simply use toggle instead of click. By using toggle you wont need a condition (if-else) statement. as suggested by T.J.Crowder.

Live Demo

$( "#myelement" ).click(function() {     
   $('#another-element').toggle("slide", { direction: "right" }, 1000);
});

How to redirect in a servlet filter?

Your response object is declared as a ServletResponse. To use the sendRedirect() method, you have to cast it to HttpServletResponse. This is an extended interface that adds methods related to the HTTP protocol.

Convert string to datetime

formatDateTime(sDate,FormatType) {
    var lDate = new Date(sDate)

    var month=new Array(12);
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";

    var weekday=new Array(7);
    weekday[0]="Sunday";
    weekday[1]="Monday";
    weekday[2]="Tuesday";
    weekday[3]="Wednesday";
    weekday[4]="Thursday";
    weekday[5]="Friday";
    weekday[6]="Saturday";

    var hh = lDate.getHours() < 10 ? '0' + 
        lDate.getHours() : lDate.getHours();
    var mi = lDate.getMinutes() < 10 ? '0' + 
        lDate.getMinutes() : lDate.getMinutes();
    var ss = lDate.getSeconds() < 10 ? '0' + 
        lDate.getSeconds() : lDate.getSeconds();

    var d = lDate.getDate();
    var dd = d < 10 ? '0' + d : d;
    var yyyy = lDate.getFullYear();
    var mon = eval(lDate.getMonth()+1);
    var mm = (mon<10?'0'+mon:mon);
    var monthName=month[lDate.getMonth()];
    var weekdayName=weekday[lDate.getDay()];

    if(FormatType==1) {
       return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi;
    } else if(FormatType==2) {
       return weekdayName+', '+monthName+' '+ 
            dd +', ' + yyyy;
    } else if(FormatType==3) {
       return mm+'/'+dd+'/'+yyyy; 
    } else if(FormatType==4) {
       var dd1 = lDate.getDate();    
       return dd1+'-'+Left(monthName,3)+'-'+yyyy;    
    } else if(FormatType==5) {
        return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi+':'+ss;
    } else if(FormatType == 6) {
        return mon + '/' + d + '/' + yyyy + ' ' + 
            hh + ':' + mi + ':' + ss;
    } else if(FormatType == 7) {
        return  dd + '-' + monthName.substring(0,3) + 
            '-' + yyyy + ' ' + hh + ':' + mi + ':' + ss;
    }
}

iOS: how to perform a HTTP POST request?

NOTE: Pure Swift 3 (Xcode 8) example: Please try out the following sample code. It is the simple example of dataTask function of URLSession.

func simpleDataRequest() {

        //Get the url from url string
        let url:URL = URL(string: "YOUR URL STRING")!

        //Get the session instance
        let session = URLSession.shared

        //Create Mutable url request
        var request = URLRequest(url: url as URL)

        //Set the http method type
        request.httpMethod = "POST"

        //Set the cache policy
        request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData

        //Post parameter
        let paramString = "key=value"

        //Set the post param as the request body
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest) {
            (data, response, error) in

            guard let _:Data = data as Data?, let _:URLResponse = response  , error == nil else {

                //Oops! Error occured.
                print("error")
                return
            }

            //Get the raw response string
            let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

            //Print the response
            print(dataString!)

        }

        //resume the task
        task.resume()

    }

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

condition binding must have optinal type which mean that you can only bind optional values in if let statement

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        // Delete the row from the data source

        if let tv = tableView as UITableView? {


        }
    }
}

This will work fine but make sure when you use if let it must have optinal type "?"

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

At times, if you are on Windows, you may not see all the processes - or the culprit process in Task manager. I had to click 'Show process from all users' and there was this java.exe that I had to kill in order to get back my workspace.

Display HTML form values in same page after submit using Ajax

_x000D_
_x000D_
var tasks = [];_x000D_
var descs = [];_x000D_
_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
  modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
  if (event.target == modal) {_x000D_
    modal.style.display = "none";_x000D_
  }_x000D_
}_x000D_
var rowCount = 1;_x000D_
_x000D_
function addTasks() {_x000D_
  var temp = 'style .fa fa-trash';_x000D_
  tasks.push(document.getElementById("taskname").value);_x000D_
  descs.push(document.getElementById("taskdesc").value);_x000D_
  var table = document.getElementById("tasksTable");_x000D_
  var row = table.insertRow(rowCount);_x000D_
  var cell1 = row.insertCell(0);_x000D_
  var cell2 = row.insertCell(1);_x000D_
  var cell3 = row.insertCell(2);_x000D_
  var cell4 = row.insertCell(3);_x000D_
  cell1.innerHTML = tasks[rowCount - 1];_x000D_
  cell2.innerHTML = descs[rowCount - 1];_x000D_
  cell3.innerHTML = getDate();_x000D_
  cell4.innerHTML = '<td class="fa fa-trash"></td>';_x000D_
  rowCount++;_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
function getDate() {_x000D_
  var today = new Date();_x000D_
  var dd = today.getDate();_x000D_
  var mm = today.getMonth() + 1; //January is 0!_x000D_
_x000D_
  var yyyy = today.getFullYear();_x000D_
_x000D_
  if (dd < 10) {_x000D_
    dd = '0' + dd;_x000D_
  }_x000D_
  if (mm < 10) {_x000D_
    mm = '0' + mm;_x000D_
  }_x000D_
  var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);_x000D_
  return today;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <!-- Trigger/Open The Modal -->_x000D_
  <div style="background-color:#0F0F8C ;height:45px">_x000D_
    <h2 style="color: white">LOGO</h2>_x000D_
  </div>_x000D_
  <div>_x000D_
    <button id="myBtn">&emsp;+ Add Task &emsp;</button>_x000D_
  </div>_x000D_
  <div>_x000D_
    <table id="tasksTable">_x000D_
      <thead>_x000D_
        <tr style="background-color:rgba(201, 196, 196, 0.86)">_x000D_
          <th style="width: 150px;">Name</th>_x000D_
          <th style="width: 250px;">Desc</th>_x000D_
          <th style="width: 120px">Date</th>_x000D_
          <th style="width: 120px class=fa fa-trash"></th>_x000D_
        </tr>_x000D_
_x000D_
      </thead>_x000D_
      <tbody></tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
  <!-- The Modal -->_x000D_
  <div id="myModal" class="modal">_x000D_
_x000D_
    <!-- Modal content -->_x000D_
    <div class="modal-content">_x000D_
_x000D_
      <div class="modal-header">_x000D_
_x000D_
        <span class="close">&times;</span>_x000D_
        <h3> Add Task</h3>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-body">_x000D_
        <table style="padding: 28px 50px">_x000D_
          <tr>_x000D_
            <td style="width:150px">Name:</td>_x000D_
            <td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>_x000D_
              Desc:_x000D_
            </td>_x000D_
            <td>_x000D_
              <textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>_x000D_
            </td>_x000D_
          </tr>_x000D_
        </table>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-footer">_x000D_
        <button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>_x000D_
        <br>_x000D_
        <br>_x000D_
        <br>_x000D_
      </div>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

disable Bootstrap's Collapse open/close animation

For Bootstrap 3 and 4 it's

.collapsing {
    -webkit-transition: none;
    transition: none;
    display: none;
}

QR Code encoding and decoding using zxing

So, for future reference for anybody who doesn't want to spend two days searching the internet to figure this out, when you encode byte arrays into QR Codes, you have to use the ISO-8859-1character set, not UTF-8.

How do I find out what version of Sybase is running

1)From OS level(UNIX):-

dataserver -v

2)From Syabse isql:-

select @@version
go

sp_version
go

Postgres could not connect to server

I have macOS Catalina (10.15.6) and PostgreSQL 12.

When I run brew services start postgresql, brew said it start PostgreSQL without problem, but it does not show when I get ps auxw | grep post.

To solve it, I install Postgres.app from this link, and install and press Init button.

It will find your databases and show it to you.

jQuery $.ajax request of dataType json will not retrieve data from PHP script

I think I know this one...

Try sending your JSON as JSON by using PHP's header() function:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header.

jQuery used to be fine without the header, but it was changed a few versions back.

ALSO

Be sure that your script is returning valid JSON. Use Firebug or Google Chrome's Developer Tools to check the request's response in the console.

UPDATE

You will also want to update your code to sanitize the $_POST to avoid sql injection attacks. As well as provide some error catching.

if (isset($_POST['get_member'])) {

    $member_id = mysql_real_escape_string ($_POST["get_member"]);

    $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';";

    if ($result = mysql_query( $query )) {

       $row = mysql_fetch_array($result);

       $type = $row['type'];
       $name = $row['name'];
       $fname = $row['fname'];
       $lname = $row['lname'];
       $email = $row['email'];
       $phone = $row['phone'];
       $website = $row['website'];
       $image = $row['image'];

       /* JSON Row */
       $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

    } else {

        /* Your Query Failed, use mysql_error to report why */
        $json = array('error' => 'MySQL Query Error');

    }

     /* Send as JSON */
     header("Content-Type: application/json", true);

    /* Return JSON */
    echo json_encode($json);

    /* Stop Execution */
    exit;

}

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

Bold & Non-Bold Text In A Single UILabel?

Update

In Swift we don't have to deal with iOS5 old stuff besides syntax is shorter so everything becomes really simple:

Swift 5

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
        NSAttributedString.Key.foregroundColor: UIColor.black
    ]
    let nonBoldAttribute = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Swift 3

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize),
        NSForegroundColorAttributeName: UIColor.black
    ]
    let nonBoldAttribute = [
        NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Usage:

let targetString = "Updated 2012/10/14 21:59 PM"
let range = NSMakeRange(7, 12)

let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44))
label.backgroundColor = UIColor.white
label.attributedText = attributedString(from: targetString, nonBoldRange: range)
label.sizeToFit()

Bonus: Internationalisation

Some people commented about internationalisation. I personally think this is out of scope of this question but for instructional purposes this is how I would do it

// Date we want to show
let date = Date()

// Create the string.
// I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"),
                          formatter.string(from: date))

// Find the range of the non-bold part
formatter.timeStyle = .none
let nonBoldRange = targetString.range(of: formatter.string(from: date))

// Convert Range<Int> into NSRange
let nonBoldNSRange: NSRange? = nonBoldRange == nil ?
    nil :
    NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound),
                targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound))

// Now just build the attributed string as before :)
label.attributedText = attributedString(from: targetString,
                                        nonBoldRange: nonBoldNSRange)

Result (Assuming English and Japanese Localizable.strings are available)

enter image description here

enter image description here


Previous answer for iOS6 and later (Objective-C still works):

In iOS6 UILabel, UIButton, UITextView, UITextField, support attributed strings which means we don't need to create CATextLayers as our recipient for attributed strings. Furthermore to make the attributed string we don't need to play with CoreText anymore :) We have new classes in obj-c Foundation.framework like NSParagraphStyle and other constants that will make our life easier. Yay!

So, if we have this string:

NSString *text = @"Updated: 2012/10/14 21:59"

We only need to create the attributed string:

if ([_label respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings

    // Create the attributes
    const CGFloat fontSize = 13;
    NSDictionary *attrs = @{
        NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize],
        NSForegroundColorAttributeName:[UIColor whiteColor]
    };
    NSDictionary *subAttrs = @{
        NSFontAttributeName:[UIFont systemFontOfSize:fontSize]
    };

    // Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded
    // This example is about attributed strings in one label
    // not about internationalisation, so we keep it simple :)
    // For internationalisation example see above code in swift
    const NSRange range = NSMakeRange(8,12);

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
      [[NSMutableAttributedString alloc] initWithString:text
                                             attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [_label setAttributedText:attributedText];
} else {
    // iOS5 and below
    // Here we have some options too. The first one is to do something
    // less fancy and show it just as plain text without attributes.
    // The second is to use CoreText and get similar results with a bit
    // more of code. Interested people please look down the old answer.

    // Now I am just being lazy so :p
    [_label setText:text];
}

There is a couple of good introductory blog posts here from guys at invasivecode that explain with more examples uses of NSAttributedString, look for "Introduction to NSAttributedString for iOS 6" and "Attributed strings for iOS using Interface Builder" :)

PS: Above code it should work but it was brain-compiled. I hope it is enough :)


Old Answer for iOS5 and below

Use a CATextLayer with an NSAttributedString ! much lighter and simpler than 2 UILabels. (iOS 3.2 and above)

Example.

Don't forget to add QuartzCore framework (needed for CALayers), and CoreText (needed for the attributed string.)

#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>

Below example will add a sublayer to the toolbar of the navigation controller. à la Mail.app in the iPhone. :)

- (void)setRefreshDate:(NSDate *)aDate
{
    [aDate retain];
    [refreshDate release];
    refreshDate = aDate;

    if (refreshDate) {

        /* Create the text for the text layer*/    
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy hh:mm"];

        NSString *dateString = [df stringFromDate:refreshDate];
        NSString *prefix = NSLocalizedString(@"Updated", nil);
        NSString *text = [NSString stringWithFormat:@"%@: %@",prefix, dateString];
        [df release];

        /* Create the text layer on demand */
        if (!_textLayer) {
            _textLayer = [[CATextLayer alloc] init];
            //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
            _textLayer.backgroundColor = [UIColor clearColor].CGColor;
            _textLayer.wrapped = NO;
            CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
            _textLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
            _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
            _textLayer.alignmentMode = kCAAlignmentCenter;
            [layer addSublayer:_textLayer];
        }

        /* Create the attributes (for the attributed string) */
        CGFloat fontSize = 13;
        UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
        CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
        UIFont *font = [UIFont systemFontOfSize:13];
        CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
        CGColorRef cgColor = [UIColor whiteColor].CGColor;
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                    (id)ctBoldFont, (id)kCTFontAttributeName,
                                    cgColor, (id)kCTForegroundColorAttributeName, nil];
        CFRelease(ctBoldFont);
        NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(id)ctFont, (id)kCTFontAttributeName, nil];
        CFRelease(ctFont);

        /* Create the attributed string (text + attributes) */
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
        [attrStr addAttributes:subAttributes range:NSMakeRange(prefix.length, 12)]; //12 is the length of " MM/dd/yyyy/ "

        /* Set the attributes string in the text layer :) */
        _textLayer.string = attrStr;
        [attrStr release];

        _textLayer.opacity = 1.0;
    } else {
        _textLayer.opacity = 0.0;
        _textLayer.string = nil;
    }
}

In this example I only have two different types of font (bold and normal) but you could also have different font size, different color, italics, underlined, etc. Take a look at NSAttributedString / NSMutableAttributedString and CoreText attributes string keys.

Hope it helps

Running EXE with parameters

ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(cPath, "\\", "HHTCtrlp.exe"));
startInfo.Arguments =cParams;
startInfo.UseShellExecute = false; 
System.Diagnostics.Process.Start(startInfo);

/exclude in xcopy just for a file type

For excluding multiple file types, you can use '+' to concatenate other lists. For example:

xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan

Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/

How do I delete files programmatically on Android?

first call the intent

Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);

then call the result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 42:
            if (resultCode == Activity.RESULT_OK) {
                Uri sdCardUri = data.getData();
                DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
                for (DocumentFile file : pickedDir.listFiles()) {
                    String pp = file.getName();
                    if(pp.equals("VLC.apk"))
                        file.delete();
                    String ppdf="";
                }
                File pathFile = new File(String.valueOf(sdCardUri));
                pathFile.delete();
            }
            break;
    }
}

Convert Long into Integer

Integer i = theLong != null ? theLong.intValue() : null;

or if you don't need to worry about null:

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).

Java 8 has a helper method that checks for overflow (you get an exception in that case):

Integer i = theLong == null ? null : Math.toIntExact(theLong);

Get multiple elements by Id

Today you can select elements with the same id attribute this way:

document.querySelectorAll('[id=test]');

Or this way with jQuery:

$('[id=test]');

CSS selector #test { ... } should work also for all elements with id = "test". ?ut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id. Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .

For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).

Field 'id' doesn't have a default value?

As id is the primary key, you cannot have different rows with the same value. Try to change your table so that the id is auto incremented:

id int NOT NULL AUTO_INCREMENT

and then set the primary key as follows:

PRIMARY KEY (id)

All together:

CREATE TABLE card_games (
   id int(11) NOT NULL AUTO_INCREMENT,
   nafnleiks varchar(50),
   leiklysing varchar(3000), 
   prentadi varchar(1500), 
   notkunarheimildir varchar(1000),
   upplysingar varchar(1000),
   ymislegt varchar(500),
   PRIMARY KEY (id));

Otherwise, you can indicate the id in every insertion, taking care to set a different value every time:

insert into card_games (id, nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values(1, 'Svartipétur', 'Leiklýsingu vantar', 'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.', 'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum', 'Aðrar upplýsingar', 'ekkert hér sem stendur' );

How can I make Flexbox children 100% height of their parent?

I have answered a similar question here.

I know you have already said position: absolute; is inconvenient, but it works. See below for further information on fixing the resize issue.

Also see this jsFiddle for a demo, although I have only added WebKit prefixes so open in Chrome.

You basically have two issues which I will deal with separately.

  1. Getting the child of a flex-item to fill height 100%
  • Set position: relative; on the parent of the child.
  • Set position: absolute; on the child.
  • You can then set width/height as required (100% in my sample).
  1. Fixing the resize scrolling "quirk" in Chrome
  • Put overflow-y: auto; on the scrollable div.
  • The scrollable div must have an explicit height specified. My sample already has height 100%, but if none is already applied you can specify height: 0;

See this answer for more information on the scrolling issue.

CSS scale height to match width - possibly with a formfactor

.video {
    width: 100%;
    position: relative;
    padding-bottom: 56.25%; /* ratio 16/9 */
}

.video iframe {
    border: none;
    position: absolute;
    width: 100%;
    height: 100%;
}

16:9

padding-bottom = 9/16 * 100 = 56.25

Handling file renames in git

For git 1.7.x the following commands worked for me:

git mv css/iphone.css css/mobile.css
git commit -m 'Rename folder.' 

There was no need for git add, since the original file (i.e. css/mobile.css) was already in the committed files previously.

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_

How does OkHttp get Json string?

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

How to store custom objects in NSUserDefaults

Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults to save and retrieve custom objects:

@interface NSUserDefaults (NSUserDefaultsExtensions)

- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;

@end


@implementation NSUserDefaults (NSUserDefaultsExtensions)


- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [self setObject:encodedObject forKey:key];
    [self synchronize];

}

- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
    NSData *encodedObject = [self objectForKey:key];
    id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

@end

Usage:

[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];

css transform, jagged edges in chrome

Try 3d transform. This works like a charm!

/* Due to a bug in the anti-liasing*/
-webkit-transform-style: preserve-3d; 
-webkit-transform: rotateZ(2deg);

Log4j output not displayed in Eclipse console

One thing to note, if you have a log4j.properties file on your classpath you do not need to call BasicConfigurator. A description of how to configure the properties file is here.

You could pinpoint whether your IDE is causing the issue by trying to run this class from the command line with log4j.jar and log4j.properties on your classpath.

How to handle the new window in Selenium WebDriver using Java?

I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

When to throw an exception?

Security is conflated with your example: You shouldn't tell an attacker that a username exists, but the password is wrong. That's extra information you don't need to share. Just say "the username or password is incorrect."

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

String "true" and "false" to boolean

ActiveRecord::Type::Boolean.new.type_cast_from_user does this according to Rails' internal mappings ConnectionAdapters::Column::TRUE_VALUES and ConnectionAdapters::Column::FALSE_VALUES:

[3] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("true")
=> true
[4] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("false")
=> false
[5] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("T")
=> true
[6] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("F")
=> false
[7] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("yes")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("yes") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):7)
=> false
[8] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("no")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("no") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):8)
=> false

So you could make your own to_b (or to_bool or to_boolean) method in an initializer like this:

class String
  def to_b
    ActiveRecord::Type::Boolean.new.type_cast_from_user(self)
  end
end

Find text string using jQuery?

Take a look at highlight (jQuery plugin).

Get position/offset of element relative to a parent container?

Warning: jQuery, not standard JavaScript

element.offsetLeft and element.offsetTop are the pure javascript properties for finding an element's position with respect to its offsetParent; being the nearest parent element with a position of relative or absolute

Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:

var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
    top: childPos.top - parentPos.top,
    left: childPos.left - parentPos.left
}

This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.

Difference between arguments and parameters in Java

Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.

You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments

Stop a gif animation onload, on mouseover start the activation

I think the jQuery plugin freezeframe.js might come in handy for you. freezeframe.js is a jQuery Plugin To Automatically Pause GIFs And Restart Animating On Mouse Hover.

I guess you can easily adapt it to make it work on page load instead.

Open images? Python

if location == a2:
    img = Image.open("picture.jpg")
    Img.show

Make sure the name of the image is in parantheses this should work

How to access the SMS storage on Android?

For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.

invalid command code ., despite escaping periods, using sed

On OS X nothing helps poor builtin sed to become adequate. The solution is:

brew install gnu-sed

And then use gsed instead of sed, which will just work as expected.

WebView and HTML5 <video>

On honeycomb use hardwareaccelerated=true and pluginstate.on_demand seems to work

Custom toast on Android: a simple example

Code for MainActivity.java file.

package com.android_examples.com.toastbackgroundcolorchange;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {

 Button BT;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 BT = (Button)findViewById(R.id.button1);
 BT.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {

 Toast ToastMessage = Toast.makeText(getApplicationContext(),"Change Toast Background color",Toast.LENGTH_SHORT);
 View toastView = ToastMessage.getView();
 toastView.setBackgroundResource(R.layout.toast_background_color);
 ToastMessage.show();

 }
 });
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.toastbackgroundcolorchange.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CLICK HERE TO SHOW TOAST MESSAGE WITH DIFFERENT BACKGROUND COLOR INCLUDING BORDER" />

</RelativeLayout>

Code for toast_background_color.xml layout file created in res->layout folder.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

 <stroke
    android:width="3dp"
    android:color="#ffffff" ></stroke>
<padding android:left="20dp" android:top="20dp"
    android:right="20dp" android:bottom="20dp" />
<corners android:radius="10dp" />
<gradient android:startColor="#ff000f"
    android:endColor="#ff0000"
    android:angle="-90"/>

</shape>

C# listView, how do I add items to columns 2, 3 and 4 etc?

Here is the msdn documentation on the listview object and the listviewItem object.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.aspx

I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.

But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:

ListViewItem i = new ListViewItem("column1");
i.SubItems.Add("column2");
i.SubItems.Add("column3");