Programs & Examples On #Memcachedb

MemcacheDB is a distributed key-value storage system designed for persistent. It uses Berkeley DB as a storing backend,so features as transaction and replication are supported.

How do I rename a column in a SQLite database table?

CASE 1 : SQLite 3.25.0+

Only the Version 3.25.0 of SQLite supports renaming columns. If your device is meeting this requirement, things are quite simple. The below query would solve your problem:

ALTER TABLE "MyTable" RENAME COLUMN "OldColumn" TO "NewColumn";

CASE 2 : SQLite Older Versions

You have to follow a different Approach to get the result which might be a little tricky

For example, if you have a table like this:

CREATE TABLE student(Name TEXT, Department TEXT, Location TEXT)

And if you wish to change the name of the column Location

Step 1: Rename the original table:

ALTER TABLE student RENAME TO student_temp;

Step 2: Now create a new table student with correct column name:

CREATE TABLE student(Name TEXT, Department TEXT, Address TEXT)

Step 3: Copy the data from the original table to the new table:

INSERT INTO student(Name, Department, Address) SELECT Name, Department, Location FROM student_temp;

Note: The above command should be all one line.

Step 4: Drop the original table:

DROP TABLE student_temp;

With these four steps you can manually change any SQLite table. Keep in mind that you will also need to recreate any indexes, viewers or triggers on the new table as well.

When to use RabbitMQ over Kafka?

Use RabbitMQ when:

  • You don’t have to handle with Bigdata and you prefer a convenient in-built UI for monitoring
  • No need of automatically replicable queues
  • No multi subscribers for the messages- Since unlike Kafka which is a log, RabbitMQ is a queue and messages are removed once consumed and acknowledgment arrived
  • If you have the requirements to use Wildcards and regex for messages
  • If defining message priority is important

In Short: RabbitMQ is good for simple use cases, with low traffic of data, with the benefit of priority queue and flexible routing options. For massive data and high throughput use Kafka.

What is the difference between print and puts?

puts adds a new line to the end of each argument if there is not one already.

print does not add a new line.


For example:

puts [[1,2,3], [4,5,nil]] Would return:

1
2
3
4
5

Whereas print [[1,2,3], [4,5,nil]] would return:

[[1,2,3], [4,5,nil]]
Notice how puts does not output the nil value whereas print does.

CentOS 7 and Puppet unable to install nc

yum install nmap-ncat.x86_64

resolved my problem

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

Validate Dynamically Added Input fields

You need to re-parse the form after adding dynamic content in order to validate the content

$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));

Parsing a JSON string in Ruby

That data looks like it is in JSON format.

You can use this JSON implementation for Ruby to extract it.

Most popular screen sizes/resolutions on Android phones

Here is a list of almost all resolutions of tablets, with the most common ones in bold :

2560X1600
1366X768

1920X1200
1280X800
1280X768
1024X800
1024X768
1024X600

960X640
960X540
854X480
800X600
800X480
800X400

Happy designing .. ! :)

Get data type of field in select statement in ORACLE

I came into the same situation. As a workaround, I just created a view (If you have privileges) and described it and dropped it later. :)

Hibernate: Automatically creating/updating the db tables based on entity classes

Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.

e.g. if you have it like:

<property name="hibernate.hbm2ddl.auto" value="create"/>

try changing it to:

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

How do I separate an integer into separate digits in an array in JavaScript?

_x000D_
_x000D_
const toIntArray = (n) => ([...n + ""].map(v => +v))
_x000D_
_x000D_
_x000D_

Change multiple files

Those commands won't work in the default sed that comes with Mac OS X.

From man 1 sed:

-i extension
             Edit files in-place, saving backups with the specified
             extension.  If a zero-length extension is given, no backup 
             will be saved.  It is not recommended to give a zero-length
             extension when in-place editing files, as you risk corruption
             or partial content in situations where disk space is exhausted, etc.

Tried

sed -i '.bak' 's/old/new/g' logfile*

and

for i in logfile*; do sed -i '.bak' 's/old/new/g' $i; done

Both work fine.

Why is SQL Server 2008 Management Studio Intellisense not working?

I understand this post is old but if anybody is still searching and has not found a solution to the intellisense issue even after re-installing, applying the cumulative updates, or other methods, then I hope I may be of assistance.

I have Applied SQL 2008 R2 Service Pack 1 which you can download here

http://www.microsoft.com/download/en/details.aspx?id=26727

32 Bit: SQLServer2008R2SP1-KB2528583-x86-ENU.exe

64 Bit: SQLServer2008R2SP1-KB2528583-x64-ENU.exe

I have applied this SP1 and now my intellisense works again. I hope this helps! (:

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...

What is the meaning of 'No bundle URL present' in react-native?

Assuming that you are using nvm and multiple versions of node installed, here is the solution:

  1. Say that you run npm install -g react-native-cli in node v6.9.5.
  2. Now make node v6.9.5 as default by running nvm alias default 6.9.5
  3. Now run react-native run-ios

The problem is, you have multiple versions of node installed via nvm and to install react-native-cli you have switched or installed latest version of node, which is not marked as default node to point in nvm yet. When you run react-native run-ios this opens up another new terminal window in which default nvm is not pointed to the node version where you have installed react-native-cli. Just follow the above setup, I hope that should help.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:

Run the following command from the ssh terminal and follow the instruction:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

Once its installed Open the Jupyter notebook and run following command:

!pip install opencv-contrib-python

Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me.

Now refresh the notebook page and check whether it's installed or not by running import cv2 in the notebook.

if statement in ng-click

Write as

<input type="submit" ng-click="profileForm.$valid==true?updateMyProfile():''" name="submit" value="Save" class="submit" id="submit">

AttributeError: 'module' object has no attribute 'urlopen'

import urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)

In Python v3 the "urllib.request" is a module by itself, therefore "urllib" cannot be used here.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

I was able to fix this issue by changing the mail settings in the system.net portion of my web.config:

<mailSettings>
    <smtp deliveryMethod="Network">
        <network host="yourserver" defaultCredentials="true"/>
    </smtp>
</mailSettings>

HTML/CSS: how to put text both right and left aligned in a paragraph

I have used this in the past:

html

January<span class="right">2014</span>

Css

.right {
    margin-left:100%;
}

Demonstration

How to set a dropdownlist item as selected in ASP.NET?

dropdownlist.ClearSelection(); //making sure the previous selection has been cleared
dropdownlist.Items.FindByValue(value).Selected = true;

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Why std::cout instead of simply cout?

In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put

using namespace std;

in your code in order to get at it.

However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.

The import org.apache.commons cannot be resolved in eclipse juno

If you got a Apache Maven project, it's easy to use this package in your project. Just specify it in your pom.xml:

<project>
...

    <properties>
        <version.commons-io>2.4</version.commons-io>
    </properties>

    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
    </dependencies>

...
</project>

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

receiving json and deserializing as List of object at spring mvc controller

For me below code worked, first sending json string with proper headers

$.ajax({
        type: "POST",
        url : 'save',
        data : JSON.stringify(valObject),
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success : function(resp){
            console.log(resp);
        },
        error : function(resp){
            console.log(resp);
        }
    });

And then on Spring side -

@RequestMapping(value = "/save", 
                method = RequestMethod.POST,
                consumes="application/json")
public @ResponseBody String  save(@RequestBody ArrayList<KeyValue> keyValList) {
    //Saving call goes here
    return "";
}

Here KeyValue is simple pojo that corresponds to your JSON structure also you can add produces as you wish, I am simply returning string.

My json object is like this -

[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
 {"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]

MySQL Database won't start in XAMPP Manager-osx

Just Click on Managed Servers Tab in XAMPP MANAGER , Now select MySQL Database, Click on configure on right side.

Change port from 3306 to 3307 and it will work.

What's the best way to loop through a set of elements in JavaScript?

Note that in some cases, you need to loop in reverse order (but then you can use i-- too).

For example somebody wanted to use the new getElementsByClassName function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).
That's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.

var menus = document.getElementsByClassName("style2");
for (var i = menus.length - 1; i >= 0; i--)
{
  menus[i].className = "style1";
}

In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!

jQuery Ajax requests are getting cancelled without being sent

Two possibilities are there when AJAX request gets dropped (if not Cross-Origin request):

  1. You are not preventing the element's default behavior for the event.
  2. You set timeout of AJAX too low, or network/application backend server is slow.

Solution for 1): Add return false; or e.preventDefault(); in the event handler.

Solution for 2): Add timeout option while forming the AJAX request. Example below.

$.ajax({
    type: 'POST',
    url: url,
    timeout: 86400,
    data: data,
    success: success,
    dataType: dataType
});

For Cross-origin requests, check Cross-Origin Resource Sharing (CORS) HTTP headers.

Making button go full-width?

Why not use the Bootstrap predefined class input-block-level that does the job?

<a href="#" class="btn input-block-level">Full-Width Button</a> <!-- BS2 -->
<a href="#" class="btn form-control">Full-Width Button</a> <!-- BS3 -->

<!-- And let's join both for BS# :) -->
<a href="#" class="btn input-block-level form-control">Full-Width Button</a>

Learn more here in the Control Sizing^ section.

How do I get the path of the Python script I am running in?

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

keycode and charcode

Handling key events consistently is not at all easy.

Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress event. Do not try to get character codes for keyup and keydown events.

Secondly, you get different sets of values in a keypress event to what you get in a keyup or keydown event.

I recommend this page as a useful resource. As a summary:

If you're interested in detecting a user typing a character, use the keypress event. IE bizarrely only stores the character code in keyCode while all other browsers store it in which. Some (but not all) browsers also store it in charCode and/or keyCode. An example keypress handler:

function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
}

If you're interested in detecting a non-printable key (such as a cursor key), use the keydown event. Here keyCode is always the property to use. Note that keyup events have the same properties.

function(evt) {
  evt = evt || window.event;
  var keyCode = evt.keyCode;

  // Check for left arrow key
  if (keyCode == 37) {
    alert("Left arrow");
  }
}

What are App Domains in Facebook Apps?

It's simply the domain that your "facebook" application (wich means application visible on facebook but hosted on the website www.xyz.com) will be hosted. So you can put App Domain = www.xyz.com

git is not installed or not in the PATH

Install git and tortoise git for windows and make sure it is on your path, (the installer for Tortoise Git includes options for the command line tools and ensuring that it is on the path - select them).

You will need to close and re-open any existing command line sessions for the changes to take effect.

Then you should be able to run npm install successfully or move on to the next problem!

how to make label visible/invisible?

you could try

if (isValid) {
    document.getElementById("endTimeLabel").style.display = "none";
}else {
    document.getElementById("endTimeLabel").style.display = "block";
}

alone those lines

Tomcat base URL redirection

Name your webapp WAR “ROOT.war” or containing folder “ROOT”

Convert timestamp to date in MySQL query

you can try this
The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’

$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
   echo $row['date'] . "
";
}

The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.

Here are some other sample date output formats that may be of practical use:

echo date("F j, Y g:i a", strtotime($row["date"]));                  // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"]));                         // 10.05.08
echo date("j, n, Y", strtotime($row["date"]));                       // 5, 10, 2008
echo date("Ymd", strtotime($row["date"]));                           // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"]));   // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"]));               // Sun Oct 5 21:34:02 PST 2008

CSS: background image on background color

This actually works for me:

background-color: #6DB3F2;
background-image: url('images/checked.png');

You can also drop a solid shadow and set the background image:

background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;

If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:

.btn{
    position: relative;
    background-color: #6DB3F2;
}
.btn:before{
    content: "";
    display: block;
    width: 100%;
    height: 100%;
    position:absolute;
    top:0;
    left:0;
    background-image: url('images/checked.png');
}

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);

$timelines = $connection->get('statuses/user_timeline', array('screen_name' => 'NSE_NIFTY', 'count' => 100, 'include_rts' => 1));

Simple (non-secure) hash function for JavaScript?

There are many realizations of hash functions written in JS. For example:

If you don't need security, you can also use base64 which is not hash-function, has not fixed output and could be simply decoded by user, but looks more lightweight and could be used for hide values: http://www.webtoolkit.info/javascript-base64.html

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

javac : command not found

You have installed the Java Runtime Environment(JRE) but it doesn't contain javac.

So on the terminal get access to the root user sudo -i and enter the password. Type yum install java-devel, hence it will install packages of javac in fedora.

How do you perform a left outer join using linq extension methods

Group Join method is unnecessary to achieve joining of two data sets.

Inner Join:

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

For Left Join just add DefaultIfEmpty()

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.

Personlay for me this way is more readable compared to GroupJoin().SelectMany()

How to block users from closing a window in Javascript?

What will you do when a user hits ALT + F4 or closes it from Task Manager

Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."

Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)

How to close form

Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:

private void button1_Click(object sender, EventArgs e)
{
    Settings newSettingsWindow = new Settings();

    if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
    {
        newSettingsWindow.Close();
    }
}

Oracle - How to create a readonly user

It is not strictly possible in default db due to the many public executes that each user gains automatically through public.

Showing empty view when ListView is empty

As appsthatmatter says, in the layout something like:

<ListView android:id="@+id/listView" ... />
<TextView android:id="@+id/emptyElement" ... />

and in the linked Activity:

this.listView = (ListView) findViewById(R.id.listView);
this.listView.setEmptyView(findViewById(R.id.emptyElement));

Does also work with a GridView...

HTML - Change\Update page contents without refreshing\reloading the page

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

How to compare two dates in php

Try this

$data1 = strtotime(\date("d/m/Y"));
$data1 = date_create($data1);
$data2 = date_create("21/06/2017");

if($data1 < $data2){
    return "The most current date is date1";
}

return "The most current date is date2";

C library function to perform sort

C/C++ standard library <stdlib.h> contains qsort function.

This is not the best quick sort implementation in the world but it fast enough and VERY EASY to be used... the formal syntax of qsort is:

qsort(<arrayname>,<size>,sizeof(<elementsize>),compare_function);

The only thing that you need to implement is the compare_function, which takes in two arguments of type "const void", which can be cast to appropriate data structure, and then return one of these three values:

  • negative, if a should be before b
  • 0, if a equal to b
  • positive, if a should be after b

1. Comparing a list of integers:

simply cast a and b to integers if x < y,x-y is negative, x == y, x-y = 0, x > y, x-y is positive x-y is a shortcut way to do it :) reverse *x - *y to *y - *x for sorting in decreasing/reverse order

int compare_function(const void *a,const void *b) {
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;
}

2. Comparing a list of strings:

For comparing string, you need strcmp function inside <string.h> lib. strcmp will by default return -ve,0,ve appropriately... to sort in reverse order, just reverse the sign returned by strcmp

#include <string.h>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}

3. Comparing floating point numbers:

int compare_function(const void *a,const void *b) {
double *x = (double *) a;
double *y = (double *) b;
// return *x - *y; // this is WRONG...
if (*x < *y) return -1;
else if (*x > *y) return 1; return 0;
}

4. Comparing records based on a key:

Sometimes you need to sort a more complex stuffs, such as record. Here is the simplest way to do it using qsort library.

typedef struct {
int key;
double value;
} the_record;

int compare_function(const void *a,const void *b) {
the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;
}

check if command was successful in a batch file

This likely doesn't work with start, as that starts a new window, but to answer your question:

If the command returns a error level you can check the following ways

By Specific Error Level

commandhere
if %errorlevel%==131 echo do something

By If Any Error

commandhere || echo what to do if error level ISN'T 0

By If No Error

commandhere && echo what to do if error level IS 0

If it does not return a error level but does give output, you can catch it in a variable and determine by the output, example (note the tokens and delims are just examples and would likely fail with any special characters)

By Parsing Full Output

for /f "tokens=* delims=" %%a in ('somecommand') do set output=%%a
if %output%==whateveritwouldsayinerror echo error

Or you could just look for a single phrase in the output like the word Error

By Checking For String

commandhere | find "Error" || echo There was no error!
commandhere | find "Error" && echo There was an error!

And you could even mix together (just remember to escape | with ^| if in a for statement)

Hope this helps.

Using "&times" word in html changes to ×

You need to escape the ampersand:

<div class="test">&amp;times</div>

&times means a multiplication sign. (Technically it should be &times; but lenient browsers let you omit the ;.)

Python: Converting string into decimal number

A2 = [float(x.strip('"')) for x in A1] works, @Jake , but there are unnecessary 0s

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I make a Mac Terminal pop-up/alert? Applescript?

Use osascript. For example:

osascript -e 'tell app "Finder" to display dialog "Hello World"' 

Replacing “Finder” with whatever app you desire. Note if that app is backgrounded, the dialog will appear in the background too. To always show in the foreground, use “System Events” as the app:

osascript -e 'tell app "System Events" to display dialog "Hello World"'

Read more on Mac OS X Hints.

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

New line character in VB.Net?

you can solve that problem in visual basic .net without concatenating your text, you can use this as a return type of your overloaded Tostring:

System.Text.RegularExpressions.Regex.Unescape(String.format("FirstName:{0} \r\n LastName: {1}", "Nordanne", "Isahac"))

Maven: Command to update repository after adding dependency to POM

Right, click on the project. Go to Maven -> Update Project.

The dependencies will automatically be installed.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:

.navbar-brand {
    min-height: 80px;
}

@media (min-width: 768px) {
    #navbar-collapse {
        position: absolute;
        bottom: 0px;
        left: 250px;
    }
}

My brand image is SVG and I used height: 50px; width: auto which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px; to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse's left setting until it looked right.

How to load external webpage in WebView

Add Internet permission in AndroidManifest.xml

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

In your Layout:

<?xml version="1.0" encoding="utf-8"?>
<WebView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"
 />

In your Activity

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

    try {
        progressDialog = new ProgressDialog(this);
        url_Api = "https://docs.microsoft.com/en-us/learn";

        webView = this.findViewById(R.id.webView);

            progressDialog.setMessage(getString(R.string.connection_Wait));
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.show();

            LoadUrlWebView( url_Api );
    }catch (Exception e){
        Log.w(TAG, "onCreate", e);
    }
}

private void LoadUrlWebView( String url_api ) {
    try {
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient( url_api ));
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);

        webView.loadUrl(url_api);
    } catch (Exception e) {
        Log.w(TAG, "setUpNavigationView", e);
    }
}

private class MyWebChromeClient extends WebChromeClient {
    private String urlAccount;

    public MyWebChromeClient( String urlAccount ) {
        this.urlAccount = urlAccount;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        try {
            //Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress);
            progressDialog.setMessage(newProgress + "% " + getString(R.string.connection_Wait));
            if (newProgress < 100 && !progressDialog.isShowing()) {
                if (progressDialog != null)
                    progressDialog.show();
            }
            if (newProgress == 100) {
                if (progressDialog != null)
                    progressDialog.dismiss();
            }
        }catch (Exception e){
            Log.w( "onProgressChanged", e);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);

        sharedPreferences = new Shared_Preferences( context );
        sharedPreferences.setPageWebView(view.getUrl());
    }

}

Box-Shadow on the left side of the element only

box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);

The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.

The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.

reference: CSS Box Shadow Property

Convert string into Date type on Python

Use datetime.datetime.strptime:

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5

JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);
        }
    });

    mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In Visual Studio 2013,

1) Check in the Project Property Pages / Configuration Properties / Linker / All Options and correct all the miss configured machine and directories.

2) Check in the Project Property Pages / Configuration Properties / Linker / Input and correct all the miss configured directories.

See example of 1)

Getting the Facebook like/share count for a given URL

use below URL and replace myurl with your post url and you will get all the things

http://api.facebook.com/restserver.php?method=links.getStats&urls=myurl

but keep in mind it will give you response in XML format only

Example :

<share_count>1</share_count>
<like_count>8</like_count>
<comment_count>0</comment_count>
<total_count>9</total_count>
<click_count>0</click_count>
<comments_fbid>**************</comments_fbid>
<commentsbox_count>0</commentsbox_count>

Convert an integer to an array of digits

You don't have to use substring(...). Use temp.charAt(i) to get a digit and use the following code to convert char to int.

char c = '7';
int i = c - '0';
System.out.println(i);

SQL: How do I SELECT only the rows with a unique value on certain column?

Try this:

select 
         contract,
        max (activity) 
from
         mytable 
group by
         contract 
having
         count (activity) = 1

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

how to configuring a xampp web server for different root directory

You can change the port while you open your XAMP control panel, follow the steps:

  1. click on config net to the start button, and
  2. select httpd.conf, a text file will open
  3. check the file and file listen:80,
  4. once got listen:80 replace with listen:8080 and
  5. save in the same folder.

Once done that, you will be able to start your local server.

List all sequences in a Postgres db 8.1 with SQL

Kind of a hack, but try this:

select 'select ''' || relname || ''' as sequence, last_value from ' || relname || ' union' FROM pg_catalog.pg_class c WHERE c.relkind IN ('S','');

Remove the last UNION and execute the result

How to send a POST request from node.js Express?

As described here for a post request :

var http = require('http');

var options = {
  host: 'www.host.com',
  path: '/',
  port: '80',
  method: 'POST'
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

What's the safest way to iterate through the keys of a Perl hash?

The rule of thumb is to use the function most suited to your needs.

If you just want the keys and do not plan to ever read any of the values, use keys():

foreach my $key (keys %hash) { ... }

If you just want the values, use values():

foreach my $val (values %hash) { ... }

If you need the keys and the values, use each():

keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }

If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():

%h = (a => 1, b => 2);

foreach my $k (keys %h)
{
  $h{uc $k} = $h{$k} * 2;
}

producing the expected resulting hash:

(a => 1, A => 2, b => 2, B => 4)

But using each() to do the same thing:

%h = (a => 1, b => 2);

keys %h;
while(my($k, $v) = each %h)
{
  $h{uc $k} = $h{$k} * 2; # BAD IDEA!
}

produces incorrect results in hard-to-predict ways. For example:

(a => 1, A => 2, b => 2, B => 8)

This, however, is safe:

keys %h;
while(my($k, $v) = each %h)
{
  if(...)
  {
    delete $h{$k}; # This is safe
  }
}

All of this is described in the perl documentation:

% perldoc -f keys
% perldoc -f each

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

How can I switch my git repository to a particular commit

If you want to throw the latest four commits away, use:

git reset --hard HEAD^^^^

Alternatively, you can specify the hash of a commit you want to reset to:

git reset --hard 6e559cb

How to hide a status bar in iOS?

-(void) viewWillAppear:(BOOL)animated
{
     [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

Is there a way to use SVG as content in a pseudo element :before or :after

.myDiv {
  display: flex;
  align-items: center;
}

.myDiv:before {
  display: inline-block;
  content: url(./dog.svg);
  margin-right: 15px;
  width: 10px;
}

HttpServletRequest to complete URL

HttpUtil being deprecated, this is the correct method

StringBuffer url = req.getRequestURL();
String queryString = req.getQueryString();
if (queryString != null) {
    url.append('?');
    url.append(queryString);
}
String requestURL = url.toString();

Why doesn't RecyclerView have onItemClickListener()?

See my approach on this:

First declare an interface like this:

/**
 * Interface used for delegating item click events in a {@link android.support.v7.widget.RecyclerView}
 * Created by Alex on 11/28/2015.
 */
  public interface OnRecyclerItemClickListener<T> {

     /**
      * Called when a click occurred inside a recyclerView item view
      * @param view that was clicked
      * @param position of the clicked view
      * @param item the concrete data that is displayed through the clicked view
      */
      void onItemClick(View view, int position, T item);
   }

Then create the adapter:

public class CustomRecyclerAdapter extends RecyclerView.Adapter {      

    private class InternalClickListener implements View.OnClickListener{

      @Override
      public void onClick(View v) {
        if(mRecyclerView != null && mItemClickListener != null){
            // find the position of the item that was clicked
            int position = mRecyclerView.getChildAdapterPosition(v);
            Data data = getItem(position);
            // notify the main listener
            mItemClickListener.onItemClick(v, position, data);
        }
    }
}

private final OnRecyclerItemClickListener mItemClickListener;
private RecyclerView mRecyclerView;    
private InternalClickListener mInternalClickListener;


/**
 *
 * @param itemClickListener used to trigger an item click event
 */
public PlayerListRecyclerAdapter(OnRecyclerItemClickListener itemClickListener){        
    mItemClickListener = itemClickListener;
    mInternalClickListener = new InternalClickListener();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
   View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);

    v.setOnClickListener(mInternalClickListener);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    // do your binding here
}

@Override
public int getItemCount() {
    return mDataSet.size();
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);

    mRecyclerView = recyclerView;
}

@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
    super.onDetachedFromRecyclerView(recyclerView);

    mRecyclerView = null;
}

public Data getItem(int position){
    return mDataset.get(position);
}
}

And now let's see how to integrate this from a fragment:

public class TestFragment extends Fragment implements OnRecyclerItemClickListener<Data>{
   private RecyclerView mRecyclerView;

   @Override
   public void onItemClick(View view, int position, Data item) {
     // do something
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      return inflater.inflate(R.layout.test_fragment, container, false);
   }

   @Override
   public void onViewCreated(View view, Bundle savedInstanceState) {
      mRecyclerView = view.findViewById(idOfTheRecycler);
      mRecyclerView .setAdapter(new CustomRecyclerAdapter(this));
   }

Do we have router.reload in vue-router?

The simplest solution is to add a :key attribute to :

<router-view :key="$route.fullPath"></router-view>

This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.

Can I get div's background-image url?

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

A Simple AJAX with JSP example

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error

How to place the ~/.composer/vendor/bin directory in your PATH?

my path didn't have /.composer, just /composer so my path was:-

export PATH="$PATH:$HOME/.config/composer/vendor/bin"

This worked for me on ubuntu 20.04

How can I use Bash syntax in Makefile targets?

You can call bash directly, use the -c flag:

bash -c "diff <(sort file1) <(sort file2) > $@"

Of course, you may not be able to redirect to the variable $@, but when I tried to do this, I got -bash: $@: ambiguous redirect as an error message, so you may want to look into that before you get too into this (though I'm using bash 3.2.something, so maybe yours works differently).

JavaScript open in a new window, not tab

I just tried this with IE (11) and Chrome (54.0.2794.1 canary SyzyASan):

window.open(url, "_blank", "x=y")

... and it opened in a new window.

Which means that Clint pachl had it right when he said that providing any one parameter will cause the new window to open.

-- and apparently it doesn't have to be a legitimate parameter!

(YMMV - as I said, I only tested it in two places...and the next upgrade might invalidate the results, any way)

ETA: I just noticed, though - in IE, the window has no decorations.

UICollectionView current visible cell index

For Swift 3.0

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: colView.contentOffset, size: colView.bounds.size)
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
    let indexPath = colView.indexPathForItem(at: visiblePoint)
}

CSS3 equivalent to jQuery slideUp and slideDown?

    try this for slide up slide down with animation 
give your **height

        @keyframes slide_up{
            from{
                min-height: 0;
                height: 0px;
                opacity: 0;
            }
            to{
                height: 560px;
                opacity: 1;
            }
        }

        @keyframes slide_down{
            from{
                height: 560px;
                opacity: 1;
            }
            to{
                min-height: 0;
                height: 0px;
                opacity: 0;
            } 
        }

OSX -bash: composer: command not found

If you have to run composer with sudo, you should change the directory of composer to

/usr/bin

this was tested on Centos8.

How do you use the ? : (conditional) operator in JavaScript?

x = 9
y = 8

unary

++x
--x

Binary

z = x + y

Ternary

2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";

The Eclipse executable launcher was unable to locate its companion launcher jar windows

Solution for Mac

Reason: Eclipse is copied from one location to another.

Solution: Need to update path(s) in eclipse.ini. My eclipse.ini was found in /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse.ini.

We need to update the path for plugins\org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar.

How do I install a NuGet package .nupkg file locally?

If you have a .nupkg file and just need the .dll file all you have to do is change the extension to .zip and find the lib directory.

How to parse date string to Date?

Here is a working example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result); 
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}

Will print:

Thu Sep 28 13:29:30 CEST 2000

How to get char from string by index?

This should further clarify the points:

a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
    print str1[a]
else:
    print('Index overflow')

Input 3 Output m

Input -3 Output p

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How to convert a structure to a byte array in C#?

You can use Marshal (StructureToPtr, ptrToStructure), and Marshal.copy but this is plataform dependent.


Serialization includes Functions to Custom Serialization.

public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) 

SerializationInfo include functions to serialize each member.


BinaryWriter and BinaryReader also contains methods to Save / Load to Byte Array (Stream).

Note that you can create a MemoryStream from a Byte Array or a Byte Array from a MemoryStream.

You can create a method Save and a method New on your structure:

   Save(Bw as BinaryWriter)
   New (Br as BinaryReader)

Then you select members to Save / Load to Stream -> Byte Array.

How to auto import the necessary classes in Android Studio with shortcut?

To import classes on the fly :

On OSX press Alt(Option) + Enter.

Android - Back button in the title bar

After a quality time I have found, theme option is the main problem in my code And following is the proper way to show the toolbar for me

In AndroidManifest file first you have to change your theme style

Theme.AppCompat.Light.DarkActionBar
to 
Theme.AppCompat.Light.NoActionBar

then at your activity xml you need to call your own Toolbar like

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:elevation="4dp"/>

And then this toolbar should be called in your Java file by

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

And for toolbar showing U should check the null to avoid NullPointerException

if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

For Home activity back add this

@Override
public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==android.R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

OR for your desired activity back

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

Operator overloading ==, !=, Equals

I think you declared the Equals method like this:

public override bool Equals(BOX obj)

Since the object.Equals method takes an object, there is no method to override with this signature. You have to override it like this:

public override bool Equals(object obj)

If you want type-safe Equals, you can implement IEquatable<BOX>.

Is there a simple way to remove unused dependencies from a maven pom.xml?

You can use dependency:analyze -DignoreNonCompile

This will print a list of used undeclared and unused declared dependencies (while ignoring runtime/provided/test/system scopes for unused dependency analysis.)

** Be careful while using this, some libraries used at runtime are considered as unused **

For more details refer this link

Should I use 'has_key()' or 'in' on Python dicts?

has_key is a dictionary method, but in will work on any collection, and even when __contains__ is missing, in will use any other method to iterate the collection to find out.

Check if a variable is of function type

I think you can just define a flag on the Function prototype and check if the instance you want to test inherited that

define a flag:

Function.prototype.isFunction = true; 

and then check if it exist

var foo = function(){};
foo.isFunction; // will return true

The downside is that another prototype can define the same flag and then it's worthless, but if you have full control over the included modules it is the easiest way

Serializing a list to JSON

There are two common ways of doing that with built-in JSON serializers:

  1. JavaScriptSerializer

    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(TheList);
    
  2. DataContractJsonSerializer

    var serializer = new DataContractJsonSerializer(TheList.GetType());
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, TheList);
        using (var sr = new StreamReader(stream))
        {
            return sr.ReadToEnd();
        }
    }
    

    Note, that this option requires definition of a data contract for your class:

    [DataContract]
    public class MyObjectInJson
    {
       [DataMember]
       public long ObjectID {get;set;}
       [DataMember]
       public string ObjectInJson {get;set;}
    }
    

Namespace for [DataContract]

First, I add the references to my Model, then I use them in my code. There are two references you should add:

using System.ServiceModel;
using System.Runtime.Serialization;

then, this problem was solved in my program. I hope this answer can help you. Thanks.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

I think you can use CHECK constraint - it is exactly what it was invented for.

ALTER TABLE someTable 
ADD CONSTRAINT someField_check CHECK (ISNUMERIC(someField) = 1) ;

My previous answer (also right by may be a bit overkill):

I think the right way is to use INSTEAD OF trigger to prevent the wrong data from being inserted (rather than deleting it post-factum)

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

Lists: Count vs Count()

myList.Count is a method on the list object, it just returns the value of a field so is very fast. As it is a small method it is very likely to be inlined by the compiler (or runtime), they may then allow other optimization to be done by the compiler.

myList.Count() is calling an extension method (introduced by LINQ) that loops over all the items in an IEnumerable, so should be a lot slower.

However (In the Microsoft implementation) the Count extension method has a “special case” for Lists that allows it to use the list’s Count property, this means the Count() method is only a little slower than the Count property.

It is unlikely you will be able to tell the difference in speed in most applications.

So if you know you are dealing with a List use the Count property, otherwise if you have a "unknown" IEnumerabl, use the Count() method and let it optimise for you.

How is length implemented in Java Arrays?

Every array in java is considered as an object. The public final length is the data member which contains the number of components of the array (length may be positive or zero)

Get everything after and before certain character in SQL Server

 declare @T table
  (
  Col varchar(20)
  )



  insert into @T 
  Select 'images/test1.jpg'
  union all
  Select 'images/test2.png'
  union all
  Select 'images/test3.jpg'
  union all
  Select 'images/test4.jpeg'
  union all
  Select 'images/test5.jpeg'

 Select substring( LEFT(Col,charindex('.',Col)-1),charindex('/',Col)+1,len(LEFT(Col,charindex('.',Col)-1))-1 )
from @T

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

How to create a GUID / UUID

Don't use Math.random in anycase since it generated a non-cryptographic source of random numbers

Solution below using crypto.getRandomValues

function uuidv4() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    // tslint:disable-next-line: no-bitwise
    const r =
      (window.crypto.getRandomValues(new Uint32Array(1))[0] *
        Math.pow(2, -32) * 16) |
      0;
    // tslint:disable-next-line: no-bitwise
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

This link helps your to understand the Insecure Randomness thrown by Fortify Scanner

Align a div to center

floating divs to center "works" with the combination of display:inline-block and text-align:center.

Try changing width of the outer div by resizing the window of this jsfiddle

<div class="outer">
    <div class="block">one</div>
    <div class="block">two</div>
    <div class="block">three</div>
    <div class="block">four</div>
    <div class="block">five</div>
</div>

and the css:

.outer {
    text-align:center;
    width: 50%;
    background-color:lightgray;
}

.block {
    width: 50px;
    height: 50px;
    border: 1px solid lime;
    display: inline-block;
    margin: .2rem;
    background-color: white;
}

Node.js Logging

A 'nodejslogger' module can be used for simple logging. It has three levels of logging (INFO, ERROR, DEBUG)

var logger = require('nodejslogger')
logger.init({"file":"output-file", "mode":"DIE"})

D : Debug, I : Info, E : Error

logger.debug("Debug logs")
logger.info("Info logs")
logger.error("Error logs")

The module can be accessed at : https://www.npmjs.com/package/nodejslogger

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

How to pass a datetime parameter?

The problem is twofold:

1. The . in the route

By default, IIS treats all URI's with a dot in them as static resource, tries to return it and skip further processing (by Web API) altogether. This is configured in your Web.config in the section system.webServer.handlers: the default handler handles path="*.". You won't find much documentation regarding the strange syntax in this path attribute (regex would have made more sense), but what this apparently means is "anything that doesn't contain a dot" (and any character from point 2 below). Hence the 'Extensionless' in the name ExtensionlessUrlHandler-Integrated-4.0.

Multiple solutions are possible, in my opinion in the order of 'correctness':

  • Add a new handler specifically for the routes that must allow a dot. Be sure to add it before the default. To do this, make sure you remove the default handler first, and add it back after yours.
  • Change the path="*." attribute to path="*". It will then catch everything. Note that from then on, your web api will no longer interpret incoming calls with dots as static resources! If you are hosting static resources on your web api, this is therefor not advised!
  • Add the following to your Web.config to unconditionally handle all requests: under <system.webserver>: <modules runAllManagedModulesForAllRequests="true">

2. The : in the route

After you've changed the above, by default, you'd get the following error:

A potentially dangerous Request.Path value was detected from the client (:).

You can change the predefined disallowed/invalid characters in your Web.config. Under <system.web>, add the following: <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,*,\,?" />. I've removed the : from the standard list of invalid characters.

Easier/safer solutions

Although not an answer to your question, a safer and easier solution would be to change the request so that all this is not required. This can be done in two ways:

  1. Pass the date as a query string parameter, like ?date=2012-12-31T22:00:00.000Z.
  2. Strip the .000 from every request. You'd still need to allow :'s (cfr point 2).

What are the recommendations for html <base> tag?

It's probably not very popular because it's not well known. I wouldn't be afraid of using it since all major browsers support it.

If your site uses AJAX you'll want to make sure all of your pages have it set correctly or you could end up with links that cannot be resolved.

Just don't use the target attribute in an HTML 4.01 Strict page.

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

What is “assert” in JavaScript?

Previous answers can be improved in terms of performances and compatibility.

Check once if the Error object exists, if not declare it :

if (typeof Error === "undefined") {
    Error = function(message) {
        this.message = message;
    };
    Error.prototype.message = "";
}

Then, each assertion will check the condition, and always throw an Error object

function assert(condition, message) {
    if (!condition) throw new Error(message || "Assertion failed");
}

Keep in mind that the console will not display the real error line number, but the line of the assert function, which is not useful for debugging.

data.frame Group By column

require(reshape2)

T <- melt(df, id = c("A"))

T <- dcast(T, A ~ variable, sum)

I am not certain the exact advantages over aggregate.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

I found the solution to my problem. It was indeed because my MySQL server was not running.

It was caused by MySQL not being correctly set up on my machine, thus not being able to run.

To remedy this, I used a script which installs MySQL on Mac OSX Mountain Lion, which must have installed missing files.

Here is the link: http://code.macminivault.com/

Important Note: This script sets the root password as a randomly generated string, which it saves on the Desktop, so take care not to delete this file and to note the password. It also installs MySQL manager in your system preferences. I'm also not sure if removes any existing databases, so be careful about that.

How do I create a singleton service in Angular 2?

From Angular@6, you can have providedIn in an Injectable.

@Injectable({
  providedIn: 'root'
})
export class UserService {

}

Check the docs here

There are two ways to make a service a singleton in Angular:

  1. Declare that the service should be provided in the application root.
  2. Include the service in the AppModule or in a module that is only imported by the AppModule.

Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:

Print PHP Call Stack

Use debug_backtrace to get a backtrace of what functions and methods had been called and what files had been included that led to the point where debug_backtrace has been called.

Signed to unsigned conversion in C - is it always safe?

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

So it is safe in the sense of that the result might be huge and wrong, but it will never crash.

How to see local history changes in Visual Studio Code?

I think there is no out-of-the-box support for that in VS Code.

You can install a plugin to give you similar functionality. Eg.:

https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints

Or the more famous:

https://marketplace.visualstudio.com/items?itemName=xyz.local-history

Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore file also solves this problem).

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

Change SQLite database mode to read-write

To share personal experience I encountered with this error that eventually fix both. Might not necessarily be related to your issue but it appears this error is so generic that it can be attributed to gazillion things.

  1. Database instance open in another application. My DB appeared to have been in a "locked" state so it transition to read only mode. I was able to track it down by stopping the a 2nd instance of the application sharing the DB.

  2. Directory tree permission - please be sure to ensure user account has permission not just at the file level but at the entire upper directory level all the way to / level.

Thanks

Remove all special characters, punctuation and spaces from string

Python 2.*

I think just filter(str.isalnum, string) works

In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'

Python 3.*

In Python3, filter( ) function would return an itertable object (instead of string unlike in above). One has to join back to get a string from itertable:

''.join(filter(str.isalnum, string)) 

or to pass list in join use (not sure but can be fast a bit)

''.join([*filter(str.isalnum, string)])

note: unpacking in [*args] valid from Python >= 3.5

Casting string to enum

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

What is the use of join() in Python threading?

With join - interpreter will wait until your process get completed or terminated

>>> from threading import Thread
>>> import time
>>> def sam():
...   print 'started'
...   time.sleep(10)
...   print 'waiting for 10sec'
... 
>>> t = Thread(target=sam)
>>> t.start()
started

>>> t.join() # with join interpreter will wait until your process get completed or terminated
done?   # this line printed after thread execution stopped i.e after 10sec
waiting for 10sec
>>> done?

without join - interpreter wont wait until process get terminated,

>>> t = Thread(target=sam)
>>> t.start()
started
>>> print 'yes done' #without join interpreter wont wait until process get terminated
yes done
>>> waiting for 10sec

load scripts asynchronously

Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.

Select arrow style change

This would work well especially for those using Bootstrap, tested in latest browser versions:

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  /* Some browsers will not display the caret when using calc, so we put the fallback first */ _x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */_x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */_x000D_
}_x000D_
/*For IE*/_x000D_
select::-ms-expand { display: none; }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-6">_x000D_
      <select class="form-control">_x000D_
       <option>Option 1</option>_x000D_
       <option>Option 2</option>_x000D_
       <option>Option 3</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Delete statement in SQL is very slow

open CMD and run this commands

NET STOP MSSQLSERVER
NET START MSSQLSERVER

this will restart the SQL Server instance. try to run again after your delete command

I have this command in a batch script and run it from time to time if I'm encountering problems like this. A normal PC restart will not be the same so restarting the instance is the most effective way if you are encountering some issues with your sql server.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

How to programmatically set the Image source

Use asp:image

<asp:Image id="Image1" runat="server"
           AlternateText="Image text"
           ImageAlign="left"
           ImageUrl="images/image1.jpg"/>

and codebehind to change image url

Image1.ImageUrl = "/MyProject;component/Images/down.png"; 

How to use Class<T> in Java?

As other answers point out, there are many and good reasons why this class was made generic. However there are plenty of times that you don't have any way of knowing the generic type to use with Class<T>. In these cases, you can simply ignore the yellow eclipse warnings or you can use Class<?> ... That's how I do it ;)

Remove directory from remote repository after adding them to .gitignore

Note: This solution works only with Github Desktop GUI.

By using Github Desktop GUI it is very simple.

  1. Move the folder onto another location (to out of the project folder) temporarily.

  2. Edit your .gitignore file and remove the folder entry which would be remove master repository on the github page.

  3. Commit and Sync the project folder.

  4. Re-move the folder into the project folder

  5. Re-edit .gitignore file.

That's all.

iPhone app could not be installed at this time

Most common issues that cause this are (from testflight's website):

  • Device storage is full
  • The provisioning profile is a developer provisioning profile
  • The ad hoc distribution provisioning profile is corrupted and the device is having an issue with it.
  • The device was restored from a backup and is causing a conflict for over-the-air distribution
  • There was a network timeout
  • Architecture settings of the build and the device are incompatible ( can sometimes happen -when "Build Active Architecture Only" is on when building).
  • Not Using Mobile Safari.

for me it turned out that my client's ipad was running iOS 4.2.2 and my project supports 5.0+.

Get resultset from oracle stored procedure

Oracle is not sql server. Try the following in SQL Developer

variable rc refcursor;
exec testproc(:rc2);
print rc2

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

Ok, this could be pretty useless and simply anecdotal, but...

This exception was thrown consistently by some Twain32 libraries we were using in my project, but would only happen in my machine.

I tried lots of suggested solutions all over the internet, to no avail... Until I unplugged my cellphone (it was connected through the USB).

And it worked.

Turns out the Twain32 libraries were trying to list my phone as a Twain compatible device, and something it did in that process caused that exception.

Go figure...

Two divs side by side - Fluid display

Using this CSS for my current site. It works perfect!

#sides{
margin:0;
}
#left{
float:left;
width:75%;
overflow:hidden;
}
#right{
float:left;
width:25%;
overflow:hidden;
} 

How to increase code font size in IntelliJ?

It is possible to change font size etc when creating custom Scheme using Save As... button:

Save As...

How to avoid Number Format Exception in java?

In Java there's sadly no way you can avoid using the parseInt function and just catching the exception. Well you could theoretically write your own parser that checks if it's a number, but then you don't need parseInt at all anymore.

The regex method is problematic because nothing stops somebody from including a number > INTEGER.MAX_VALUE which will pass the regex test but still fail.

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

Android Studio - Failed to notify project evaluation listener error

I got this problem too. I fix it by Change build.gradle in project

Change

dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
}

And also I change the distributionUrl in gradle-wrapper.properties(Global Version)

distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip

And got succeed.FYI.

MSSQL Select statement with incremental integer column... not from a table

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

How to convert string to integer in PowerShell

Example:

2.032 MB (2,131,022 bytes)

$u=($mbox.TotalItemSize.value).tostring()

$u=$u.trimend(" bytes)") #yields 2.032 MB (2,131,022

$u=$u.Split("(") #yields `$u[1]` as 2,131,022

$uI=[int]$u[1]

The result is 2131022 in integer form.

How to select distinct query using symfony2 doctrine query builder?

If you use the "select()" statement, you can do this:

$category = $catrep->createQueryBuilder('cc')
    ->select('DISTINCT cc.contenttype')
    ->Where('cc.contenttype = :type')
    ->setParameter('type', 'blogarticle')
    ->getQuery();

$categories = $category->getResult();

Get attribute name value of <input>

A better way could be using 'this', it takes whatever the name of the 'id' is and uses that. As long as you add the class name called 'mytarget'.

Whenever any of the fields that have target change then it will show an alert box with the name of that field. Just cut and past whole script for it to work!

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
 $('.mytarget').change(function() {
var name1 = $(this).attr("name");
alert(name1);
 });
});
</script>

Name: <input type="text" name="myname" id="myname" class="mytarget"><br />
Age: <input type="text" name="myage" id="myage" class="mytarget"><br />

how to call a variable in code behind to aspx page

For

<%=clients%>

to work you need to have a public or protected variable clients in the code-behind.

Here is an article that explains it: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

How to monitor Java memory usage?

There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.

Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.

Writing a new line to file in PHP (line feed)

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

some data
some data

How can I get useful error messages in PHP?

Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9

Get the date (a day before current time) in Bash

Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.

I find out I can get the previous date with little trick on timezone.

DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
echo $DATE

CSS Classes & SubClasses

The class you apply on the div can be used to as a reference point to style elements with that div, for example.

<div class="area1">
    <table>
        <tr>
                <td class="item">Text Text Text</td>
                <td class="item">Text Text Text</td>
        </tr>
    </table>
</div>


.area1 { border:1px solid black; }

.area1 td { color:red; } /* This will effect any TD within .area1 */

To be super semantic you should move the class onto the table.

    <table class="area1">
        <tr>
                <td>Text Text Text</td>
                <td>Text Text Text</td>
        </tr>
    </table>

Responsive css styles on mobile devices ONLY

Yes, this can be done via javascript feature detection ( or browser detection , e.g. Modernizr ) . Then, use yepnope.js to load required resources ( JS and/or CSS )

How to use bitmask?

Briefly bitmask helps to manipulate position of multiple values. There is a good example here ;

Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:

    #define LOG_ERRORS            1  // 2^0, bit 0
    #define LOG_WARNINGS          2  // 2^1, bit 1
    #define LOG_NOTICES           4  // 2^2, bit 2
    #define LOG_INCOMING          8  // 2^3, bit 3
    #define LOG_OUTGOING         16  // 2^4, bit 4
    #define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assigning a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;



**

WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :

**

if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
   ...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

You can also search C++ Triks

Finish all activities at a time

There are three solution for clear activity history.

1) You can write finish() at the time of start new activity through intent.

2) Write android:noHistory="true" in all <activity> tag in Androidmanifest.xml file, using this if you are open new activity and you don't write finish() at that time previous activity is always finished, after write your activity look like this.

<activity
    android:name=".Splash_Screen_Activity"
    android:label="@string/app_name"
    android:noHistory="true">

</activity>

3) write system.exit(0) for exit from the application.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

For people who like the .Net convention of "try" functions that return a boolean and handle a byref param containing the result. If you don't need the out parameter you can omit it and just use the return value.

StringTests.js

  var obj1 = {};
  var bool1 = '{"h":"happy"}'.tryParse(obj1); // false
  var obj2 = {};
  var bool2 = '2114509 GOODLUCKBUDDY 315852'.tryParse(obj2);  // false

  var obj3 = {};
  if('{"house_number":"1","road":"Mauchly","city":"Irvine","county":"Orange County","state":"California","postcode":"92618","country":"United States of America","country_code":"us"}'.tryParse(obj3))
    console.log(obj3);

StringUtils.js

String.prototype.tryParse = function(jsonObject) {
  jsonObject = jsonObject || {};
  try {
    if(!/^[\[{]/.test(this) || !/[}\]]$/.test(this)) // begin / end with [] or {}
      return false; // avoid error handling for strings that obviously aren't json
    var json = JSON.parse(this);
    if(typeof json === 'object'){
      jsonObject.merge(json);
      return true;
    }
  } catch (e) {
    return false;
  }
}

ObjectUtils.js

Object.defineProperty(Object.prototype, 'merge', {
  value: function(mergeObj){
    for (var propertyName in mergeObj) {
      if (mergeObj.hasOwnProperty(propertyName)) {
        this[propertyName] = mergeObj[propertyName];
      }      
    }
    return this;
  },
  enumerable: false, // this is actually the default
});

Changing route doesn't scroll to top in the new page

I found this solution. If you go to a new view the function gets executed.

var app = angular.module('hoofdModule', ['ngRoute']);

    app.controller('indexController', function ($scope, $window) {
        $scope.$on('$viewContentLoaded', function () {
            $window.scrollTo(0, 0);
        });
    });

How to set cache: false in jQuery.get call

Per the JQuery documentation, .get() only takes the url, data (content), dataType, and success callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax(), this is done with the beforeSend() method. But since .get() is a shortcut, it doesn't allow it.

It should be relatively easy to switch your .ajax() calls to .get() calls though. After all, .get() is just a subset of .ajax(), so you can probably use all the default values for .ajax() (except, of course, for beforeSend()).

Edit:

::Looks at Jivings' answer::

Oh yeah, forgot about the cache parameter! While beforeSend() is useful for adding other headers, the built-in cache parameter is far simpler here.

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

How to exclude a directory in find . command

Use the -prune option. So, something like:

find . -type d -name proc -prune -o -name '*.js'

The '-type d -name proc -prune' only look for directories named proc to exclude.
The '-o' is an 'OR' operator.

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

This works for me for Django 1.9 . The Python script to execute was in the root of the Django project.

    import django 
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PROJECT_NAME.settings")
    django.setup()
    from APP_NAME.models import *

Set PROJECT_NAME and APP_NAME to yours

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

mkdir c:\JDK
cd c:\JDK
git clone https://bitbucket.org/ramazanpolat/jdk-8u112-windows-x64/

or

git clone https://bitbucket.org/ramazanpolat/jdk-8u112-windows-x86

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

Git pull - Please move or remove them before you can merge

Apparently the files were added in remote repository, no matter what was the content of .gitignore file in the origin.

As the files exist in the remote repository, git has to pull them to your local work tree as well and therefore complains that the files already exist.

.gitignore is used only for scanning for the newly added files, it doesn't have anything to do with the files which were already added.

So the solution is to remove the files in your work tree and pull the latest version. Or the long-term solution is to remove the files from the repository if they were added by mistake.

A simple example to remove files from the remote branch is to

$git checkout <brachWithFiles>
$git rm -r *.extension
$git commit -m "fixin...."
$git push

Then you can try the $git merge again

count (non-blank) lines-of-code in bash

If you want the sum of all non-blank lines for all files of a given file extension throughout a project:

while read line
do grep -cve '^\s*$' "$line"
done <  <(find $1 -name "*.$2" -print) | awk '{s+=$1} END {print s}'

First arg is the project's base directory, second is the file extension. Sample usage:

./scriptname ~/Dropbox/project/src java

It's little more than a collection of previous solutions.

How to logout and redirect to login page using Laravel 5.4?

In your web.php (routes):

add:

Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');

In your LoginController.php

add:

public function logout(Request $request) {
  Auth::logout();
  return redirect('/login');
}

Also, in the top of LoginController.php, after namespace

add:

use Auth;

Now, you are able to logout using yourdomain.com/logout URL or if you have created logout button, add href to /logout

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

You can define 2 images in your HTML code and use display: none; to decide which one will be visible.

Convert comma separated string of ints to int array

import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
  String line;
  String[] lineVector;
  int n,m,i,j;
  Scanner sc = new Scanner(System.in);
  line = sc.nextLine();
  lineVector = line.split(",");
  //enter the size of the array
  n=Integer.parseInt(lineVector[0]);
  m=Integer.parseInt(lineVector[1]);
  int arr[][]= new int[n][m];
  //enter the array here
  System.out.println("Enter the array:");
  for(i=0;i<n;i++)
  {
  line = sc.nextLine();
  lineVector = line.split(",");
  for(j=0;j<m;j++)
  {
  arr[i][j] = Integer.parseInt(lineVector[j]);
  }
  }
  sc.close();
}
}

On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr. e.g input: 2,3 1,2,3 2,4,6 will store values as arr = {{1,2,3},{2,4,6}};

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

How would I check a string for a certain letter in Python?

in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

In this case string is nothing but a list of characters:

dog = "xdasds"
if "x" in dog:
     print "Yes!"

You can check a substring too:

>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>> 
>>> 
>>> 'xa' in "xdasds"
False

Think collection:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>> 

You can also test the set membership over user defined classes.

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

How to enable Auto Logon User Authentication for Google Chrome

While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.

Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:

  • Launching Chrome with the auth-server-whitelist command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz". Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.
  • Installing, enabling, and configuring the AuthServerWhitelist/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.

Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:

  1. Download and unzip the latest Chrome policy templates
  2. Start > Run > gpedit.msc
  3. Navigate to Local Computer Policy > Computer Configuration > Administrative Templates
  4. Right-click Administrative Templates, and select Add/Remove Templates
  5. Add the windows\adm\en-US\chrome.adm template via the dialog
  6. In Computer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication enable and configure Authentication server whitelist
  7. Restart Chrome and navigate to chrome://policy to view active policies

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

generate days from date range

It's a good idea with generating these dates on the fly. However, I do not feel myself comfortable to do this with quite large range so I've ended up with the following solution:

  1. Created a table "DatesNumbers" that will hold numbers used for dates calculation:
CREATE TABLE DatesNumbers (
    i MEDIUMINT NOT NULL,
    PRIMARY KEY (i)
)
COMMENT='Used by Dates view'
;
  1. Populated the table using above techniques with numbers from -59999 to 40000. This range will give me dates from 59999 days (~164 years) behind to 40000 days (109 years) ahead:
INSERT INTO DatesNumbers
SELECT 
    a.i + (10 * b.i) + (100 * c.i) + (1000 * d.i) + (10000 * e.i) - 59999 AS i
FROM 
  (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a,
  (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b,
  (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c,
  (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS d,
  (SELECT 0 AS i UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS e
;
  1. Created a view "Dates":
SELECT
      i,
      CURRENT_DATE() + INTERVAL i DAY AS Date
FROM
    DatesNumbers

That's it.

  • (+) Easy to read queries
  • (+) No on the fly numbers generations
  • (+) Gives dates in the past and in the future and there is NO UNION in view for this as in this post.
  • (+) "In the past only" or "in the future only" dates could be filtered using WHERE i < 0 or WHERE i > 0 (PK)
  • (-) 'temporary' table & view is used

PDF to image using Java

If GPL is fine you may have an additional look at jPodRenderer (SourceForge)

Is there a way to check if a file is in use?

The accepted answers above suffer an issue where if file has been opened for writing with a FileShare.Read mode or if the file has a Read-Only attribute the code will not work. This modified solution works most reliably, with two things to keep in mind (as true for the accepted solution also):

  1. It will not work for files that has been opened with a write share mode
  2. This does not take into account threading issues so you will need to lock it down or handle threading issues separately.

Keeping the above in mind, this checks if the file is either locked for writing or locked to prevent reading:

public static bool FileLocked(string FileName)
{
    FileStream fs = null;

    try
    {
        // NOTE: This doesn't handle situations where file is opened for writing by another process but put into write shared mode, it will not throw an exception and won't show it as write locked
        fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None); // If we can't open file for reading and writing then it's locked by another process for writing
    }
    catch (UnauthorizedAccessException) // https://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx
    {
        // This is because the file is Read-Only and we tried to open in ReadWrite mode, now try to open in Read only mode
        try
        {
            fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (Exception)
        {
            return true; // This file has been locked, we can't even open it to read
        }
    }
    catch (Exception)
    {
        return true; // This file has been locked
    }
    finally
    {
        if (fs != null)
            fs.Close();
    }
    return false;
}

Index (zero based) must be greater than or equal to zero

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter Your FirstName ");
            String FirstName = Console.ReadLine();

            Console.WriteLine("Enter Your LastName ");
            String LastName = Console.ReadLine();
            Console.ReadLine();

            Console.WriteLine("Hello {0}, {1} ", FirstName, LastName);
            Console.ReadLine();

        }
    }
}

Picture

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

At least 8 = {8,}:

str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)

How can I determine if a variable is 'undefined' or 'null'?

Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.

Convert `List<string>` to comma-separated string

Follow this:

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

        name.Add("Latif");

        name.Add("Ram");

        name.Add("Adam");
        string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));

MySQL: How to allow remote connection to mysql

If your MySQL server process is listening on 127.0.0.1 or ::1 only then you will not be able to connect remotely. If you have a bind-address setting in /etc/my.cnf this might be the source of the problem.

You will also have to add privileges for a non-localhost user as well.

Setting Short Value Java

There is no such thing as a byte or short literal. You need to cast to short using (short)100

How do I display images from Google Drive on a website?

If you have some image files, just upload them to a public folder on your Google Drive, copy its folder ID from the address bar (e.g. 0B0Gi4v5omoZUVXhCT2kta1l0ZG8) and paste it into a form at GDrives, then choose your own alias (e.g. myimgs) and voila! You can access the images one by one using e.g. http://gdriv.es/myimgs/myimage.jpg.

If you want to embed a whole folder on your website (in a frame), you can use one of the following URLs, replacing [folderID] with your own ID:

If you prefer to get the file list in XML or JSON, you can use YQL.

Note: You can use Google+ Photos to host ans embed your images as well.

Validating IPv4 addresses with regexp

''' This code works for me, and is as simple as that.

Here I have taken the value of ip and I am trying to match it with regex.

ip="25.255.45.67"    

op=re.match('(\d+).(\d+).(\d+).(\d+)',ip)

if ((int(op.group(1))<=255) and (int(op.group(2))<=255) and int(op.group(3))<=255) and (int(op.group(4))<=255)):

print("valid ip")

else:

print("Not valid")

Above condition checks if the value exceeds 255 for all the 4 octets then it is not a valid. But before applying the condition we have to convert them into integer since the value is in a string.

group(0) prints the matched output, Whereas group(1) prints the first matched value and here it is "25" and so on. '''

Get the value of input text when enter key pressed

$("input").on("keydown",function search(e) {
    if(e.keyCode == 13) {
        alert($(this).val());
    }
});

jsFiddle example : http://jsfiddle.net/NH8K2/1/

Where is svcutil.exe in Windows 7?

To find any file location

  1. In windows start menu Search box
  2. type in svcutil.exe
  3. Wait for results to populate
  4. Right click on svcutil.exe and Select 'Open file location'
  5. Copy Windows explorer path

How do I remove newlines from a text file?

perl -p -i -e 's/\R//g;' filename

Must do the job.

MySQL duplicate entry error even though there is no duplicate entry

Your code and schema are OK. You probably trying on previous version of table.

http://sqlfiddle.com/#!2/9dc64/1/0

Your table even has no UNIQUE, so that error is impossible on that table.

Backup data from that table, drop it and re-create.

Maybe you tried to run that CREATE TABLE IF NOT EXIST. It was not created, you have old version, but there was no error because of IF NOT EXIST.

You may run SQL like this to see current table structure:

DESCRIBE my_table;

Edit - added later:

Try to run this:

DROP TABLE `my_table`; --make backup - it deletes table

CREATE TABLE `my_table` (
  `number` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `money` int(11) NOT NULL,
  PRIMARY KEY (`number`,`name`),
  UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Additionally, if you can't see the "Provide Export Compliance Information" button make sure you have the right role in your App Store Connect or talk to the right person (Account Holder, Admin, or App Manager).

Django: How can I call a view function from template?

For deleting all data:

HTML FILE

  class="btn btn-primary" href="{% url 'delete_product'%}">Delete

Put the above code in an anchor tag. (the a tag!)

url.py

path('delete_product', views.delete_product, name='delete_product')]

views.py

def delete_product(request):
    if request.method == "GET":
        dest = Racket.objects.all()
        dest.delete()
        return render(request, "admin_page.html")

Cannot find mysql.sock

I'm getting the same error on Mac OS X 10.11.6:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

After a lot of agonizing and digging through advice here and in related questions, none of which seemed to fix the problem, I went back and deleted the installed folders, and just did brew install mysql.

Still getting the same error with most commands, but this works:

/usr/local/bin/mysqld

and returns:

/usr/local/bin/mysqld: ready for connections.

Version: '5.7.12' socket: '/tmp/mysql.sock' port: 3306 Homebrew

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

notifyDataSetChange not working from custom adapter

Change your method from

public void updateReceiptsList(List<Receipt> newlist) {
    receiptlist = newlist;
    this.notifyDataSetChanged();
}

To

public void updateReceiptsList(List<Receipt> newlist) {
    receiptlist.clear();
    receiptlist.addAll(newlist);
    this.notifyDataSetChanged();
}

So you keep the same object as your DataSet in your Adapter.