Programs & Examples On #Django cms

Django CMS is a plugin-based Django application for managing hierarchical pages of content, possibly in multiple languages and/or on multiple sites.

Django: OperationalError No Such Table

Running the following commands solved this for me 1. python manage.py migrate 2. python manage.py makemigrations 3. python manage.py makemigrations appName

groovy: safely find a key in a map and return its value

Groovy maps can be used with the property property, so you can just do:

def x = mymap.likes

If the key you are looking for (for example 'likes.key') contains a dot itself, then you can use the syntax:

def x = mymap.'likes.key'

What is the Maximum Size that an Array can hold?

I think it is linked with your RAM (or probably virtual memory) space and for the absolute maximum constrained to your OS version (e.g. 32 bit or 64 bit)

Excel 2010: how to use autocomplete in validation list

=OFFSET(NameList!$A$2:$A$200,MATCH(INDIRECT("FillData!"&ADDRESS(ROW(),COLUMN(),4))&"*",NameList!$A$2:$A$200,0)-1,0,COUNTIF($A$2:$A$200,INDIRECT("FillData!"&ADDRESS(ROW(),COLUMN(),4))&"*"),1)
  1. Create sheet name as Namelist. In column A fill list of data.

  2. Create another sheet name as FillData for making data validation list as you want.

  3. Type first alphabet and select, drop down menu will appear depend on you type.

Create a folder inside documents folder in iOS apps

I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

Better:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

How can I debug a .BAT script?

I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging.

ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.

PAUSE
Prompt the user to press any key to continue.

Source: Batch File Help

@workmad3: answer has more good tips for working with the echo command.

Another helpful resource... DDB: DOS Batch File Tips

Getting the class name from a static method in Java

If you are using reflection, you can get the Method object and then:

method.getDeclaringClass().getName()

To get the Method itself, you can probably use:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)

Angular js init ng-model from default values

If you like Kevin Stone's approach above https://stackoverflow.com/a/17823590/584761 consider an easier approach by writing directives for specific tags such as 'input'.

app.directive('input', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if (attrs.ngModel) {
                val = attrs.value || element.text();
                $parse(attrs.ngModel).assign(scope, val);
            }
        }
    }; });

If you go this route you won't have to worry about adding ng-initial to every tag. It automatically sets the value of the model to the tag's value attribute. If you do not set the value attribute it will default to an empty string.

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

Can I use Objective-C blocks as properties?

Of course you could use blocks as properties. But make sure they are declared as @property(copy). For example:

typedef void(^TestBlock)(void);

@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end

In MRC, blocks capturing context variables are allocated in stack; they will be released when the stack frame is destroyed. If they are copied, a new block will be allocated in heap, which can be executed later on after the stack frame is poped.

CSS: Change image src on img:hover

With only html and css, its not posible to change the src of image. If you do replace the img tag with div tag, then you might be able to change the image that is set as the background as like

div {
    background: url('http://dummyimage.com/100x100/000/fff');
}
div:hover {
    background: url('http://dummyimage.com/100x100/eb00eb/fff');
}

And if you think you can use some javascript code then you should be able to change the src of the img tag as below

_x000D_
_x000D_
function hover(element) {_x000D_
  element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');_x000D_
}_x000D_
_x000D_
function unhover(element) {_x000D_
  element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');_x000D_
}
_x000D_
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
_x000D_
_x000D_
_x000D_

How do I debug a stand-alone VBScript script?

Export this folder to a backup file and try remove this folder and all the content.

HKEY_CURRENT_USER\Software\Microsoft\Script Debugger

How to leave a message for a github.com user

Github said on April 3rd 2012 :

Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

Source

Get decimal portion of a number with JavaScript

float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here

ExtJs Gridpanel store refresh

Refresh Grid Store

Ext.getCmp('GridId').getStore().reload();

This will reload the grid store and get new data.

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.

How to create a localhost server to run an AngularJS project

If you're running node.js http-server is super easy.

cd into your project folder and

npx http-server -o 

# or, install it separately so you don't need npx
npm install -g http-server
http-server -o 

-o is to open browser to the page. Run http-server --help to view other options such as changing the port number

Don't have node?

these other one-liners might be easier if you don't have node/npm installed.

For example python comes preinstalled on most systems, so John Doe's python servers below would be quicker.

MacOS comes installed with ruby, so this is another easy option if you're running a Mac: ruby -run -ehttpd . -p8000 and open your browser to http://localhost:8000.

makefiles - compile all c files at once

SRCS=$(wildcard *.c)

OBJS=$(SRCS:.c=.o)

all: $(OBJS)

Can't get Python to import from a different folder

After going through the answers given by these contributors above - Zorglub29, Tom, Mark, Aaron McMillin, lucasamaral, JoeyZhao, Kjeld Flarup, Procyclinsur, martin.zaenker, tooty44 and debugging the issue that I was facing I found out a different use case due to which I was facing this issue. Hence adding my observations below for anybody's reference.

In my code I had a cyclic import of classes. For example:

src
 |-- utilities.py (has Utilities class that uses Event class)  
 |-- consume_utilities.py (has Event class that uses Utilities class)
 |-- tests
      |-- test_consume_utilities.py (executes test cases that involves Event class)

I got following error when I tried to execute python -m pytest tests/test_utilities.py for executing UTs written in test_utilities.py.

ImportError while importing test module '/Users/.../src/tests/test_utilities.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_utilities.py:1: in <module>
    from utilities import Utilities
...
...
E   ImportError: cannot import name 'Utilities'

The way I resolved the error was by re-factoring my code to move the functionality in cyclic import class so that I could remove the cyclic import of classes.

Note, I have __init__.py file in my 'src' folder as well as 'tests' folder and still was able to get rid of the 'ImportError' just by re-factoring the code.

Following stackoverflow link provides much more details on Circular dependency in Python.

Simple Random Samples from a Sql database

Maybe you could do

SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)

How to detect a remote side socket close?

The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this:

public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}

Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.

The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.

Examples for string find in Python

If you want to search for the last instance of a string in a text, you can run rfind.

Example:

   s="Hello"
   print s.rfind('l')

output: 3

*no import needed

Complete syntax:

stringEx.rfind(substr, beg=0, end=len(stringEx))

How to take backup of a single table in a MySQL database?

You can use this code:

This example takes a backup of sugarcrm database and dumps the output to sugarcrm.sql

# mysqldump -u root -ptmppassword sugarcrm > sugarcrm.sql

# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

The sugarcrm.sql will contain drop table, create table and insert command for all the tables in the sugarcrm database. Following is a partial output of sugarcrm.sql, showing the dump information of accounts_contacts table:

--

-- Table structure for table accounts_contacts

DROP TABLE IF EXISTS `accounts_contacts`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `accounts_contacts` (
`id` varchar(36) NOT NULL,
`contact_id` varchar(36) default NULL,
`account_id` varchar(36) default NULL,
`date_modified` datetime default NULL,
`deleted` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `idx_account_contact` (`account_id`,`contact_id`),
KEY `idx_contid_del_accid` (`contact_id`,`deleted`,`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--

Matching special characters and letters in regex

I tried a bunch of these but none of them worked for all of my tests. So I found this:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$

from this source: https://www.w3resource.com/javascript/form/password-validation.php

Parse JSON String into List<string>

Try this:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
    public static void Main()
    {
        List<Man> Men = new List<Man>();

        Man m1 = new Man();
        m1.Number = "+1-9169168158";
        m1.Message = "Hello Bob from 1";
        m1.UniqueCode = "0123";
        m1.State = 0;

        Man m2 = new Man();
        m2.Number = "+1-9296146182";
        m2.Message = "Hello Bob from 2";
        m2.UniqueCode = "0125";
        m2.State = 0;

        Men.AddRange(new Man[] { m1, m2 });

        string result = JsonConvert.SerializeObject(Men);
        Console.WriteLine(result);  

        List<Man> NewMen = JsonConvert.DeserializeObject<List<Man>>(result);
        foreach(Man m in NewMen) Console.WriteLine(m.Message);
    }
}
public class Man
{
    public string Number{get;set;}
    public string Message {get;set;}
    public string UniqueCode {get;set;}
    public int State {get;set;}
}

Where is database .bak file saved from SQL Server Management Studio?

Set registry item for your server instance. For example:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.2\MSSQLServer\BackupDirectory

Android: TextView: Remove spacing and padding on top and bottom

See this:

Align ImageView with EditText horizontally

It seems that the background image of EditText has some transparent pixels which also add padding.

A solution is to change the default background of EditText to something else (or nothing, but no background for a EditText is probably not acceptable). That's can be made setting android:background XML attribute.

android:background="@drawable/myEditBackground"

How to use `subprocess` command with pipes

To use a pipe with the subprocess module, you have to pass shell=True.

However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.

COPY with docker but with exclusion

For those using gcloud build:

gcloud build ignores .dockerignore and looks instead for .gcloudignore

Use:

cp .dockerignore .gcloudignore

Source

writing to serial port from linux command line

If you want to use hex codes, you should add -e option to enable interpretation of backslash escapes by echo (but the result is the same as with echoCtrlRCtrlB). And as wallyk said, you probably want to add -n to prevent the output of a newline:

echo -en '\x12\x02' > /dev/ttyS0

Also make sure that /dev/ttyS0 is the port you want.

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf. Look for the lines that read:

# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true

Just remove the # in front of httpinterface and restart the mongod service:

sudo restart mongod

Note: You can also enable the rest interface by adding a line that reads rest=true right below the httpinterface line mentioned above.

Get List of connected USB Devices

Adel Hazzah's answer gives working code, Daniel Widdis's and Nedko's comments mention that you need to query Win32_USBControllerDevice and use its Dependent property, and Daniel's answer gives a lot of detail without code.

Here's a synthesis of the above discussion to provide working code that lists the directly accessible PNP device properties of all connected USB devices:

using System;
using System.Collections.Generic;
using System.Management; // reference required

namespace cSharpUtilities
{
    class UsbBrowser
    {

        public static void PrintUsbDevices()
        {
            IList<ManagementBaseObject> usbDevices = GetUsbDevices();

            foreach (ManagementBaseObject usbDevice in usbDevices)
            {
                Console.WriteLine("----- DEVICE -----");
                foreach (var property in usbDevice.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
                Console.WriteLine("------------------");
            }
        }

        public static IList<ManagementBaseObject> GetUsbDevices()
        {
            IList<string> usbDeviceAddresses = LookUpUsbDeviceAddresses();

            List<ManagementBaseObject> usbDevices = new List<ManagementBaseObject>();

            foreach (string usbDeviceAddress in usbDeviceAddresses)
            {
                // query MI for the PNP device info
                // address must be escaped to be used in the query; luckily, the form we extracted previously is already escaped
                ManagementObjectCollection curMoc = QueryMi("Select * from Win32_PnPEntity where PNPDeviceID = " + usbDeviceAddress);
                foreach (ManagementBaseObject device in curMoc)
                {
                    usbDevices.Add(device);
                }
            }

            return usbDevices;
        }

        public static IList<string> LookUpUsbDeviceAddresses()
        {
            // this query gets the addressing information for connected USB devices
            ManagementObjectCollection usbDeviceAddressInfo = QueryMi(@"Select * from Win32_USBControllerDevice");

            List<string> usbDeviceAddresses = new List<string>();

            foreach(var device in usbDeviceAddressInfo)
            {
                string curPnpAddress = (string)device.GetPropertyValue("Dependent");
                // split out the address portion of the data; note that this includes escaped backslashes and quotes
                curPnpAddress = curPnpAddress.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1];

                usbDeviceAddresses.Add(curPnpAddress);
            }

            return usbDeviceAddresses;
        }

        // run a query against Windows Management Infrastructure (MI) and return the resulting collection
        public static ManagementObjectCollection QueryMi(string query)
        {
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection result = managementObjectSearcher.Get();

            managementObjectSearcher.Dispose();
            return result;
        }

    }

}

You'll need to add exception handling if you want it. Consult Daniel's answer if you want to figure out the device tree and such.

Execution failed for task ':app:compileDebugAidl': aidl is missing

Use your file browser and copy-paste the IInAppBillingService.aidl into /app/src/main/aidl/com/android/vending/billing/

JComboBox Selection Change Listener?

you can do this with jdk >= 8

getComboBox().addItemListener(this::comboBoxitemStateChanged);

so

public void comboBoxitemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
        YourObject selectedItem = (YourObject) e.getItem();
        //TODO your actitons
    }
}

How do I pass parameters to a jar file at the time of execution?

The JAVA Documentation says:

java [ options ] -jar file.jar [ argument ... ]

and

... Non-option arguments after the class name or JAR file name are passed to the main function...

Maybe you have to put the arguments in single quotes.

How to use <md-icon> in Angular Material?

By Using like
use css and font same location

@font-face {
    font-family: 'Material-Design-Icons';
    src: url('Material-Design-Icons.eot');
    src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
         url('Material-Design-Icons.woff2') format('woff2'),
         url('Material-Design-Icons.woff') format('woff'),
         url('Material-Design-Icons.ttf') format('truetype'),
         url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

"Could not find a valid gem in any repository" (rubygame and others)

I tried to install a gem which is for JRuby only, running into the same error. Using jruby's command worked then:

jruby -S gem install some_jruby_gem

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

Plugin with id 'com.google.gms.google-services' not found

Add classpath com.google.gms:google-services:3.0.0 dependencies at project level build.gradle

Refer the sample block from project level build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {

        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

How to install Laravel's Artisan?

You just have to read the laravel installation page:

  1. Install Composer if not already installed
  2. Open a command line and do:
composer global require "laravel/installer"

Inside your htdocs or www directory, use either:

laravel new appName

(this can lead to an error on windows computers while using latest Laravel (1.3.2)) or:

composer create-project --prefer-dist laravel/laravel appName

(this works also on windows) to create a project called "appName".

To use "php artisan xyz" you have to be inside your project root! as artisan is a file php is going to use... Simple as that ;)

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

I was facing the same issue. Everything was fine but in

bootstrap/cache/config.php

always had the incomplete password. Upon digging further, realized that the password had '#' character in it and that was getting dropped. As '#' is used to mark a line as a comment.

How might I convert a double to the nearest integer value?

double d;
int rounded = (int)Math.Round(d);

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

jQuery add text to span within a div

You can use:

$("#tagscloud span").text("Your text here");

The same code will also work for the second case. You could also use:

$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");

Laravel - Pass more than one variable to view

Its simple :)

<link rel="icon" href="{{ asset('favicon.ico')}}" type="image/x-icon" />

How do I clear inner HTML

The h1 tags unfortunately do not receive the onmouseout events.

The simple Javascript snippet below will work for all elements and uses only 1 mouse event.

Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."

_x000D_
_x000D_
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
    if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
_x000D_
_x000D_

This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

CentOS: Enabling GD Support in PHP Installation

The thing that did the trick for me eventually was:

yum install gd gd-devel php-gd

and then restart apache:

service httpd restart

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

How to set a Fragment tag by code?

I know it's been 6 years ago but if anyone is facing the same problem do like I've done:

Create a custom Fragment Class with a tag field:

public class MyFragment extends Fragment {
 private String _myTag;
 public void setMyTag(String value)
 {
   if("".equals(value))
     return;
   _myTag = value;
 }
 //other code goes here
}

Before adding the fragment to the sectionPagerAdapter set the tag just like that:

 MyFragment mfrag= new MyFragment();
 mfrag.setMyTag("TAG_GOES_HERE");
 sectionPagerAdapter.AddFragment(mfrag);

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!

In the child pom, use something like this:

<modelVersion>4.0.0</modelVersion>

<parent>
  <groupId>org.felipe</groupId>
  <artifactId>tutorial_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
</parent>

<artifactId>tutorial_maven_jar</artifactId>

Using properties like ${project.groupId} won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.

AngularJS ng-style with a conditional expression

For single css property

ng-style="1==1 && {'color':'red'}"

For multiple css properties below can be referred

ng-style="1==1 && {'color':'red','font-style': 'italic'}"

Replace 1==1 with your condition expression

How to tell git to use the correct identity (name and email) for a given project?

As of Git 2.13 you can use an includeIf in your gitconfig to include a file with a different configuration based on the path of the repository where you are running your git commands.

Since a new enough Git comes with Ubuntu 18.04 I've been using this in my ~/.gitconfig quite happily.

[include]
  path = ~/.gitconfig.alias # I like to keep global aliases separate
  path = ~/.gitconfig.defaultusername # can maybe leave values unset/empty to get warned if a below path didn't match
# If using multiple identities can use per path user/email
# The trailing / is VERY important, git won't apply the config to subdirectories without it
[includeIf "gitdir:~/projects/azure/"]
  path = ~/.gitconfig.azure # user.name and user.email for Azure
[includeIf "gitdir:~/projects/gitlab/"]
  path = ~/.gitconfig.gitlab # user.name and user.email for GitLab
[includeIf "gitdir:~/projects/foss/"]
  path = ~/.gitconfig.github # user.name and user.email for GitHub

https://motowilliams.com/conditional-includes-for-git-config#disqus_thread

To use Git 2.13 you will either need to add a PPA (Ubuntu older than 18.04/Debian) or download the binaries and install (Windows/other Linux).

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to convert color code into media.brush?

For WinRT (Windows Store App)

using Windows.UI;
using Windows.UI.Xaml.Media;

    public static Brush ColorToBrush(string color) // color = "#E7E44D"
    {
        color = color.Replace("#", "");
        if (color.Length == 6)
        {
            return new SolidColorBrush(ColorHelper.FromArgb(255,
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
        }
        else
        {
            return null;
        }
    }

How do you underline a text in Android XML?

Another way to do it, is creating a custom component extending TextView. It's good for cases where you need to have multiple underlined TextViews.

Here's the code for the component:

package com.myapp.components;

import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;

public class LinkTextView extends AppCompatTextView {
    public LinkTextView(Context context) {
        this(context, null);
    }

    public LinkTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        SpannableString content = new SpannableString(text);
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);

        super.setText(content, type);
    }
}

And how to use it in xml:

<com.myapp.components.LinkTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

How to show and update echo on same line

You can try this.. My own version of it..

funcc() {
while true ; do 
for i in \| \/ \- \\ \| \/ \- \\; do 
  echo -n -e "\r$1  $i  "
sleep 0.5
done  
#echo -e "\r                                                                                      "
[ -f /tmp/print-stat ] && break 2
done
}

funcc "Checking Kubectl" & &>/dev/null
sleep 5
touch /tmp/print-stat
echo -e "\rPrint Success                  "

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

JavaScript URL Decode function

//How decodeURIComponent Works

function proURIDecoder(val)
{
  val=val.replace(/\+/g, '%20');
  var str=val.split("%");
  var cval=str[0];
  for (var i=1;i<str.length;i++)
  {
    cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
  }

  return cval;
}

document.write(proURIDecoder(window.location.href));

Merge up to a specific commit

Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:

branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2

For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.

To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:

git co A
git co SHA-of-A2
git co -b AA

Then we created a branch BB from commit B3:

git co B
git co SHA-of-B3
git co -b BB

At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.

It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Detect Route Change with react-router

react-router v6

In the upcoming v6, this can be done by combining the useLocation and useEffect hooks

import { useLocation } from 'react-router-dom';

const MyComponent = () => {
  const location = useLocation()

  React.useEffect(() => {
    // runs on location, i.e. route, change
    console.log('handle route change here', location)
  }, [location])
  ...
}

For convenient reuse, you can do this in a custom useLocationChange hook

// runs action(location) on location, i.e. route, change
const useLocationChange = (action) => {
  const location = useLocation()
  React.useEffect(() => { action(location) }, [location])
}

const MyComponent1 = () => {
  useLocationChange((location) => { 
    console.log('handle route change here', location) 
  })
  ...
}

const MyComponent2 = () => {
  useLocationChange((location) => { 
    console.log('and also here', location) 
  })
  ...
}

If you also need to see the previous route on change, you can combine with a usePrevious hook

const usePrevious(value) {
  const ref = React.useRef()
  React.useEffect(() => { ref.current = value })

  return ref.current
}

const useLocationChange = (action) => {
  const location = useLocation()
  const prevLocation = usePrevious(location)
  React.useEffect(() => { 
    action(location, prevLocation) 
  }, [location])
}

const MyComponent1 = () => {
  useLocationChange((location, prevLocation) => { 
    console.log('changed from', prevLocation, 'to', location) 
  })
  ...
}

It's important to note that all the above fire on the first client route being mounted, as well as subsequent changes. If that's a problem, use the latter example and check that a prevLocation exists before doing anything.

How do I send a JSON string in a POST request in Go

If you already have a struct.

import (
    "bytes"
    "encoding/json"
    "io"
    "net/http"
    "os"
)

// .....

type Student struct {
    Name    string `json:"name"`
    Address string `json:"address"`
}

// .....

body := &Student{
    Name:    "abc",
    Address: "xyz",
}

payloadBuf := new(bytes.Buffer)
json.NewEncoder(payloadBuf).Encode(body)
req, _ := http.NewRequest("POST", url, payloadBuf)

client := &http.Client{}
res, e := client.Do(req)
if e != nil {
    return e
}

defer res.Body.Close()

fmt.Println("response Status:", res.Status)
// Print the body to the stdout
io.Copy(os.Stdout, res.Body)

Full gist.

Add newline to VBA or Visual Basic 6

There are actually two ways of doing this:

  1. st = "Line 1" + vbCrLf + "Line 2"

  2. st = "Line 1" + vbNewLine + "Line 2"

These even work for message boxes (and all other places where strings are used).

how can I connect to a remote mongo server from Mac OS terminal

Another way to do this is:

mongo mongodb://mongoDbIPorDomain:port

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }

Numpy where function multiple conditions

I have worked out this simple example

import numpy as np

ar = np.array([3,4,5,14,2,4,3,7])

print [X for X in list(ar) if (X >= 3 and X <= 6)]

>>> 
[3, 4, 5, 4, 3]

Bash if statement with multiple conditions throws an error

You can get some inspiration by reading an entrypoint.sh script written by the contributors from MySQL that checks whether the specified variables were set.

As the script shows, you can pipe them with -a, e.g.:

if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
    ...
fi

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

WP -- Get posts by category?

add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]

Is it possible to add dynamically named properties to JavaScript object?

Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.

var defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

//Call the method to add properties to any object
defineProp( data, "PropertyA",  1 );
defineProp( data, "PropertyB",  2 );
defineProp( data, "PropertyC",  3 );

reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript

PHP: how can I get file creation date?

Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

i had the same problem with my jar the solution

  1. Create the MANIFEST.MF file:

Manifest-Version: 1.0

Sealed: true

Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar

Main-Class: com.MainClass

  1. Right click on project, Select Export.

select export all outpout folders for checked project

  1. select using existing manifest from workspace and select the MANIFEST.MF file

This worked for me :)

How to redirect a URL path in IIS?

Taken from Microsoft Technet.

Redirecting Web Sites in IIS 6.0 (IIS 6.0)


When a browser requests a page or program on your Web site, the Web server locates the page identified by the URL and returns it to the browser. When you move a page on your Web site, you can't always correct all of the links that refer to the old URL of the page. To make sure that browsers can find the page at the new URL, you can instruct the Web server to redirect the browser to the new URL.

You can redirect requests for files in one directory to a different directory, to a different Web site, or to another file in a different directory. When the browser requests the file at the original URL, the Web server instructs the browser to request the page by using the new URL.

Important

You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

Procedures

To redirect requests to another Web site or directory


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination directory or Web site. For example, to redirect all requests for files in the Catalog directory to the NewCatalog directory, type /NewCatalog.

To redirect all requests to a single file


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination file.

  5. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

    You can use wildcards and redirect variables in the destination URL to precisely control how the original URL is translated into the destination URL.

    You can also use the redirect method to redirect all requests for files in a particular directory to a program. Generally, you should pass any parameters from the original URL to the program, which you can do by using redirect variables.

    To redirect requests to a program


  6. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  7. Click the Home Directory, Virtual Directory, or Directory tab.

  8. Under The content for this source should come from, click A redirection to a URL.

    In the Redirect to box, type the URL of the program, including any redirect variables needed to pass parameters to the program. For example, to redirect all requests for scripts in a Scripts directory to a logging program that records the requested URL and any parameters passed with the URL, type /Scripts/Logger.exe?URL=$V+PARAMS=$P. $V and $P are redirect variables.

  9. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Here's my super late implementation in PHP. This one's recursive. I wrote it just before I found this post. I wanted to see if others had solved this problem already...

public function GetColumn($intNumber, $strCol = null) {

    if ($intNumber > 0) {
        $intRem = ($intNumber - 1) % 26;
        $strCol = $this->GetColumn(intval(($intNumber - $intRem) / 26), sprintf('%s%s', chr(65 + $intRem), $strCol));
    }

    return $strCol;
}

Why is synchronized block better than synchronized method?

Define 'better'. A synchronized block is only better because it allows you to:

  1. Synchronize on a different object
  2. Limit the scope of synchronization

Now your specific example is an example of the double-checked locking pattern which is suspect (in older Java versions it was broken, and it is easy to do it wrong).

If your initialization is cheap, it might be better to initialize immediately with a final field, and not on the first request, it would also remove the need for synchronization.

How to sort an array in descending order in Ruby

Simple Solution from ascending to descending and vice versa is:

STRINGS

str = ['ravi', 'aravind', 'joker', 'poker']
asc_string = str.sort # => ["aravind", "joker", "poker", "ravi"]
asc_string.reverse # => ["ravi", "poker", "joker", "aravind"]

DIGITS

digit = [234,45,1,5,78,45,34,9]
asc_digit = digit.sort # => [1, 5, 9, 34, 45, 45, 78, 234]
asc_digit.reverse # => [234, 78, 45, 45, 34, 9, 5, 1]

How do I set up IntelliJ IDEA for Android applications?

The 5th step in "New Project' has apparently changed slightly since.

Where it says android sdk then has the drop down menu that says none, there is no longer a 'new' button.

  • 5.)

    • a.)click the ... to the right of none.
    • b.)click the + in the top left of new window dialog. (Add new Sdk)
    • c.)click android sdk from drop down menu
    • d.)select home directory for your android sdk
    • e.)select java sdk version you want to use
    • f.)select android build target.
    • g.)hit ok!

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Try looking here: Best way to get application folder path

To quote from there:

System.IO.Directory.GetCurrentDirectory() returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

Checking if form has been submitted - PHP

On a different note, it is also always a good practice to add a token to your form and verify it to check if the data was not sent from outside. Here are the steps:

  1. Generate a unique token (you can use hash) Ex:

    $token = hash (string $algo , string $data [, bool $raw_output = FALSE ] );
    
  2. Assign this token to a session variable. Ex:

    $_SESSION['form_token'] = $token;
    
  3. Add a hidden input to submit the token. Ex:

    input type="hidden" name="token" value="{$token}"
    
  4. then as part of your validation, check if the submitted token matches the session var.

    Ex: if ( $_POST['token'] === $_SESSION['form_token'] ) ....
    

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

Better way of getting time in milliseconds in javascript?

I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now() functionality to get finer grain timing in javascript.

window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||            
        Date.now  /*none found - fallback to browser default */
})();

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How to redirect output of an already running process

Screen

If process is running in a screen session you can use screen's log command to log the output of that window to a file:

Switch to the script's window, C-a H to log.
Now you can :

$ tail -f screenlog.2 | grep whatever

From screen's man page:

log [on|off]

Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.

I'm sure tmux has something similar as well.

Check if an element is present in an array

In lodash you can use _.includes (which also aliases to _.contains)

You can search the whole array:

_.includes([1, 2, 3], 1); // true

You can search the array from a starting index:

_.includes([1, 2, 3], 1, 1);  // false (begins search at index 1)

Search a string:

_.includes('pebbles', 'eb');  // true (string contains eb)

Also works for checking simple arrays of objects:

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');    // true
_.includes({ 'user': 'fred', 'age': false }, false);  // true

One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects

_.includes({ 'user': 'fred', 'age': {} }, {});   // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3);   // false

Setting width of spreadsheet cell using PHPExcel

This worked for me:

$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);

be sure to add setAuzoSize(false), before the setWidth(); as Rolland mentioned

iPhone is not available. Please reconnect the device

Before you debug with iPhone, follow this mapping table about the version of Xcode and iOS:

Xcode 12.3 ? iOS 14.3

Xcode 12.2 ? iOS 14.2

Xcode 12.1 ? iOS 14.1

Xcode 12 ? iOS 14

Xcode 11.7 ? iOS 13.7

Xcode 11.6 ? iOS 13.6

Xcode 11.5 ? iOS 13.5

Xcode 11.4 ? iOS 13.4

Download at https://developer.apple.com/download/more/.

If you're still encountering the error, try to unpair the device within the menu Window > Devices and Simulators, clean Xcode, reconnect and trust the device, then re-run. It worked for me! enter image description here

Get more info: https://en.wikipedia.org/wiki/Xcode

Hide div after a few seconds

<script>
      $(function() {
      $(".hide-it").hide(7000);
    });              
</script>

<div id="hide-it">myDiv</div>

What is %0|%0 and how does it work?

It's a logic bomb, it keeps recreating itself and takes up all your CPU resources. It overloads your computer with too many processes and it forces it to shut down. If you make a batch file with this in it and start it you can end it using taskmgr. You have to do this pretty quickly or your computer will be too slow to do anything.

Using Bootstrap Tooltip with AngularJS

You can do this with AngularStrap which

is a set of native directives that enables seamless integration of Bootstrap 3.0+ into your AngularJS 1.2+ app."

You can inject the entire library like this:

var app = angular.module('MyApp', ['mgcrea.ngStrap']); 

Or only pull in the tooltip feature like this:

var app = angular.module('MyApp', ['mgcrea.ngStrap.tooltip']); 

Demo in Stack Snippets

_x000D_
_x000D_
var app = angular.module('MyApp', ['mgcrea.ngStrap']);  
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.tpl.min.js"></script>_x000D_
_x000D_
<div ng-app="MyApp" class="container" >_x000D_
_x000D_
  <button type="button" _x000D_
          class="btn btn-default" _x000D_
          data-trigger="hover" _x000D_
          data-placement="right"_x000D_
          data-title="Tooltip on right"_x000D_
          bs-tooltip>_x000D_
    MyButton_x000D_
  </button>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Combine Multiple child rows into one row MYSQL

The easiest way would be to make use of the GROUP_CONCAT group function here..

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  GROUP_CONCAT(Ordered_Options.Value) as `Options`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Which would output:

Id              ItemName       Options

1               Pizza          Pepperoni,Extra Cheese

2               Stromboli      Extra Cheese

That way you can have as many options as you want without having to modify your query.

Ah, if you see your results getting cropped, you can increase the size limit of GROUP_CONCAT like this:

SET SESSION group_concat_max_len = 8192;

Fixed height and width for bootstrap carousel

Apply following style to carousel listbox.

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

Convert base-2 binary number string to int

Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)

add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])

Highcharts - how to have a chart with dynamic height?

Another good option is, to pass a renderTo HTML reference. If it is a string, the element by that id is used. Otherwise you can do:

chart: {
    renderTo: document.getElementById('container')
},

or with jquery:

chart: {
    renderTo: $('#container')[0]
},

Further information can be found here: https://api.highcharts.com/highstock/chart.renderTo

How to redirect 'print' output to a file using python?

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
    print >> f, 'Filename:', filename     # Python 2.x
    print('Filename:', filename, file=f)  # Python 3.x

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

import sys

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f

for i in range(2):
    print('i = ', i)

sys.stdout = orig_stdout
f.close()

Since Python 3.4 there's a simple context manager available to do this in the standard library:

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

Redirecting externally from the shell itself is another option, and often preferable:

./script.py > out.txt

Other questions:

What is the first filename in your script? I don't see it initialized.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

onclick or inline script isn't working in extension

Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).

You are going to have to do something similar to this:

Assign an ID to the link (<a onClick=hellYeah("xxx")> becomes <a id="link">), and use addEventListener to bind the event. Put the following in your popup.js file:

document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('link');
    // onClick's logic below:
    link.addEventListener('click', function() {
        hellYeah('xxx');
    });
});

popup.js should be loaded as a separate script file:

<script src="popup.js"></script>

How to check for the type of a template parameter?

I think todays, it is better to use, but only with C++17.

#include <type_traits>

template <typename T>
void foo() {
    if constexpr (std::is_same_v<T, animal>) {
        // use type specific operations... 
    } 
}

If you use some type specific operations in if expression body without constexpr, this code will not compile.

How do I get the object if it exists, or None if it does not exist?

To make things easier, here is a snippet of the code I wrote, based on inputs from the wonderful replies here:

class MyManager(models.Manager):

    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except ObjectDoesNotExist:
            return None

And then in your model:

class MyModel(models.Model):
    objects = MyManager()

That's it. Now you have MyModel.objects.get() as well as MyModel.objetcs.get_or_none()

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

For MacOS 10.15 Catalina try to install the previous openssl:

brew update && brew upgrade
brew uninstall --ignore-dependencies openssl
brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb

Play audio with Python

Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.

Install via pip:

$ pip install playsound

Once you've installed, you can use it like this:

from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')

Call of overloaded function is ambiguous

That is ambiguous because a pointer is just an address, so an int can also be treated as a pointer – 0 (an int) can be converted to unsigned int or char * equally easily.

The short answer is to call p.setval() with something that's unambiguously one of the types it's implemented for: unsigned int or char *. p.setval(0U), p.setval((unsigned int)0), and p.setval((char *)0) will all compile.

It's generally a good idea to stay out of this situation in the first place, though, by not defining overloaded functions with such similar types.

Omitting the first line from any Linux command output

This is a quick hacky way: ls -lart | grep -v ^total.

Basically, remove any lines that start with "total", which in ls output should only be the first line.

A more general way (for anything):

ls -lart | sed "1 d"

sed "1 d" means only print everything but first line.

What is the difference between And and AndAlso in VB.NET?

The And operator will check all conditions in the statement before continuing, whereas the Andalso operator will stop if it knows the condition is false. For example:

if x = 5 And y = 7

Checks if x is equal to 5, and if y is equal to 7, then continues if both are true.

if x = 5 AndAlso y = 7

Checks if x is equal to 5. If it's not, it doesn't check if y is 7, because it knows that the condition is false already. (This is called short-circuiting.)

Generally people use the short-circuiting method if there's a reason to explicitly not check the second part if the first part is not true, such as if it would throw an exception if checked. For example:

If Not Object Is Nothing AndAlso Object.Load()

If that used And instead of AndAlso, it would still try to Object.Load() even if it were nothing, which would throw an exception.

Explaining Apache ZooKeeper

My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface

From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.

Example CLI commands

create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode

Try yourself

How to spin up a zookeper environment within minutes on docker for windows, linux or mac:

One time set up:

docker network create dn

Run server in a terminal window:

docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper

Run client in a second terminal window:

docker run -it --rm --network dn zookeeper zkCli.sh -server zook

See also documentation of image on dockerhub

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

Zip folder in C#

This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);

How to change RGB color to HSV?

Have you considered simply using System.Drawing namespace? For example:

System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();

Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

Because pypy is not 100% compatible, takes 8 gigs of ram to compile, is a moving target, and highly experimental, where cpython is stable, the default target for module builders for 2 decades (including c extensions that don't work on pypy), and already widely deployed.

Pypy will likely never be the reference implementation, but it is a good tool to have.

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

Setting up Gradle for api 26 (Android)

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 compile 'com.android.support:appcompat-v7:26.0.1'
    compile 'com.android.support:recyclerview-v7:26.0.1'
    compile 'com.android.support:cardview-v7:26.0.1'

Regular expression to match URLs in Java

When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.

In this case, as others pointed out, you missed the case insensitivity option.

Cannot catch toolbar home button click event

In my case I had to put the icon using:

toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

And then listen to click events with default onOptionsItemSelected and android.R.id.home id

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

No module named 'openpyxl' - Python 3.4 - Ubuntu

I had the same problem solved using instead of pip install :

sudo apt-get install python-openpyxl
sudo apt-get install python3-openpyxl

The sudo command also works better for other packages.

Change jsp on button click

You could make those submit buttons and inside the servlet your are submitting the form to you could test the name of the button which was pressed and render the corresponding jsp page.

<input type="submit" value="Creazione Nuovo Corso" name="CreateCourse" />
<input type="submit" value="Gestione Autorizzazioni" name="AuthorizationManager" />

Inside the TrainerMenu servlet if request.getParameter("CreateCourse") is not empty then the first button was clicked and you could render the corresponding jsp.

Referring to a Column Alias in a WHERE Clause

How about using a subquery(this worked for me in Mysql)?

SELECT * from (SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary) as 'your_alias'
WHERE daysdiff > 120

Using Font Awesome icon for bullet points, with a single list item element

I'd like to build upon some of the answers above and given elsewhere and suggest using absolute positioning along with the :before pseudo class. A lot of the examples above (and in similar questions) are utilizing custom HTML markup, including Font Awesome's method of handling. This goes against the original question, and isn't strictly necessary.

DEMO HERE

ul {
  list-style-type: none;
  padding-left: 20px;
}

li {
  position: relative;
  padding-left: 20px;
  margin-bottom: 10px
}

li:before {
  position: absolute;
  top: 0;
  left: 0;
  font-family: FontAwesome;
  content: "\f058";
  color: green;
}

That's basically it. You can get the ISO value for use in CSS content on the Font Awesome cheatsheet. Simply use the last 4 alphanumerics prefixed with a backslash. So [&#xf058;] becomes \f058

How do I do an OR filter in a Django query?

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

This ends up with a query like :

(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

What is the difference between a JavaBean and a POJO?

You've seen the formal definitions above, for all they are worth.

But don't get too hung up on definitions. Let's just look more at the sense of things here.

JavaBeans are used in Enterprise Java applications, where users frequently access data and/or application code remotely, i.e. from a server (via web or private network) via a network. The data involved must therefore be streamed in serial format into or out of the users' computers - hence the need for Java EE objects to implement the interface Serializable. This much of a JavaBean's nature is no different to Java SE application objects whose data is read in from, or written out to, a file system. Using Java classes reliably over a network from a range of user machine/OS combinations also demands the adoption of conventions for their handling. Hence the requirement for implementing these classes as public, with private attributes, a no-argument constructor and standardised getters and setters.

Java EE applications will also use classes other than those that were implemented as JavaBeans. These could be used in processing input data or organizing output data but will not be used for objects transferred over a network. Hence the above considerations need not be applied to them bar that the be valid as Java objects. These latter classes are referred to as POJOs - Plain Old Java Objects.

All in all, you could see Java Beans as just Java objects adapted for use over a network.

There's an awful lot of hype - and no small amount of humbug - in the software world since 1995.

jQuery.post( ) .done( ) and success:

jQuery used to ONLY have the callback functions for success and error and complete.

Then, they decided to support promises with the jqXHR object and that's when they added .done(), .fail(), .always(), etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.

As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.

The .success() method has been deprecated in favor of the common promise object method names.

From the jQuery doc, you can see how various promise methods relate to the callback types:

jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {}); Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use .then().

How can I check if a Perl module is installed on my system from the command line?

You can check for a module's installation path by:

perldoc -l XML::Simple

The problem with your one-liner is that, it is not recursively traversing directories/sub-directories. Hence, you get only pragmatic module names as output.

How do I unload (reload) a Python module?

2018-02-01

  1. module foo must be imported successfully in advance.
  2. from importlib import reload, reload(foo)

31.5. importlib — The implementation of import — Python 3.6.4 documentation

Are members of a C++ struct initialized to 0 by default?

Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:

Snapshot s;
memset(&s, 0, sizeof (s));

or similarly

Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));

I wouldn't go so far as to use calloc() in a C++ program though.

Fixed position but relative to container

position: sticky that is a new way to position elements that is conceptually similar to position: fixed. The difference is that an element with position: sticky behaves like position: relative within its parent, until a given offset threshold is met in the viewport.

In Chrome 56 (currently beta as of December 2016, stable in Jan 2017) position: sticky is now back.

https://developers.google.com/web/updates/2016/12/position-sticky

More details are in Stick your landings! position: sticky lands in WebKit.

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Currently, Microsoft don't provide download option for '2007 Office System Driver: Data Connectivity Components' and click on first answer for '2007 Office System Driver: Data Connectivity Components' redirect to Cnet where getting download link creates confusion.

That's why who use SQL Server 2014 and latest version of SQL Server in Windows 10 click on below link for download this component which resolve your problem : - Microsoft Access Database Engine 2010

Happy Coding!

Convert Rtf to HTML

Mike Stall posted the code for one he wrote in c# here :

http://blogs.msdn.com/jmstall/archive/2006/10/20/rtf_5F00_html.aspx

Background color not showing in print preview

if you are using Bootstrap.just use this code in your custom css file. Bootstrap removes all your colors in print preview.

@media print{
  .box-text {

    font-size: 27px !important; 
    color: blue !important;
    -webkit-print-color-adjust: exact !important;
  }
}

Find a line in a file and remove it

You want to do something like the following:

  • Open the old file for reading
  • Open a new (temporary) file for writing
  • Iterate over the lines in the old file (probably using a BufferedReader)
    • For each line, check if it matches what you are supposed to remove
    • If it matches, do nothing
    • If it doesn't match, write it to the temporary file
  • When done, close both files
  • Delete the old file
  • Rename the temporary file to the name of the original file

(I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

For those using a fresh install of Ubuntu, or another Linux distro, make sure your have at least the package "build-essential" before you try to compile Eclipse CDT projects.

At Terminal, type:

sudo apt-get install build-essential

It should be enough to compile and run your apps.

Of course, you can also perform full g++ install, using:

sudo apt-get install g++

Unit Testing: DateTime.Now

Moles:

[Test]  
public void TestOfDateTime()  
{  
      var firstValue = DateTime.Now;
      MDateTime.NowGet = () => new DateTime(2000,1,1);
      var secondValue = DateTime.Now;
      Assert(firstValue > secondValue); // would be false if 'moleing' failed
}

Disclaimer - I work on Moles

How to start new activity on button click

Starting an activity from another activity is very common scenario among android applications.
To start an activity you need an Intent object.

How to create Intent Objects?

An intent object takes two parameter in its constructor

  1. Context
  2. Name of the activity to be started. (or full package name)

Example:

enter image description here

So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity (HomeActivity-->DetailActivity).

Here is the code snippet which shows how to start DetailActivity from

HomeActivity.

Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);

And you are done.

Coming back to button click part.

Button button = (Button) findViewById(R.id.someid);

button.setOnClickListener(new View.OnClickListener() {
     
     @Override
     public void onClick(View view) {
         Intent i = new Intent(HomeActivity.this,DetailActivity.class);
         startActivity(i);  
      }

});

Styling twitter bootstrap buttons

Here is a good resource: http://charliepark.org/bootstrap_buttons/

You can change color and see the effect in action.

What is the use of hashCode in Java?

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

H2 in-memory database. Table not found

I have tried the above solution,but in my case as suggested in the console added the property DB_CLOSE_ON_EXIT=FALSE, it fixed the issue.

 spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false;DB_CLOSE_ON_EXIT=FALSE

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

jQuery if statement, syntax

If you're using Jquery to manipulate the DOM, then I have found the following a good way to include logic in a Jquery statement:

$(selector).addClass(A && B?'classIfTrue':'');

Reverse a comparator in Java 8

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

In result you get a easy reusable Class File, testable unit step and clear javadoc.

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}

Make button width fit to the text

Remove the width and display: block and then add display: inline-block to the button. To have it remain centered you can either add text-align: center; on the body or do the same on a newly created container.

The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.

Example: http://cssdeck.com/labs/2u4kf6dv

Get a list of all the files in a directory (recursive)

This code works for me:

import groovy.io.FileType

def list = []

def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  list << file
}

Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:

list.each {
  println it.path
}

How do I exit a foreach loop in C#?

Use break.


Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);

Razor MVC Populating Javascript array with Model Array

To expand on the top-voted answer, for reference, if the you want to add more complex items to the array:

@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");

etc.

Furthermore, if you want to pass the array as a parameter to your controller, you can stringify it first:

myArray = JSON.stringify({ 'myArray': myArray });

How can we run a test method with multiple parameters in MSTest?

There is, of course, another way to do this which has not been discussed in this thread, i.e. by way of inheritance of the class containing the TestMethod. In the following example, only one TestMethod has been defined but two test cases have been made.

In Visual Studio 2012, it creates two tests in the TestExplorer:

  1. DemoTest_B10_A5.test
  2. DemoTest_A12_B4.test

    public class Demo
    {
        int a, b;
    
        public Demo(int _a, int _b)
        {
            this.a = _a;
            this.b = _b;
        }
    
        public int Sum()
        {
            return this.a + this.b;
        }
    }
    
    public abstract class DemoTestBase
    {
        Demo objUnderTest;
        int expectedSum;
    
        public DemoTestBase(int _a, int _b, int _expectedSum)
        {
            objUnderTest = new Demo(_a, _b);
            this.expectedSum = _expectedSum;
        }
    
        [TestMethod]
        public void test()
        {
            Assert.AreEqual(this.expectedSum, this.objUnderTest.Sum());
        }
    }
    
    [TestClass]
    public class DemoTest_A12_B4 : DemoTestBase
    {
        public DemoTest_A12_B4() : base(12, 4, 16) { }
    }
    
    public abstract class DemoTest_B10_Base : DemoTestBase
    {
        public DemoTest_B10_Base(int _a) : base(_a, 10, _a + 10) { }
    }
    
    [TestClass]
    public class DemoTest_B10_A5 : DemoTest_B10_Base
    {
        public DemoTest_B10_A5() : base(5) { }
    }
    

Postgres manually alter sequence

Use select setval('payments_id_seq', 21, true);

setval contains 3 parameters:

  • 1st parameter is sequence_name
  • 2nd parameter is Next nextval
  • 3rd parameter is optional.

The use of true or false in 3rd parameter of setval is as follows:

SELECT setval('payments_id_seq', 21);           // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true);     // Same as above 
SELECT setval('payments_id_seq', 21, false);    // Next nextval will return 21

The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:

SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;

where table_name is the name of the table, id is the primary key of the table

Simple parse JSON from URL on Android and display in listview

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class GetJsonFromUrl {
    String url = null;

    public GetJsonFromUrl(String url) {
        this.url = url;
    }

    public String GetJsonData() {
        try {
            URL Url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            line = sb.toString();
            connection.disconnect();
            is.close();
            sb.delete(0, sb.length());
            return line;
        } catch (Exception e) {
            return null;
        }
    }
} 

and this class use for post data

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by user on 11/2/16.
 */
public class sendDataToServer {
   public String postdata(String requestURL,HashMap<String,String> postDataParams){
        try {
            String response = "";
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
            Log.d("test", response);
            return response;
        }catch (Exception e){
            return e.toString();
        }
    }

    public String postjson(String url,String json){
        try {

            URL obj = new URL(url);
            HttpURLConnection con= (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept", "application/json");
            String urlParameters = ""+json;

            // Send post request
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());
            return response.toString();
        }catch(Exception e){

            return e.toString();
        }
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }

   /* public String postdata(String url) {
    }*/
}

How to pass value from <option><select> to form action

Like @Shoaib answered, you dont need any jQuery or Javascript. You can to this simply with pure html!

<form method="POST" action="index.php?action=contact_agent">
  <select name="agent_id" required>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <input type="submit" value="Submit">
</form>
  1. Remove &agent_id= from form action since you don't need it there.
  2. Add name="agent_id" to the select
  3. Optionally add word required do indicate that this selection is required.

Since you are using PHP, then by posting the form to index.php you can catch agent_id with $_POST

/** Since you reference action on `form action` then value of $_GET['action'] will be contact_agent */
$action = $_GET['action'];

/** Value of $_POST['agent_id'] will be selected option value */
$agent_id = $_POST['agent_id']; 

As conclusion for such a simple task you should not use any javascript or jQuery. To @FelipeAlvarez that answers your comment

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

Refused to load the script because it violates the following Content Security Policy directive

We used this:

<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; style-src 'self' http://* https://* 'unsafe-inline'; script-src 'self' http://* https://* 'unsafe-inline' 'unsafe-eval'">

open link of google play store in mobile version android

Below code may helps you for display application link of google play sore in mobile version.

For Application link :

Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

  try {
        startActivity(myAppLinkToMarket);

      } catch (ActivityNotFoundException e) {

        //the device hasn't installed Google Play
        Toast.makeText(Setting.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();
              }

For Developer link :

Uri uri = Uri.parse("market://search?q=pub:" + YourDeveloperName);
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

            try {

                startActivity(myAppLinkToMarket);

            } catch (ActivityNotFoundException e) {

                //the device hasn't installed Google Play
                Toast.makeText(Settings.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();

            } 

In Windows cmd, how do I prompt for user input and use the result in another command?

Try this:

@echo off
set /p id="Enter ID: "

You can then use %id% as a parameter to another batch file like jstack %id%.

For example:

set /P id=Enter id: 
jstack %id% > jstack.txt

Function that creates a timestamp in c#

I believe you can create a unix style datestamp accurate to a second using the following

//Find unix timestamp (seconds since 01/01/1970)
long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
timestamp = ticks.ToString();

Adjusting the denominator allows you to choose your level of precision

Declaring abstract method in TypeScript

If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:

/**
 * The interface defines all abstract methods and extends the concrete base class
 */
interface IAnimal extends Animal {
    speak() : void;
}

/**
 * The abstract base class only defines concrete methods & properties.
 */
class Animal {

    private _impl : IAnimal;

    public name : string;

    /**
     * Here comes the clever part: by letting the constructor take an 
     * implementation of IAnimal as argument Animal cannot be instantiated
     * without a valid implementation of the abstract methods.
     */
    constructor(impl : IAnimal, name : string) {
        this.name = name;
        this._impl = impl;

        // The `impl` object can be used to delegate functionality to the
        // implementation class.
        console.log(this.name + " is born!");
        this._impl.speak();
    }
}

class Dog extends Animal implements IAnimal {
    constructor(name : string) {
        // The child class simply passes itself to Animal
        super(this, name);
    }

    public speak() {
        console.log("bark");
    }
}

var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"

Since the Animal class requires an implementation of IAnimal it's impossible to construct an object of type Animal without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal, not Animal. E.g.:

//This works
function letTheIAnimalSpeak(animal: IAnimal) {
    console.log(animal.name + " says:");
    animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
    console.log(animal.name + " says:");
    animal.speak();
}

The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

Another possibility is to do something like:

#ifndef _STACK_HPP
#define _STACK_HPP

template <typename Type>
class stack {
    public:
            stack();
            ~stack();
};

#include "stack.cpp"  // Note the include.  The inclusion
                      // of stack.h in stack.cpp must be 
                      // removed to avoid a circular include.

#endif

I dislike this suggestion as a matter of style, but it may suit you.

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

How to restart Activity in Android

Before SDK 11, a way to do this is like so:

public void reload() {
    Intent intent = getIntent();
    overridePendingTransition(0, 0);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    overridePendingTransition(0, 0);
    startActivity(intent);
}

Need to list all triggers in SQL Server database with table name and table's schema

The just above code is incorrect as shown:

SELECT 
    sysobjects.name AS trigger_name 
    --,USER_NAME(sysobjects.uid) AS trigger_owner 
    --,s.name AS table_schema 
    --,OBJECT_NAME(parent_obj) AS table_name 
    --,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate 
    --,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete 
    --,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert 
    --,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter 
    --,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof 
    --,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled] 
FROM sysobjects 
/*
INNER JOIN sysusers 
    ON sysobjects.uid = sysusers.uid 
*/  
INNER JOIN sys.tables t 
    ON sysobjects.parent_obj = t.object_id 

INNER JOIN sys.schemas s 
    ON t.schema_id = s.schema_id 
WHERE sysobjects.type = 'TR' 
EXCEPT
SELECT OBJECT_NAME(parent_id) as Table_Name FROM sys.triggers

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

Convert unsigned int to signed int C

The representation of the values 65529u and -7 are identical for 16-bit ints. Only the interpretation of the bits is different.

For larger ints and these values, you need to sign extend; one way is with logical operations

int y = (int )(x | 0xffff0000u); // assumes 16 to 32 extension, x is > 32767

If speed is not an issue, or divide is fast on your processor,

int y = ((int ) (x * 65536u)) / 65536;

The multiply shifts left 16 bits (again, assuming 16 to 32 extension), and the divide shifts right maintaining the sign.

How can I convert string date to NSDate?

try this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.

Swift 3 and later (Swift 4 included)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here

Where am I? - Get country

I used GEOIP db and created a function. You can consume this link directly http://jamhubsoftware.com/geoip/getcountry.php

{"country":["India"],"isoCode":["IN"],"names":[{"de":"Indien","en":"India","es":"India","fr":"Inde","ja":"\u30a4\u30f3\u30c9","pt-BR":"\u00cdndia","ru":"\u0418\u043d\u0434\u0438\u044f","zh-CN":"\u5370\u5ea6"}]}

you can download autoload.php and .mmdb file from https://dev.maxmind.com/geoip/geoip2/geolite2/

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ip_address = $_SERVER['REMOTE_ADDR'];
//$ip_address = '3.255.255.255';

require_once 'vendor/autoload.php';

use GeoIp2\Database\Reader;

// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('/var/www/html/geoip/GeoLite2-City.mmdb');

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->city($ip_address);

//print($record->country->isoCode . "\n"); // 'US'
//print($record->country->name . "\n"); // 'United States'
$rows['country'][] = $record->country->name;
$rows['isoCode'][] = $record->country->isoCode;
$rows['names'][] = $record->country->names;
print json_encode($rows);
//print($record->country->names['zh-CN'] . "\n"); // '??'
//
//print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
//print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
//
//print($record->city->name . "\n"); // 'Minneapolis'
//
//print($record->postal->code . "\n"); // '55455'
//
//print($record->location->latitude . "\n"); // 44.9733
//print($record->location->longitude . "\n"); // -93.2323
?>

Enter key press behaves like a Tab in Javascript

Try this...

$(document).ready(function () {
    $.fn.enterkeytab = function () {
        $(this).on('keydown', 'input,select,text,button', function (e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
            ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select').filter(':visible');
                next = focusable.eq(focusable.index(this) + 1);
                if (next.length) {
                    //if disable try get next 10 fields
                    if (next.is(":disabled")){
                        for(i=2;i<10;i++){
                            next = focusable.eq(focusable.index(this) + i);
                            if (!next.is(":disabled"))
                                break;
                        }
                    }
                    next.focus();
                }
                return false;
            }
        });
    }
    $("form").enterkeytab();
});

How to install latest version of git on CentOS 7.x/6.x

as git says:

RHEL and derivatives typically ship older versions of git. You can download a tarball and build from source, or use a 3rd-party repository such as the IUS Community Project to obtain a more recent version of git.

there is good tutorial here. in my case (Centos7 server) after install had to logout and login again.

PHP - Fatal error: Unsupported operand types

I guess you want to do this:

$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
   $avg = round($total_rating_points / $total_rating_count, 1);

OpenCV with Network Cameras

rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).

Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/

I did not need to compile OpenCV with ffmpg support.

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

YourModel::where(function ($query) use($a,$b) {
    $query->where('a','=',$a)
          ->orWhere('b','=', $b);
})->where(function ($query) use ($c,$d) {
    $query->where('c','=',$c)
          ->orWhere('d','=',$d);
});

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How to use this boolean in an if statement?

Actually, the entire approach would be cleaner if you only had to use one instance of StringBuffer, instead of creating one in every recursive call... I would go for:

private String getWhoozitYs(){
     StringBuffer sb = new StringBuffer();
     while (generator.nextBoolean()) {
         sb.append("y");
     }

     return sb.toString();
}

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Java - Check Not Null/Empty else assign default value

I know the question is really old, but with generics one can add a more generalized method with will work for all types.

public static <T> T getValueOrDefault(T value, T defaultValue) {
    return value == null ? defaultValue : value;
}

Changing an element's ID with jQuery

I did something similar with this construct

$('li').each(function(){
  if(this.id){
    this.id = this.id+"something";
  }
});

How do I keep two side-by-side divs the same height?

I like to use pseudo elements to achieve this. You can use it as background of the content and let them fill the space.

With these approach you can set margins between columns, borders, etc.

_x000D_
_x000D_
.wrapper{_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
}_x000D_
.wrapper:before,_x000D_
.wrapper:after{_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 100%;_x000D_
  width: 40%;_x000D_
  border: 2px solid blue;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
}_x000D_
.wrapper:before{_x000D_
  left: 0;_x000D_
  background-color: red;_x000D_
}_x000D_
.wrapper:after{_x000D_
  right: 0;_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
.div1, .div2{_x000D_
  width: 40%;_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  z-index: 1;_x000D_
}_x000D_
.div1{_x000D_
  margin-right: 20%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="div1">Content Content Content Content Content Content Content Content Content_x000D_
  </div><div class="div2">Other</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between CR LF, LF and CR line break types?

CR and LF are control characters, respectively coded 0x0D (13 decimal) and 0x0A (10 decimal).

They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix only uses LF and the old MacOS ( pre-OSX MacIntosh) used CR.

An apocryphal historical perspective:

As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn't communicate very well with one another ;-)

Most modern text editors and text-oriented applications offer options/settings etc. that allow the automatic detection of the file's end-of-line convention and to display it accordingly.

Create new user in MySQL and give it full access to one database

Try this to create the user:

CREATE USER 'user'@'hostname';

Try this to give it access to the database dbTest:

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

If you are running the code/site accessing MySQL on the same machine, hostname would be localhost.

Now, the break down.

GRANT - This is the command used to create users and grant rights to databases, tables, etc.

ALL PRIVILEGES - This tells it the user will have all standard privileges. This does not include the privilege to use the GRANT command however.

dbtest.* - This instructions MySQL to apply these rights for use in the entire dbtest database. You can replace the * with specific table names or store routines if you wish.

TO 'user'@'hostname' - 'user' is the username of the user account you are creating. Note: You must have the single quotes in there. 'hostname' tells MySQL what hosts the user can connect from. If you only want it from the same machine, use localhost

IDENTIFIED BY 'password' - As you would have guessed, this sets the password for that user.

request exceeds the configured maxQueryStringLength when using [Authorize]

In the root web.config for your project, under the system.web node:

<system.web>
    <httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
...

In addition, I had to add this under the system.webServer node or I got a security error for my long query strings:

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxUrl="10999" maxQueryString="2097151" />
      </requestFiltering>
    </security>
...

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Solution

npm cache clean --force

For Windows : go to C:\Users\username\AppData\Roaming\npm-cache
Delete all files and run

npm install && npm start

Can I install/update WordPress plugins without providing FTP access?

setting up a ftp or even an SFTP connection or chmod 777 are bad ways to go for anything other than a local environment. Opening even an SFTP method introduces more security risks that are not needed.

what is needed is a writeable permission to /wp-content/uploads & /wp-content/plugins/ by the owner of those directories. (linux ls -la will show you ownership).

Default apache user that runs is www-data.

chmod 777 allows any user on the machine to edit those file, not just the apache/php thread user.

SFTP if you are not already using it, will introduce another point of possible failure from an external source. Whereas you only need access by the local user running the apache/php process to complete the objective.

Didn't see anyone making these points, so I thought I would offer this info to help with our constant WP security issues online.

How do I force "git pull" to overwrite local files?

I summarized other answers. You can execute git pull without errors:

git fetch --all
git reset --hard origin/master
git reset --hard HEAD
git clean -f -d
git pull

Warning: This script is very powerful, so you could lose your changes.

nvarchar(max) still being truncated

Your first problem is a limitation of the PRINT statement. I'm not sure why sp_executesql is failing. It should support pretty much any length of input.

Perhaps the reason the query is malformed is something other than truncation.

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

PHP JSON String, escape Double Quotes for JS output

Another way would be to encode the quotes using htmlspecialchars:

$json_array = array(
    'title' => 'Example string\'s with "special" characters'
);

$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');

AppStore - App status is ready for sale, but not in app store

After your app status changes to 'Ready for Sale' you will get official mail from Apple. The mail itself states that it might take 24 hours before your App is available on AppStore. If it takes more than days then contact Apple.

Refer below screenshot.

Screenshot

Spring-Security-Oauth2: Full authentication is required to access this resource

The reason is that by default the /oauth/token endpoint is protected through Basic Access Authentication.

All you need to do is add the Authorization header to your request.

You can easily test it with a tool like curl by issuing the following command:

curl.exe --user [email protected]:12345678 http://localhost:8081/dummy-project-web/oauth/token?grant_type=client_credentials

How can I list the contents of a directory in Python?

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)

JQuery DatePicker ReadOnly

Readonly datepicker with example (jquery) - 
In following example you can not open calendar popup.
Check following code see normal and readonly datepicker.

Html Code- 

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang = "en">_x000D_
   <head>_x000D_
      <meta charset = "utf-8">_x000D_
      <title>jQuery UI Datepicker functionality</title>_x000D_
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"_x000D_
         rel = "stylesheet">_x000D_
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>_x000D_
_x000D_
      <!-- Javascript -->_x000D_
      <script>_x000D_
         $(function() {_x000D_
                var currentDate=new Date();_x000D_
                $( "#datepicker-12" ).datepicker({_x000D_
                  setDate:currentDate,_x000D_
                  beforeShow: function(i) { _x000D_
                      if ($(i).attr('readonly')) { return false; } _x000D_
                   }_x000D_
                });_x000D_
                $( "#datepicker-12" ).datepicker("setDate", currentDate);_x000D_
                $("#datepicker-13").datepicker();_x000D_
                $( "#datepicker-13" ).datepicker("setDate", currentDate);_x000D_
        });_x000D_
      </script>_x000D_
   </head>_x000D_
_x000D_
   <body>_x000D_
      <!-- HTML --> _x000D_
      <p>Readonly DatePicker: <input type = "text" id = "datepicker-12" readonly="readonly"></p>_x000D_
      <p>Normal DatePicker: <input type = "text" id = "datepicker-13"></p>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I run a command on an already existing Docker container?

# docker exec -d container_id command 

Ex:

# docker exec -d xcdefrdtt service jira stop 

How can I detect the encoding/codepage of a text file

The tool "uchardet" does this well using character frequency distribution models for each charset. Larger files and more "typical" files have more confidence (obviously).

On ubuntu, you just apt-get install uchardet.

On other systems, get the source, usage & docs here: https://github.com/BYVoid/uchardet

Invoke a second script with arguments from a script

Invoke-Expression should work perfectly, just make sure you are using it correctly. For your case it should look like this:

Invoke-Expression "$scriptPath $argumentList"

I tested this approach with Get-Service and seems to be working as expected.

Tomcat 7 "SEVERE: A child container failed during start"

As a generic solution, I recommend that you remove all the secondary dependencies and run the application, if it worked, revert back some, and continue doing the same as long as the application starts, in the end, you will be able to identify which dependency caused the issue.

Using the same way, for example, I found that dependencies whose the groupId is: org.apache.axis2 have caused the issue.

 <dependency>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2-transport-local</artifactId>
        <version>1.6.1</version>
 </dependency>
 <dependency>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2-transport-http</artifactId>
        <version>1.6.1</version>
 </dependency>

Is it possible to style a select box?

You can style to some degree with CSS by itself

select {
    background: red;
    border: 2px solid pink;
}

But this is entirely up to the browser. Some browsers are stubborn.

However, this will only get you so far, and it doesn't always look very good. For complete control, you'll need to replace a select via jQuery with a widget of your own that emulates the functionality of a select box. Ensure that when JS is disabled, a normal select box is in its place. This allows more users to use your form, and it helps with accessibility.

How do you use script variables in psql?

I've found this question and the answers extremely useful, but also confusing. I had lots of trouble getting quoted variables to work, so here is the way I got it working:

\set deployment_user username    -- username
\set deployment_pass '\'string_password\''
ALTER USER :deployment_user WITH PASSWORD :deployment_pass;

This way you can define the variable in one statement. When you use it, single quotes will be embedded into the variable.

NOTE! When I put a comment after the quoted variable it got sucked in as part of the variable when I tried some of the methods in other answers. That was really screwing me up for a while. With this method comments appear to be treated as you'd expect.

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);