Programs & Examples On #Profile provider

Reference - What does this error mean in PHP?

Strict Standards: Non-static method [<class>::<method>] should not be called statically

Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT flag in your error_reporting() settings.

Example :

class HTML {
   public function br() {
      echo '<br>';
   }
}

HTML::br() or $html::br()

You can actually avoid this error by not adding E_STRICT to error_reporting(), eg

error_reporting(E_ALL & ~E_STRICT);

since as for PHP 5.4.0 and above, E_STRICT is included in E_ALL [ref]. But that is not adviceable. The solution is to define your intended static function as actual static :

public static function br() {
  echo '<br>';
}

or call the function conventionally :

$html = new HTML();
$html->br();

Related questions :

Draw line in UIView

Maybe this is a bit late, but I want to add that there is a better way. Using UIView is simple, but relatively slow. This method overrides how the view draws itself and is faster:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0f);

    CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point

    CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}

Download file using libcurl in C/C++

Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.

Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA

Example

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://stackoverflow.com";
    char outfilename[FILENAME_MAX] = "page.html";
    curl = curl_easy_init();                                                                                                                                                                                                                                                           
    if (curl)
    {   
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }   
    return 0;
}

Adding a Time to a DateTime in C#

Using https://github.com/FluentDateTime/FluentDateTime

DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);

Cell Style Alignment on a range

Maybe declaring a range might workout better for you.

// fill in the starting and ending range programmatically this is just an example. 
string startRange = "A1";
string endRange = "A1";
Excel.Range currentRange = (Excel.Range)excelWorksheet.get_Range(startRange , endRange );
currentRange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

You can do it with SQL Management Studio -

Server Properties - Security - [Server Authentication section] you check Sql Server and Windows authentication mode

Here is the msdn source - http://msdn.microsoft.com/en-us/library/ms188670.aspx

Sublime Text 2 - View whitespace characters

A "quick and dirty" way is to use the find function and activate regular expressions.

Then just search for : \s for highlighting spaces \t for tabs \n for new-lines etc.

How to set up subdomains on IIS 7

Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.

*.example.com IN A 1.2.3.4

http://www.webmasterworld.com/microsoft_asp_net/3194877.htm

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

Adding a Scrollable JTextArea (Java)

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.add(scroll);
frame.setVisible (true);

Clearing my form inputs after submission

Just include this line at the end of function and the Problem is solved easily!

document.getElementById("btnsubmit").value = "";

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

How to pass data from child component to its parent in ReactJS?

You can even avoid the function at the parent updating the state directly

In Parent Component:

render(){
 return(<Child sendData={ v => this.setState({item: v}) } />);
}

In the Child Component:

demoMethod(){
   this.props.sendData(value);
}

How can I convert string to datetime with format specification in JavaScript?

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.

function ParseDate(dateString) {
    //dd.mm.yyyy, or dd.mm.yy
    var dateArr = dateString.split(".");
    if (dateArr.length == 1) {
        return null;    //wrong format
    }
    //parse time after the year - separated by space
    var spacePos = dateArr[2].indexOf(" ");
    if(spacePos > 1) {
        var timeString = dateArr[2].substr(spacePos + 1);
        var timeArr = timeString.split(":");
        dateArr[2] = dateArr[2].substr(0, spacePos);
        if (timeArr.length == 2) {
            //minutes only
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
        } else {
            //including seconds
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
        }
    } else {
        //gotcha at months - January is at 0, not 1 as one would expect
        return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
    }
}

How to load a tsv file into a Pandas DataFrame?

Try this

df = pd.read_csv("rating-data.tsv",sep='\t')
df.head()

enter image description here

You actually need to fix the sep parameter.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

From what I understand, You have to save a user's input locally to a text file.

Check this link. See if this helps.

Saving user input to a text file locally

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

How do you cast a List of supertypes to a List of subtypes?

With Java 8, you actually can

List<TestB> variable = collectionOfListA
    .stream()
    .map(e -> (TestB) e)
    .collect(Collectors.toList());

How to encode the filename parameter of Content-Disposition header in HTTP?

I tested the following code in all major browsers, including older Explorers (via the compatibility mode), and it works well everywhere:

$filename = $_GET['file']; //this string from $_GET is already decoded
if (strstr($_SERVER['HTTP_USER_AGENT'],"MSIE"))
  $filename = rawurlencode($filename);
header('Content-Disposition: attachment; filename="'.$filename.'"');

The controller for path was not found or does not implement IController

In my case I had @{ Html.RenderAction("HeaderMenu", "Layout", new { Area = string.Empty }); } in _Layout.cshtml but the LayoutController did not exist! (I had copied _Layout.cshtml from another solution but forgot to copy the controller)

how to create inline style with :before and :after

The key is to use background-color: inherit; on the pseudo element.
See: http://jsfiddle.net/EdUmc/

Git - How to use .netrc file on Windows to save user and password

I am posting a way to use _netrc to download materials from the site www.course.com.

If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n instead of -U <username> -P <password> for convenience. He/she can do it like this:

  1. Check the home path on Windows OS: setx HOME %USERPROFILE%(refer to VonC's answer). It will save the HOME environment variable as C:\Users\"username".

  2. Locate into the directory C:\Users\"username" and create a file name _netrc.NOTE: there is NOT any suffix. the content is like: machine coursera-dl login <user> password <pass>

  3. Use a command like coursera-dl -n --path PATH <course name> to download the class materials. More coursera-dl options details for this page.

How to fully delete a git repository created with init?

true,like mine was stored in USERS,so had to open USERS go to View on you upper left find Options,open it and edit folders'view options in view still to display hidden files/folders,all your folders will be displayed and you can deleted the repo manually,remember to hide the files/folders once done with the delete.

show distinct column values in pyspark dataframe: python

In addition to the dropDuplicates option there is the method named as we know it in pandas drop_duplicates:

drop_duplicates() is an alias for dropDuplicates().

Example

s_df = sqlContext.createDataFrame([("foo", 1),
                                   ("foo", 1),
                                   ("bar", 2),
                                   ("foo", 3)], ('k', 'v'))
s_df.show()

+---+---+
|  k|  v|
+---+---+
|foo|  1|
|foo|  1|
|bar|  2|
|foo|  3|
+---+---+

Drop by subset

s_df.drop_duplicates(subset = ['k']).show()

+---+---+
|  k|  v|
+---+---+
|bar|  2|
|foo|  1|
+---+---+
s_df.drop_duplicates().show()


+---+---+
|  k|  v|
+---+---+
|bar|  2|
|foo|  3|
|foo|  1|
+---+---+

how to convert a string to a bool

Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:

bool val = Convert.ToBoolean("true");

or an extension method to do whatever weird mapping you're doing:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

How to resolve ambiguous column names when retrieving results?

You can either use the numerical indices ($row[0]) or better, use AS in the MySQL:

SELECT *, user.id AS user_id FROM ...

Getting attributes of Enum's value

I implemented this extension method to get the description from enum values. It works for all kind of enums.

public static class EnumExtension
{
    public static string ToDescription(this System.Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }
}

Adding an onclicklistener to listview (android)

Try this:

    list.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3)
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

How to make android listview scrollable?

Putting ListView inside a ScrollView is never inspired. But if you want your posted XML-like behavior, there're 3 options to me:

  1. Remove ScrollView: Removing your ScrollView, you may give the ListViews some specific size with respect to the total layout (either specific dp or layout_weight).

  2. Replace ListViews with LinearLayouts: You may add the list-items by iterating through the item-list and add each item-view to the respective LinearLayout by inflating the view & setting the respective data (string, image etc.)

  3. If you really need to put your ListViews inside the ScrollView, you must make your ListViews non-scrollable (Which is practically the same as the solution 2 above, but with ListView codes), otherwise the layout won't function as you expect.
    To make a ListView non-scrollable, you may read this SO post, where the precise solution to me is like the one below:

_x000D_
_x000D_
listView.setOnTouchListener(new OnTouchListener() {_x000D_
  public boolean onTouch(View v, MotionEvent event) {_x000D_
    return (event.getAction() == MotionEvent.ACTION_MOVE);_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

moment.js, how to get day of week number

Define "doesn't work".

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

This prints "4", as expected.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

localStorage.clear()

That'll clear the stored data. Then refresh and things should start to work.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Select parent element of known element in Selenium

This might be useful for someone else: Using this sample html

<div class="ParentDiv">
    <label for="label">labelName</label>
    <input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
    <label for="animal">pig</label>
    <input type="button" value="elementToSelect">
</div>

If for example, I want to select an element in the same section (e.g div) as a label, you can use this

//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect'] 

This just means, look for a label (it could anything like a, h2) called labelName. Navigate to the parent of that label (i.e. div class="ParentDiv"). Search within the descendants of that parent to find any child element with the value of elementToSelect. With this, it will not select the second elementToSelect with DontSelect div as parent.

The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need. Other Syntax like following-sibling::h2 can also be used in some cases. This means the sibling following element h2. This will work for elements at the same level, having the same parent.

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

Ubuntu Users:

I had the same problem and I fixed it by installing nodejson my system independent of the gem.

on ubuntu its: sudo apt-get install nodejs

I'm using 64bit ubuntu 11.10

update: From @Galina 's answer below I'm guessing that the latest version of nodejs is required, so @steve98177 your best option on a redhat(or CentOS) box is to install from source code as @Galina did, but as you can't "make/install" on this box ?, I suggest you try to install a fedora rpm(long shot) https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager or find another RH/CentOs box(that you can 'make' on) and create your own rpm and install on original RH box(if old glibc on RH plays nice).

The real issue here(IMHO) is installing Gems that have dependencies on installed packages outside of the ruby environment, is there a way of knowing before installing ? an RFI for Gems or bundler ?


CentOS/RedHat Users:

sudo yum install nodejs

How to get ID of clicked element with jQuery

Your IDs are #1, and cycle just wants a number passed to it. You need to remove the # before calling cycle.

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('#', '')); 
    return false; 
});

Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1.

<a href="#" id="pager_1" class="pagerlink" >link</a>

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('pager_', '')); 
    return false; 
});

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

How to change a string into uppercase

For questions on simple string manipulation the dir built-in function comes in handy. It gives you, among others, a list of methods of the argument, e.g., dir(s) returns a list containing upper.

PreparedStatement IN clause alternatives?

My workaround (JavaScript)

    var s1 = " SELECT "

 + "FROM   table t "

 + "  where t.field in ";

  var s3 = '(';

  for(var i =0;i<searchTerms.length;i++)
  {
    if(i+1 == searchTerms.length)
    {
     s3  = s3+'?)';
    }
    else
    {
        s3  = s3+'?, ' ;
    }
   }
    var query = s1+s3;

    var pstmt = connection.prepareStatement(query);

     for(var i =0;i<searchTerms.length;i++)
    {
        pstmt.setString(i+1, searchTerms[i]);
    }

SearchTerms is the array which contains your input/keys/fields etc

How can I get the values of data attributes in JavaScript code?

You need to access the dataset property:

document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid),
    subject: this.dataset.type,
    points: parseInt(this.dataset.points),
    user: "Luïs"
  });
});

Result:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

unknown type name 'uint8_t', MinGW

I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.

I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).

Open Excel file for reading with VBA without display

Open them from a new instance of Excel.

Sub Test()

    Dim xl As Excel.Application
    Set xl = CreateObject("Excel.Application")

    Dim w As Workbook
    Set w = xl.Workbooks.Add()

    MsgBox "Not visible yet..."
    xl.Visible = True

    w.Close False
    Set xl = Nothing

End Sub

You need to remember to clean up after you're done.

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

You can try adding action="#{yourBean.function1}" on each button (changing of course the method function2, function3, or whatever you need). If that does not work, you can try the same with the onclick event.

Anyway, it would be easier to help you if you tell us what kind of buttons are you trying to use, a4j:commandButton or whatever you are using.

Highcharts - how to have a chart with dynamic height?

Alternatively, you can directly use javascript's window.onresize

As example, my code (using scriptaculos) is :

window.onresize = function (){
    var w = $("form").getWidth() + "px";
    $('gfx').setStyle( { width : w } );
}

Where form is an html form on my webpage and gfx the highchart graphics.

How to pass arguments from command line to gradle

I have written a piece of code that puts the command line arguments in the format that gradle expects.

// this method creates a command line arguments
def setCommandLineArguments(commandLineArgs) {
    // remove spaces 
    def arguments = commandLineArgs.tokenize()

            // create a string that can be used by Eval 
            def cla = "["
            // go through the list to get each argument
            arguments.each {
                    cla += "'" + "${it}" + "',"
            }

    // remove last "," add "]" and set the args 
    return cla.substring(0, cla.lastIndexOf(',')) + "]"
}

my task looks like this:

task runProgram(type: JavaExec) {
    if ( project.hasProperty("commandLineArgs") ) {
            args Eval.me( setCommandLineArguments(commandLineArgs) )
    }
}

To pass the arguments from the command line you run this:

gradle runProgram -PcommandLineArgs="arg1 arg2 arg3 arg4"    

How to indent a few lines in Markdown markup?

Some Markdown implementations seem to use the ~ character for indentation.

How to obtain the last index of a list?

all above answers is correct but however

a = [];
len(list1) - 1 # where 0 - 1 = -1

to be more precisely

a = [];
index = len(a) - 1 if a else None;

if index == None : raise Exception("Empty Array")

since arrays is starting with 0

How to check if a particular service is running on Ubuntu

There is a simple way to verify if a service is running

systemctl status service_name

Try PostgreSQL:

systemctl status postgresql

How to copy and edit files in Android shell?

If you just want to append to a file, e.g. to add some lines to a configuration file, inbuilt shell commands are enough:

adb shell
cat >> /path/to/file <<EOF
some text to append
a second line of text to append
EOF
exit

In the above, replace /path/to/file with the file you want to edit. You'll need to have write permission on the file, which implies root access if you're editing a system file. Secondly, replace some text to append and a second line of text to append with the lines you want to add.

Is there a limit on number of tcp/ip connections between machines on linux?

When looking for the max performance you run into a lot of issue and potential bottlenecks. Running a simple hello world test is not necessarily going to find them all.

Possible limitations include:

  • Kernel socket limitations: look in /proc/sys/net for lots of kernel tuning..
  • process limits: check out ulimit as others have stated here
  • as your application grows in complexity, it may not have enough CPU power to keep up with the number of connections coming in. Use top to see if your CPU is maxed
  • number of threads? I'm not experienced with threading, but this may come into play in conjunction with the previous items.

How to enable DataGridView sorting when user clicks on the column header?

If you get an error message like

An unhandled exception of type 'System.NullReferenceException' occurred in System.Windows.Forms.dll

if you work with SortableBindingList, your code probably uses some loops over DataGridView rows and also try to access the empty last row! (BindingSource = null)

If you don't need to allow the user to add new rows directly in the DataGridView this line of code easily solve the issue:

InitializeComponent();
m_dataGridView.AllowUserToAddRows = false; // after components initialized
...

ES6 modules implementation, how to load a json file

This just works on React & React Native

const data = require('./data/photos.json');

console.log('[-- typeof data --]', typeof data); // object


const fotos = data.xs.map(item => {
    return { uri: item };
});

Can constructors be async?

Since it is not possible to make an async constructor, I use a static async method that returns a class instance created by a private constructor. This is not elegant but it works ok.

public class ViewModel       
{       
    public ObservableCollection<TData> Data { get; set; }       

    //static async method that behave like a constructor       
    async public static Task<ViewModel> BuildViewModelAsync()  
    {       
        ObservableCollection<TData> tmpData = await GetDataTask();  
        return new ViewModel(tmpData);
    }       

    // private constructor called by the async method
    private ViewModel(ObservableCollection<TData> Data)
    {
        this.Data = Data;   
    }
}  

jQuery get the image src

This is what you need

 $('img').context.currentSrc

How can I split a text into sentences?

You can try using Spacy instead of regex. I use it and it does the job.

import spacy
nlp = spacy.load('en')

text = '''Your text here'''
tokens = nlp(text)

for sent in tokens.sents:
    print(sent.string.strip())

How to add an image in Tkinter?

It's not a standard lib of python 2.7. So in order for these to work properly and if you're using Python 2.7 you should download the PIL library first: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:

  1. Make sure that your script.py is at the same folder with the image you want to show.
  2. Edit your script.py

    from Tkinter import *        
    from PIL import ImageTk, Image
    
    app_root = Tk()
    
    #Setting it up
    img = ImageTk.PhotoImage(Image.open("app.png"))
    
    #Displaying it
    imglabel = Label(app_root, image=img).grid(row=1, column=1)        
    
    
    app_root.mainloop()
    

Hope that helps!

Find the most popular element in int[] array

Comparing two arrays, I Hope for that this is useful for you.

public static void main(String []args){

        int primerArray [] = {1,2,1,3,5};
        int arrayTow [] = {1,6,7,8};


       int numberMostRepetly =  validateArrays(primerArray,arrayTow);

       System.out.println(numberMostRepetly);


}


public static int validateArrays(int primerArray[], int arrayTow[]){

    int numVeces = 0;

    for(int i = 0; i< primerArray.length; i++){

        for(int c = i+1; c < primerArray.length; c++){

            if(primerArray[i] == primerArray[c]){
                numVeces = primerArray[c];
                // System.out.println("Numero que mas se repite");
                //System.out.println(numVeces);
            }
        }

        for(int a = 0; a < arrayTow.length; a++){

            if(numVeces == arrayTow[a]){
               // System.out.println(numVeces);
                return numVeces;
            }
        }
    }

    return 0;

}

CSS border less than 1px

It's impossible to draw a line on screen that's thinner than one pixel. Try using a more subtle color for the border instead.

How can I check for an empty/undefined/null string in JavaScript?

I usually use something like:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

How to check string length with JavaScript

The quick and dirty way would be to simple bind to the keyup event.

_x000D_
_x000D_
$('#mytxt').keyup(function(){_x000D_
    $('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
_x000D_
_x000D_

But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup )

How to calculate the SVG Path for an arc (of a circle)

ReactJS component based on the selected answer:

import React from 'react';

const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
    const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;

    return {
        x: centerX + (radius * Math.cos(angleInRadians)),
        y: centerY + (radius * Math.sin(angleInRadians))
    };
};

const describeSlice = (x, y, radius, startAngle, endAngle) => {

    const start = polarToCartesian(x, y, radius, endAngle);
    const end = polarToCartesian(x, y, radius, startAngle);

    const largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

    const d = [
        "M", 0, 0, start.x, start.y,
        "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");

    return d;
};

const path = (degrees = 90, radius = 10) => {
    return describeSlice(0, 0, radius, 0, degrees) + 'Z';
};

export const Arc = (props) => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
    <g transform="translate(150,150)" stroke="#000" strokeWidth="2">
        <path d={path(props.degrees, props.radius)} fill="#333"/>
    </g>

</svg>;

export default Arc;

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Just set setStackFromEnd=true or setReverseLayout=true so that LLM will layout items from end.

The difference between these two is that setStackFromEnd will set the view to show the last element, the layout direction will remain the same. (So, in an left-to-right horizontal Recycler View, the last element will be shown and scrolling to the left will show the earlier elements)

Whereas setReverseLayout will change the order of the elements added by the Adapter. The layout will start from the last element, which will be the left-most in an LTR Recycler View and then, scrolling to the right will show the earlier elements.

Sample:

final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
_listView.setLayoutManager(linearLayoutManager);

See documentation for details.

Java: Convert String to TimeStamp

I should like to contribute the modern answer. When this question was asked in 2013, using the Timestamp class was right, for example for storing a date-time into your database. Today the class is long outdated. The modern Java date and time API came out with Java 8 in the spring of 2014, three and a half years ago. I recommend you use this instead.

Depending on your situation an exact requirements, there are two natural replacements for Timestamp:

  • Instant is a point on the time-line. For most purposes I would consider it safest to use this. An Instant is independent of time zone and will usually work well even in situations where your client device and your database server run different time zones.
  • LocalDateTime is a date and time of day without time zone, like 2011-10-02 18:48:05.123 (to quote the question).

A modern JDBC driver (JDBC 4.2 or higher) and other modern tools for database access will be happy to store either an Instant or a LocalDateTime into your database column of datatype timestamp. Both classes and the other date-time classes I am using in this answer belong to the modern API known as java.time or JSR-310.

It’s easiest to convert your string to LocalDateTime, so let’s take that first:

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    String text = "2011-10-02 18:48:05.123";
    LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
    System.out.println(dateTime);

This prints

2011-10-02T18:48:05.123

If your string was in yyyy-MM-dd format, instead do:

    String text = "2009-10-20";
    LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
    System.out.println(dateTime);

This prints

2009-10-20T00:00

Or still better, take the output from LocalDate.parse() and store it into a database column of datatype date.

In both cases the procedure for converting from a LocalDateTime to an Instant is:

    Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    System.out.println(ts);

I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:

    Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();

Play a Sound with Python

For Linux user, if low level pcm data manipulation is needed, try alsaaudio module. There is a playwav.py example inside the package too.

How can I define fieldset border color?

If you don't want 3D border use:

border:#f00 1px solid;

String split on new line, tab and some number of spaces

Regex's aren't really the best tool for the job here. As others have said, using a combination of str.strip() and str.split() is the way to go. Here's a one liner to do it:

>>> data = '''\n\tName: John Smith
... \n\t  Home: Anytown USA
... \n\t    Phone: 555-555-555
... \n\t  Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t  Misc: Data with spaces'''
>>> {line.strip().split(': ')[0]:line.split(': ')[1] for line in data.splitlines() if line.strip() != ''}
{'Name': 'Jane Smith', 'Other Home': 'Somewhere Else', 'Notes': 'Other data', 'Misc': 'Data with spaces', 'Phone': '555-555-555', 'Home': 'Anytown USA'}

How do I set the default Java installation/runtime (Windows)?

I just had that problem (Java 1.8 vs. Java 9 on Windows 7) and my findings are:

short version

default seems to be (because of Path entry)

c:\ProgramData\Oracle\Java\javapath\java -version

select the version you want (test, use tab completing in cmd, not sure what those numbers represent), I had 2 options, see longer version for details

c:\ProgramData\Oracle\Java\javapath_target_[tab]

remove junction/link and link to your version (the one ending with 181743567 in my case for Java 8)

rmdir javapath
mklink /D javapath javapath_target_181743567

longer version:

Reinstall Java 1.8 after Java 9 didn't work. The sequence of installations was jdk1.8.0_74, jdk-9.0.4 and attempt to make Java 8 default with jdk1.8.0_162...

After jdk1.8.0_162 installation I still have

java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

What I see in path is

Path=...;C:\ProgramData\Oracle\Java\javapath;...

So I checked what is that and I found it is a junction (link)

c:\ProgramData\Oracle\Java>dir
 Volume in drive C is OSDisk
 Volume Serial Number is DA2F-C2CC

 Directory of c:\ProgramData\Oracle\Java

2018-02-07  17:06    <DIR>          .
2018-02-07  17:06    <DIR>          ..
2018-02-08  17:08    <DIR>          .oracle_jre_usage
2017-08-22  11:04    <DIR>          installcache
2018-02-08  17:08    <DIR>          installcache_x64
2018-02-07  17:06    <JUNCTION>     javapath [C:\ProgramData\Oracle\Java\javapath_target_185258831]
2018-02-07  17:06    <DIR>          javapath_target_181743567
2018-02-07  17:06    <DIR>          javapath_target_185258831

Those hashes doesn't ring a bell, but when I checked

c:\ProgramData\Oracle\Java\javapath_target_181743567>.\java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

c:\ProgramData\Oracle\Java\javapath_target_185258831>.\java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

so to make Java 8 default again I had to delete the link as described here

rmdir javapath

and recreate with Java I wanted

mklink /D javapath javapath_target_181743567

tested:

c:\ProgramData\Oracle\Java>java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

** update (Java 10) **

With Java 10 it is similar, only javapath is in c:\Program Files (x86)\Common Files\Oracle\Java\ which is strange as I installed 64-bit IMHO

.\java -version
java version "10.0.2" 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)

python numpy/scipy curve fitting

I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

enter image description here

Razor View Without Layout

I wanted to display the login page without the layout and this works pretty good for me.(this is the _ViewStart.cshtml file) You need to set the ViewBag.Title in the Controller.

@{
    if (! (ViewContext.ViewBag.Title == "Login"))
    {
        Layout = "~/Views/Shared/_Layout.cshtml";        
    } 
}

I know it's a little bit late but I hope this helps some body.

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Take screenshots in the iOS simulator

on iOS Simulator,

Press Command + control + c or from menu : Edit>Copy Screen

open "Preview" app, Press Command + n or from menu : File> New from clipboard , then you can save command+s

For Retina, activate iOS Simulator then on menu:HardWare>Device>iPhone (Retina) and follow above process

Command + S

is the way to save on Desktop, (on new iPhone simulators, this was introduced in later simulator)

How to insert text at beginning of a multi-line selection in vi/Vim

For commenting blocks of code, I like the NERD Commenter plugin.

Select some text:

Shift-V
...select the lines of text you want to comment....

Comment:

,cc

Uncomment:

,cu

Or just toggle the comment state of a line or block:

,c<space>

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

How to use export with Python on Linux

Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.

$(python -c 'print "export MY_DATA=my_export"')

(you can also enclose the statement in backticks in some shells ``)

Submit a form using jQuery

For information
if anyone use

$('#formId').submit();

Do not something like this

<button name = "submit">

It took many hours to find me that submit() won't work like this.

How do you make websites with Java?

While a lot of others should be mentioned, Apache Wicket should be preferred.

Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.

How can I drop a table if there is a foreign key constraint in SQL Server?

BhupeshC and murat , this is what I was looking for. However @SQL varchar(4000) wasn't big enough. So, small change

DECLARE @cmd varchar(4000)

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 

select 'ALTER TABLE ['+s.name+'].['+t.name+'] DROP CONSTRAINT [' + RTRIM(f.name) +'];' FROM sys.Tables t INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id INNER JOIN sys.schemas s ON s.schema_id = f.schema_id

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @cmd
WHILE @@FETCH_STATUS = 0
BEGIN
    -- EXEC (@cmd)
    PRINT @cmd
    FETCH NEXT FROM MY_CURSOR INTO @cmd
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

GO

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).

The request was aborted: Could not create SSL/TLS secure channel

Similar to an existing answer but in PowerShell:

[System.Net.ServicePointManager]::SecurityProtocol = `
[System.Net.SecurityProtocolType]::Tls11 -bor 
[System.Net.SecurityProtocolType]::Tls12 -bor `   
[System.Net.SecurityProtocolType]::Tls -bor `
[System.Net.SecurityProtocolType]::Ssl3

Then calling Invoke-WebRequest should work.

Got this from anonymous feedback, good suggestion: Simpler way to write this would be:

[System.Net.ServicePointManager]::SecurityProtocol = @("Tls12","Tls11","Tls","Ssl3")

Found this fantastic and related post by Jaykul: Validating Self-Signed Certificates From .Net and PowerShell

Java: how can I split an ArrayList in multiple small ArrayLists?

Let's suppose you want the considere the class that split the list into multiple chuncks as a library class.

So let's say the class is called 'shared' and in should be final to be sure it won't be extended.

   import java.util.ArrayList;
   import java.util.Arrays;
   import java.util.List;

public final class Shared {
List<Integer> input;
int portion;

public Shared(int portion, Integer... input) {
    this.setPortion(portion);
    this.setInput(input);
}

public List<List<Integer>> listToChunks() {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    int size = this.size();
    int startAt = 0;
    int endAt = this.portion;

    while (endAt <= size) {

        result.add(this.input.subList(startAt, endAt));
        startAt = endAt;
        endAt = (size - endAt < this.portion && size - endAt > 0) ? (this.size()) : (endAt + this.portion);
    }

    return result;
}

public int size() {
    return this.input.size();
}

public void setInput(Integer... input) {
    if (input != null && input.length > 0)
        this.input = Arrays.asList(input);
    else
        System.out.println("Error 001 : please enter a valid array of integers.");
}

public void setPortion(int portion) {
    if (portion > 0)
        this.portion = portion;
    else
        System.out.println("Error 002 : please enter a valid positive number.");
}
}

Next, let's try to execute it from another class that hold the public static void main(String... args)

public class exercise {

public static void main(String[] args) {
    Integer[] numbers = {1, 2, 3, 4, 5, 6, 7};
    int portion = 2;
    Shared share = new Shared(portion, numbers);
    System.out.println(share.listToChunks());   
}
}

Now, if you enter an array of integer [1, 2, 3, 4, 5, 6, 7] with a partition of 2. the result will be [[1, 2], [3, 4], [5, 6], [7]]

RegEx to exclude a specific string constant

You could use negative lookahead, or something like this:

^([^A]|A([^B]|B([^C]|$)|$)|$).*$

Maybe it could be simplified a bit.

string comparison in batch file

Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.

Works for me...

C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

Checking if any elements in one list are in another

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True

Converting string to date in mongodb

In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })

How to listen to route changes in react router v4?

v5.1 introduces the useful hook useLocation

https://reacttraining.com/blog/react-router-v5-1/#uselocation

import { Switch, useLocation } from 'react-router-dom'

function usePageViews() {
  let location = useLocation()

  useEffect(
    () => {
      ga.send(['pageview', location.pathname])
    },
    [location]
  )
}

function App() {
  usePageViews()
  return <Switch>{/* your routes here */}</Switch>
}

How to receive POST data in django

You should have access to the POST dictionary on the request object.

Difference between Python's Generators and Iterators

Examples from Ned Batchelder highly recommended for iterators and generators

A method without generators that do something to even numbers

def evens(stream):
   them = []
   for n in stream:
      if n % 2 == 0:
         them.append(n)
   return them

while by using a generator

def evens(stream):
    for n in stream:
        if n % 2 == 0:
            yield n
  • We don't need any list nor a return statement
  • Efficient for large/ infinite length stream ... it just walks and yield the value

Calling the evens method (generator) is as usual

num = [...]
for n in evens(num):
   do_smth(n)
  • Generator also used to Break double loop

Iterator

A book full of pages is an iterable, A bookmark is an iterator

and this bookmark has nothing to do except to move next

litr = iter([1,2,3])
next(litr) ## 1
next(litr) ## 2
next(litr) ## 3
next(litr) ## StopIteration  (Exception) as we got end of the iterator

To use Generator ... we need a function

To use Iterator ... we need next and iter

As been said:

A Generator function returns an iterator object

The Whole benefit of Iterator:

Store one element a time in memory

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

Find the IP address of the client in an SSH session

 who | cut -d"(" -f2 |cut -d")" -f1

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

use video as background for div

Why not fix a <video> and use z-index:-1 to put it behind all other elements?

html, body { width:100%; height:100%; margin:0; padding:0; }

<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
    <video id="video" style="width:100%; height:100%">
        ....
    </video>
</div>
<div class='content'>
    ....

Demo

If you want it within a container you have to add a container element and a little more CSS

/* HTML */
<div class='vidContain'>
    <div class='vid'>
        <video> ... </video>
    </div>
    <div class='content'> ... The rest of your content ... </div>
</div>

/* CSS */
.vidContain {
    width:300px; height:200px;
    position:relative;
    display:inline-block;
    margin:10px;
}
.vid {
    position: absolute; 
    top: 0; left:0;
    width: 100%; height: 100%; 
    z-index: -1;
}    
.content {
    position:absolute;
    top:0; left:0;
    background: black;
    color:white;
}

Demo

Android Material Design Button Styles

If I understand you correctly, you want to do something like this:
enter image description here

In such case, it should be just enough to use:

<item name="android:colorButtonNormal">#2196f3</item>

Or for API less than 21:

<item name="colorButtonNormal">#2196f3</item>

In addition to Using Material Theme Tutorial.

Animated variant is here.

How to split large text file in windows?

Of course there is! Win CMD can do a lot more than just split text files :)

Split a text file into separate files of 'max' lines each:

Split text file (max lines each):
: Initialize
set input=file.txt
set max=10000

set /a line=1 >nul
set /a file=1 >nul
set out=!file!_%input%
set /a max+=1 >nul

echo Number of lines in %input%:
find /c /v "" < %input%

: Split file
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (

if !line!==%max% (
set /a line=1 >nul
set /a file+=1 >nul
set out=!file!_%input%
echo Writing file: !out!
)

REM Write next file
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>out!
set /a line+=1 >nul
)

If above code hangs or crashes, this example code splits files faster (by writing data to intermediate files instead of keeping everything in memory):

eg. To split a file with 7,600 lines into smaller files of maximum 3000 lines.

  1. Generate regexp string/pattern files with set command to be fed to /g flag of findstr

list1.txt

\[[0-9]\]
\[[0-9][0-9]\]
\[[0-9][0-9][0-9]\]
\[[0-2][0-9][0-9][0-9]\]

list2.txt

\[[3-5][0-9][0-9][0-9]\]

list3.txt

\[[6-9][0-9][0-9][0-9]\]

  1. Split the file into smaller files:
type "%input%" | find /v /n "" | findstr /b /r /g:list1.txt > file1.txt
type "%input%" | find /v /n "" | findstr /b /r /g:list2.txt > file2.txt
type "%input%" | find /v /n "" | findstr /b /r /g:list3.txt > file3.txt
  1. remove prefixed line numbers for each file split:
    eg. for the 1st file:
for /f "tokens=* delims=[" %i in ('type "%cd%\file1.txt"') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>file_1.txt)

Notes:
Works with leading whitespace, blank lines & whitespace lines.

Tested on Win 10 x64 CMD, on 4.4GB text file, 5651982 lines.

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How do I install Java on Mac OSX allowing version switching?

Note: These solutions work for various versions of Java including Java 8, Java 11, and the new Java 15, and for any other previous Java version covered by the listed version managers. This includes alternative JDK's from OpenJDK, Oracle, IBM, Azul, Amazon Correto, Graal and more. Easily work with Java 7, Java 8, Java 9, Java 10, Java 11, Java 12, Java 13, Java 14, and Java 15!

You have a few options for how to do the installation as well as manage JDK switching. Installation can be done by Homebrew, SDKMAN, Jabba, or a manual install. Switching can be done by JEnv, SDKMAN, Jabba, or manually by setting JAVA_HOME. All of these are described below.


Installation

First, install Java using whatever method you prefer including Homebrew, SDKMAN or a manual install of the tar.gz file. The advantage of a manual install is that the location of the JDK can be placed in a standardized location for Mac OSX. Otherwise, there are easier options such as SDKMAN that also will install other important and common tools for the JVM.

Installing and Switching versions with SDKMAN

SDKMAN is a bit different and handles both the install and the switching. SDKMAN also places the installed JDK's into its own directory tree, which is typically ~/.sdkman/candidates/java. SDKMAN allows setting a global default version, and a version specific to the current shell.

  1. Install SDKMAN from https://sdkman.io/install

  2. List the Java versions available to make sure you know the version ID

    sdk list java
    
  3. Install one of those versions, for example, Java 15:

    sdk install java 15-open 
    
  4. Make 15 the default version:

    sdk default java 15-open
    

    Or switch to 15 for the session:

    sdk use java 15-open
    

When you list available versions for installation using the list command, you will see a wide variety of distributions of Java:

sdk list java

And install additional versions, such as JDK 8:

sdk install java 8.0.181-oracle

SDKMAN can work with previously installed existing versions. Just do a local install giving your own version label and the location of the JDK:

sdk install java my-local-13 /Library/Java/JavaVirtualMachines/jdk-13.jdk/Contents/Home

And use it freely:

sdk use java my-local-13

More information is available in the SDKMAN Usage Guide along with other SDK's it can install and manage.

SDKMAN will automatically manage your PATH and JAVA_HOME for you as you change versions.


Install manually from OpenJDK download page:

  1. Download OpenJDK for Mac OSX from http://jdk.java.net/ (for example Java 15)

  2. Unarchive the OpenJDK tar, and place the resulting folder (i.e. jdk-15.jdk) into your /Library/Java/JavaVirtualMachines/ folder since this is the standard and expected location of JDK installs. You can also install anywhere you want in reality.

Install with Homebrew

The version of Java available in Homebrew Cask previous to October 3, 2018 was indeed the Oracle JVM. Now, however, it has now been updated to OpenJDK. Be sure to update Homebrew and then you will see the lastest version available for install.

  1. install Homebrew if you haven't already. Make sure it is updated:

     brew update
    
  2. Add the casks tap, if you want to use the AdoptOpenJDK versions (which tend to be more current):

     brew tap adoptopenjdk/openjdk
    

    These casks change their Java versions often, and there might be other taps out there with additional Java versions.

  3. Look for installable versions:

     brew search java   
    

    or for AdoptOpenJDK versions:

     brew search jdk     
    
  4. Check the details on the version that will be installed:

     brew info java
    

    or for the AdoptOpenJDK version:

     brew info adoptopenjdk
    
  5. Install a specific version of the JDK such as java11, adoptopenjdk8, or adoptopenjdk13, or just java or adoptopenjdk for the most current of that distribution. For example:

     brew install java
    
     brew cask install adoptopenjdk13
    

And these will be installed into /Library/Java/JavaVirtualMachines/ which is the traditional location expected on Mac OSX.

Other installation options:

Some other flavours of OpenJDK are:

Azul Systems Java Zulu certified builds of OpenJDK can be installed by following the instructions on their site.

Zulu® is a certified build of OpenJDK that is fully compliant with the Java SE standard. Zulu is 100% open source and freely downloadable. Now Java developers, system administrators, and end-users can enjoy the full benefits of open source Java with deployment flexibility and control over upgrade timing.

Amazon Correto OpenJDK builds have an easy to use an installation package for Java 8 or Java 11, and installs to the standard /Library/Java/JavaVirtualMachines/ directory on Mac OSX.

Amazon Corretto is a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK). Corretto comes with long-term support that will include performance enhancements and security fixes. Amazon runs Corretto internally on thousands of production services and Corretto is certified as compatible with the Java SE standard. With Corretto, you can develop and run Java applications on popular operating systems, including Linux, Windows, and macOS.


Where is my JDK?!?!

To find locations of previously installed Java JDK's installed at the default system locations, use:

/usr/libexec/java_home -V

Matching Java Virtual Machines (8):
15, x86_64: "OpenJDK 15" /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home 14, x86_64: "OpenJDK 14" /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home 13, x86_64: "OpenJDK 13" /Library/Java/JavaVirtualMachines/openjdk-13.jdk/Contents/Home 12, x86_64: "OpenJDK 12" /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
11, x86_64: "Java SE 11" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.2, x86_64: "Java SE 10.0.2" /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
1.8.0_144, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home

You can also report just the location of a specific Java version using -v. For example for Java 15:

/usr/libexec/java_home -v 15

/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

Knowing the location of the installed JDK's is also useful when using tools like JEnv, or adding a local install to SDKMAN, or linking a system JDK in Jabba -- and you need to know where to find them.

If you need to find JDK's installed by other tools, check these locations:

  • SDKMAN installs to ~/.sdkman/candidates/java/
  • Jabba installs to ~/.jabba/jdk

Switching versions manually

The Java executable is a wrapper that will use whatever JDK is configured in JAVA_HOME, so you can change that to also change which JDK is in use.

For example, if you installed or untar'd JDK 15 to /Library/Java/JavaVirtualMachines/jdk-15.jdk if it is the highest version number it should already be the default, if not you could simply set:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

And now whatever Java executable is in the path will see this and use the correct JDK.

Using the /usr/libexec/java_home utility as previously described helps you to create aliases or to run commands to change Java versions by identifying the locations of different JDK installations. For example, creating shell aliases in your .profile or .bash_profile to change JAVA_HOME for you:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)
export JAVA_10_HOME=$(/usr/libexec/java_home -v10)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
export JAVA_12_HOME=$(/usr/libexec/java_home -v12)
export JAVA_13_HOME=$(/usr/libexec/java_home -v13)
export JAVA_14_HOME=$(/usr/libexec/java_home -v14)
export JAVA_15_HOME=$(/usr/libexec/java_home -v15)

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'
alias java10='export JAVA_HOME=$JAVA_10_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
alias java12='export JAVA_HOME=$JAVA_12_HOME'
alias java13='export JAVA_HOME=$JAVA_13_HOME'
alias java14='export JAVA_HOME=$JAVA_14_HOME'
alias java15='export JAVA_HOME=$JAVA_15_HOME'

# default to Java 15
java15

Then to change versions, just use the alias.

java8
java -version

java version "1.8.0_144"

Of course, setting JAVA_HOME manually works too!


Switching versions with JEnv

JEnv expects the Java JDK's to already exist on the machine and can be in any location. Typically you will find installed Java JDK's in /Library/Java/JavaVirtualMachines/. JEnv allows setting the global version of Java, one for the current shell, and a per-directory local version which is handy when some projects require different versions than others.

  1. Install JEnv if you haven't already, instructions on the site http://www.jenv.be/ for manual install or using Homebrew.

  2. Add any Java version to JEnv (adjust the directory if you placed this elsewhere):

    jenv add /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home
    
  3. Set your global version using this command:

    jenv global 15
    

You can also add other existing versions using jenv add in a similar manner, and list those that are available. For example Java 8:

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home 
jenv versions

See the JEnv docs for more commands. You may now switch between any Java versions (Oracle, OpenJDK, other) at any time either for the whole system, for shells, or per local directory.

To help manage JAVA_HOME while using JEnv you can add the export plugin to do this for you.

$ jenv enable-plugin export
  You may restart your session to activate jenv export plugin echo export plugin activated

The export plugin may not adjust JAVA_HOME if it is already set, so you may need to clear this variable in your profile so that it can be managed by JEnv.

You can also use jenv exec <command> <parms...> to run single commands with JAVA_HOME and PATH set correctly for that one command, which could include opening another shell.


Installing and Switching versions with Jabba

Jabba also handles both the install and the switching. Jabba also places the installed JDK's into its own directory tree, which is typically ~/.jabba/jdk.

  1. Install Jabba by following the instructions on the home page.

  2. List available JDK's

    jabba ls-remote

  3. Install Java JDK 12

    jabba install [email protected]

  4. Use it:

    jabba use [email protected]

You can also alias version names, link to existing JDK's already installed, and find a mix of interesting JDK's such as GraalVM, Adopt JDK, IBM JDK, and more. The complete usage guide is available on the home page as well.

Jabba will automatically manage your PATH and JAVA_HOME for you as you change versions.

How do I load the contents of a text file into a javascript variable?

Update 2019: Using Fetch:

fetch('http://localhost/foo.txt')
  .then(response => response.text())
  .then((data) => {
    console.log(data)
  })

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Simple if else onclick then do?

I did it that way and I like it better, but it can be optimized, right?

// Obtengo los botones y la caja de contenido
var home = document.getElementById("home");
var about = document.getElementById("about");
var service = document.getElementById("service");
var contact = document.getElementById("contact");
var content = document.querySelector("section");

function botonPress(e){
  console.log(e.getAttribute("id"));
  var screen = e.getAttribute("id");
  switch(screen){
    case "home":
      // cambiar fondo
      content.style.backgroundColor = 'black';
      break;
    case "about":
      // cambiar fondo
      content.style.backgroundColor = 'blue';
      break;
    case "service":
      // cambiar fondo
      content.style.backgroundColor = 'green';
      break;
    case "contact":
      // cambiar fondo
      content.style.backgroundColor = 'red';
      break;
  }
}

How can I format a decimal to always show 2 decimal places?

You can use the string formatting operator as so:

num = 49
x = "%.2f" % num  # x is now the string "49.00"

I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.

CSS: fixed position on x-axis but not y?

I realize this thread is mighty old but it helped me come up with a solution for my project.

In my case I had a header that I wanted to never be less than 1000px wide, header always on top, with content that could go unlimited right.

header{position:fixed; min-width:1024px;}
<header data-min-width="1024"></header>

    $(window).on('scroll resize', function () {
        var header = $('header');
        if ($(this).width() < header.data('min-width')) {
            header.css('left', -$(this).scrollLeft());
        } else {
            header.css('left', '');
        }
    });

This also should handle when your browser is less than your headers min-width

How can I center <ul> <li> into div

Another option is:

HTML

<nav>
  <ul class = "main-nav"> 
   <li> Productos </li>
   <li> Catalogo </li>
   <li> Contact </li>  
   <li> Us </li>
  </ul>
</nav>    

CSS:

nav {
  text-align: center;
}

nav .main-nav li {
  float: left;
  width: 20%;
  margin-right: 5%;
  font-size: 36px;
  text-align: center;
}

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

And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message

MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'

A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell

sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep  zzZZ";  afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s

Why would one omit the close tag?

Pros

Cons

  • Avoids headache with adding inadvertently whitespaces after the closing tag, because it breaks the header() function behavior... Some editors or FTP clients / servers are also known to change automatically the end of files (at least, it's their default configuration)
  • PHP manual says closing tag is optional, and Zend even forbids it.

Conclusion

I would say that the arguments in favor of omitting the tag look stronger (helps to avoid big headache with header() + it's PHP/Zend "recommendation"). I admit that this isn't the most "beautiful" solution I've ever seen in terms of syntax consistency, but what could be better ?

Why when I transfer a file through SFTP, it takes longer than FTP?

For comparison, I tried transfering a 299GB ntfs disk image from an i5 laptop running Raring Ringtail Ubuntu alpha 2 live cd to an i7 desktop running Ubuntu 12.04.1. Reported speeds:

over wifi + powerline: scp: 5MB/sec (40 Mbit/sec)

over gigabit ethernet + netgear G5608 v3:

scp: 44MB/sec

sftp: 47MB/sec

sftp -C: 13MB/sec

So, over a good gigabit link, sftp is slightly faster than scp, 2010-era fast CPUs seem fast enough to encrypt, but compression isn't a win in all cases.

Over a bad gigabit ethernet link, though, I've had sftp far outperform scp. Something about scp being very chatty, see "scp UNBELIEVABLY slow" on comp.security.ssh from 2008: https://groups.google.com/forum/?fromgroups=#!topic/comp.security.ssh/ldPV3msFFQw http://fixunix.com/ssh/368694-scp-unbelievably-slow.html

How to call a RESTful web service from Android?

Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/

// The connection URL 
String url = "https://ajax.googleapis.com/ajax/" + 
    "services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");

ImportError: cannot import name

Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app module, call mod_login.mod_login

app.py

from flask import Flask
import mod_login

# ...

do_stuff_with(mod_login.mod_login)

mod_login.py

from app import app

mod_login = something

Select columns based on string match - dplyr::select

No need to use select just use [ instead

data[,grepl("search_string", colnames(data))]

Let's try with iris dataset

>iris[,grepl("Sepal", colnames(iris))]
  Sepal.Length Sepal.Width
1          5.1         3.5
2          4.9         3.0
3          4.7         3.2
4          4.6         3.1
5          5.0         3.6
6          5.4         3.9

How to plot ROC curve in Python

When you need the probabilities as well... The following gets the AUC value and plots it all in one shot.

from sklearn.metrics import plot_roc_curve

plot_roc_curve(m,xs,y)

When you have the probabilities... you can't get the auc value and plots in one shot. Do the following:

from sklearn.metrics import roc_curve

fpr,tpr,_ = roc_curve(y,y_probas)
plt.plot(fpr,tpr, label='AUC = ' + str(round(roc_auc_score(y,m.oob_decision_function_[:,1]), 2)))
plt.legend(loc='lower right')

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

pytest cannot import module while python can

I had the same problem but for another reason than the ones mentioned:

I had py.test installed globally, while the packages were installed in a virtual environment.

The solution was to install pytest in the virtual environment. (In case your shell hashes executables, as Bash does, use hash -r, or use the full path to py.test)

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

How to find out if an item is present in a std::vector?

You can use count too. It will return the number of items present in a vector.

int t=count(vec.begin(),vec.end(),item);

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

Submitting a form by pressing enter without a submit button

Have you tried this ?

<input type="submit" style="visibility: hidden;" />

Since most browsers understand visibility:hidden and it doesn't really work like display:none, I'm guessing that it should be fine, though. Haven't really tested it myself, so CMIIW.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

How to insert a picture into Excel at a specified cell position with VBA

Try this:

With xlApp.ActiveSheet.Pictures.Insert(PicPath)
    With .ShapeRange
        .LockAspectRatio = msoTrue
        .Width = 75
        .Height = 100
    End With
    .Left = xlApp.ActiveSheet.Cells(i, 20).Left
    .Top = xlApp.ActiveSheet.Cells(i, 20).Top
    .Placement = 1
    .PrintObject = True
End With

It's better not to .select anything in Excel, it is usually never necessary and slows down your code.

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

ReferenceError: document is not defined (in plain JavaScript)

It depends on when the self executing anonymous function is running. It is possible that it is running before window.document is defined.

In that case, try adding a listener

window.addEventListener('load', yourFunction, false);
// ..... or 
window.addEventListener('DOMContentLoaded', yourFunction, false);

yourFunction () {
  // some ocde

}

Update: (after the update of the question and inclusion of the code)

Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM

SQL Server tables: what is the difference between @, # and ##?

# and ## tables are actual tables represented in the temp database. These tables can have indexes and statistics, and can be accessed across sprocs in a session (in the case of a global temp table, it is available across sessions).

The @table is a table variable.

For more: http://www.sqlteam.com/article/temporary-tables

Convenient C++ struct initialisation

You could use a lambda:

const FooBar fb = [&] {
    FooBar fb;
    fb.foo = 12;
    fb.bar = 3.4;
    return fb;
}();

More information on this idiom can be found on Herb Sutter's blog.

Remove the last chars of the Java String variable

I am surprised to see that all the other answers (as of Sep 8, 2013) either involve counting the number of characters in the substring ".null" or throw a StringIndexOutOfBoundsException if the substring is not found. Or both :(

I suggest the following:

public class Main {

    public static void main(String[] args) {

        String path = "file.txt";
        String extension = ".doc";

        int position = path.lastIndexOf(extension);

        if (position!=-1)
            path = path.substring(0, position);
        else
            System.out.println("Extension: "+extension+" not found");

        System.out.println("Result: "+path);
    }

}

If the substring is not found, nothing happens, as there is nothing to cut off. You won't get the StringIndexOutOfBoundsException. Also, you don't have to count the characters yourself in the substring.

How to move/rename a file using an Ansible task on a remote system

Bruce wasn't attempting to stat the destination to check whether or not to move the file if it was already there; he was making sure the file to be moved actually existed before attempting the mv.

If your interest, like Tom's, is to only move if the file doesn't already exist, I think we should still integrate Bruce's check into the mix:

- name: stat foo
  stat: path=/path/to/foo
  register: foo_stat

- name: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar
  when: foo_stat.stat.exists

Stripping everything but alphanumeric chars from a string in Python

Regular expressions to the rescue:

import re
re.sub(r'\W+', '', your_string)

By Python definition '\W == [^a-zA-Z0-9_], which excludes all numbers, letters and _

How to clear gradle cache?

Gradle cache is located at

  • On Windows: %USERPROFILE%\.gradle\caches
  • On Mac / UNIX: ~/.gradle/caches/

You can browse to these directory and manually delete it or run

rm -rf $HOME/.gradle/caches/

on UNIX system. Run this command will also force to download dependencies.


UPDATE

Clear the Android build cache of current project

NOTE: Android Studio's File > Invalidate Caches / Restart doesn't clear the Android build cache, so you'll have to clean it separately.

On Windows:

gradlew cleanBuildCache

On Mac or UNIX:

./gradlew cleanBuildCache

Add image in pdf using jspdf

For result in base64, before convert to canvas:

var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });

Automatically scroll down chat div

What you need to do is divide it into two divs. One with overflow set to scroll, and an inner one to hold the text so you can get it's outersize.

<div id="chatdiv">
    <div id="textdiv"/>
</div>

textdiv.html("");
$.each(chatMessages, function (i, e) {
    textdiv.append("<span>" + e + "</span><br/>");
});
chatdiv.scrollTop(textdiv.outerHeight());

You can check out a jsfiddle here: http://jsfiddle.net/xj5c3jcn/1/

Obviously you don't want to rebuild the whole text div each time, so take that with a grain of salt - just an example.

Rename a file in C#

public static class ImageRename
{
    public static void ApplyChanges(string fileUrl,
                                    string temporaryImageName,
                                    string permanentImageName)
    {
        var currentFileName = Path.Combine(fileUrl,
                                           temporaryImageName);

        if (!File.Exists(currentFileName))
            throw new FileNotFoundException();

        var extention = Path.GetExtension(temporaryImageName);
        var newFileName = Path.Combine(fileUrl,
                                       $"{permanentImageName}
                                         {extention}");

        if (File.Exists(newFileName))
            File.Delete(newFileName);

        File.Move(currentFileName, newFileName);
    }
}

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012

Select N random elements from a List<T> in C#

Using linq:

YourList.OrderBy(x => rnd.Next()).Take(5)

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

A potentially trivial solution to this is to switch to using multiprocessing.dummy. This is a thread based implementation of the multiprocessing interface that doesn't seem to have this problem in Python 2.7. I don't have a lot of experience here, but this quick import change allowed me to call apply_async on a class method.

A few good resources on multiprocessing.dummy:

https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy

http://chriskiehl.com/article/parallelism-in-one-line/

How do you do a deep copy of an object in .NET?

Maybe you only need a shallow copy, in that case use Object.MemberWiseClone().

There are good recommendations in the documentation for MemberWiseClone() for strategies to deep copy: -

http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx

How to initialize a nested struct?

You need to redefine the unnamed struct during &Configuration{}

package main

import "fmt"

type Configuration struct {
    Val   string
    Proxy struct {
        Address string
        Port    string
    }
}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: struct {
            Address string
            Port    string
        }{
            Address: "127.0.0.1",
            Port:    "8080",
        },
    }
    fmt.Println(c)
}

https://play.golang.org/p/Fv5QYylFGAY

Download single files from GitHub

This would definitely work. At least in Chrome. Right click on the "Raw" icon -> Save Link As.

Can you autoplay HTML5 videos on the iPad?

iOS 10 update

The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).

To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/

iOS 9 and before

As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.

My assumption as to why they've disabled the auto-play feature?

Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.


After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:

"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.

In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.

Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:

Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.


What this means (in terms of code) is that Javascript's play() and load() methods are inactive until the user initiates playback, unless the play() or load() method is triggered by user action (e.g. a click event).

Basically, a user-initiated play button works, but an onLoad="play()" event does not.

For example, this would play the movie:

<input type="button" value="Play" onclick="document.myMovie.play()">

Whereas the following would do nothing on iOS:

<body onload="document.myMovie.play()">

PHP - Redirect and send data via POST

I used the following code to capture POST data that was submitted from form.php and then concatenate it onto a URL to send it BACK to the form for validation corrections. Works like a charm, and in effect converts POST data into GET data.

foreach($_POST as $key => $value) {
   $urlArray[] =  $key."=".$value;  
}
$urlString = implode("&", $urlArray);

echo "Please <a href='form.php?".$urlString."'>go back</a>";

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

CentOS: Enabling GD Support in PHP Installation

For PHP7 on CentOS or EC2 Linux AMI:

sudo yum install php70-gd

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

Then

list1 + list2

Is the same as

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

Which evaluates to

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Much like

"abdcde" + "fghijk"

Produces

"abdcdefghijk"

Simulating ENTER keypress in bash script

You might find the yes command useful.

See man yes

codeigniter model error: Undefined property

You have to load the db library first. In autoload.php add :

$autoload['libraries'] = array('database');

Also, try renaming User model class for "User_model".

Initializing array of structures

There are only two syntaxes at play here.

  1. Plain old array initialisation:

    int x[] = {0, 0}; // x[0] = 0, x[1] = 0
    
  2. A designated initialiser. See the accepted answer to this question: How to initialize a struct in accordance with C programming language standards

    The syntax is pretty self-explanatory though. You can initialise like this:

    struct X {
        int a;
        int b;
    }
    struct X foo = { 0, 1 }; // a = 0, b = 1
    

    or to use any ordering,

    struct X foo = { .b = 0, .a = 1 }; // a = 1, b = 0
    

adding multiple entries to a HashMap at once in one statement

Maps have also had factory methods added in Java 9. For up to 10 entries Maps have overloaded constructors that take pairs of keys and values. For example we could build a map of various cities and their populations (according to google in October 2016) as follow:

Map<String, Integer> cities = Map.of("Brussels", 1_139000, "Cardiff", 341_000);

The var-args case for Map is a little bit harder, you need to have both keys and values, but in Java, methods can’t have two var-args parameters. So the general case is handled by taking a var-args method of Map.Entry<K, V> objects and adding a static entry() method that constructs them. For example:

Map<String, Integer> cities = Map.ofEntries(
    entry("Brussels", 1139000), 
    entry("Cardiff", 341000)
);

Collection Factory Methods in Java 9

not finding android sdk (Unity)

Linux Users:

cp -r Android AndroidUnity
cd AndroidUnity/Sdk
rm -rf tools
wget http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip
unzip tools_r25.2.5-windows.zip

In Unity preferences change to this newly created sdk folder.

How do I format XML in Notepad++?

OK, here is how I did it in Notepad++:

  • Plugins
  • Plugin manager
  • Show plugin manager
  • Check XML tools
  • Install
  • Restart Notepad++
  • Open XML file
  • Plugins
  • XML tools
  • Pretty print (XML only -- with line breaks)

Ruby: character to ascii from a string

use "x".ord for a single character or "xyz".sum for a whole string.

Escape a string in SQL Server so that it is safe to use in LIKE expression

Do you want to look for strings that include an escape character? For instance you want this:

select * from table where myfield like '%10%%'.

Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.

select * from table where myfield like '%10!%%' ESCAPE '!'

Is there a way to create key-value pairs in Bash script?

For persistent key/value storage, you can use kv-bash, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash

Usage

git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash

Try create some permanent variables

kvset myName  xyz
kvset myEmail [email protected]

#read the varible
kvget myEmail

#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

If you want 8 bit representation of characters that used in many encoding, this may help you.

You must change variable targetEncoding to whatever encoding you want.

Encoding targetEncoding = Encoding.GetEncoding(874); // Your target encoding
Encoding utf8 = Encoding.UTF8;

var stringBytes = utf8.GetBytes(Name);
var stringTargetBytes = Encoding.Convert(utf8, targetEncoding, stringBytes);
var ascii8BitRepresentAsCsString = Encoding.GetEncoding("Latin1").GetString(stringTargetBytes);

Add st, nd, rd and th (ordinal) suffix to a number

Here's a slightly different approach (I don't think the other answers do this). I'm not sure whether I love it or hate it, but it works!

export function addDaySuffix(day: number) { 
  const suffixes =
      '  stndrdthththththththththththththththththstndrdthththththththst';
    const startIndex = day * 2;

    return `${day}${suffixes.substring(startIndex, startIndex + 2)}`;
  }

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

conda-env now does this automatically (if pip was installed with conda).

You can see how this works by using the export tool used for migrating an environment:

conda env export -n <env-name> > environment.yml

The file will list both conda packages and pip packages:

name: stats
channels:
  - javascript
dependencies:
  - python=3.4
  - bokeh=0.9.2
  - numpy=1.9.*
  - nodejs=0.10.*
  - flask
  - pip:
    - Flask-Testing

If you're looking to follow through with exporting the environment, move environment.yml to the new host machine and run:

conda env create -f path/to/environment.yml

How to use activity indicator view on iPhone?

in regards to:

Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.

note that if you do utilise this code you MUST provide ALL the sourcecode to your own application to any user that requests it. You need to be aware that they may decide to repackage your code and sell it on the store themselves. This is all provided for under the terms of the GNU General Public License (GPL).

If you don't want to be forced into opening your sourcecode then you cannot use anything from the wordpress iphone application including the, referenced activity progress window, without forcing the GPL to apply to your own.

Does hosts file exist on the iPhone? How to change it?

It might exist, but you cannot change it on a non-jailbreaked iPhone.

Assuming that your development webserver is on a Mac, why don't you simply use its Bonjour name (e.g. MyMac.local.) instead of myrealwebserverontheinternet.com?

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

The requested resource does not support HTTP method 'GET'

Resolved this issue by using http(s) when accessing the endpoint. The route I was accessing was not available over http. So I would say verify the protocols for which the route is available.

Set adb vendor keys

I tried almost anything but no help...

Everytime was just this

?  ~ adb devices    
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e    unauthorized

However I've managed to connect device!

There is tutor, step by step.

  1. Remove existing adb keys on PC:

$ rm -v .android/adbkey* .android/adbkey .android/adbkey.pub

  1. Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys

  2. Now create new adb keypair

? ~ adb keygen .android/adbkey adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey' adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'

  1. Manually copy from PC .android/adbkey.pub (pubkic key) to Device on path /data/misc/adb/adb_keys

  2. Reboot device and check adb devices :

? ~ adb devices List of devices attached aeef5e4e device

Permissions of /data/misc/adb/adb_keys are (766/-rwxrw-rw-) on my device

What does "publicPath" in Webpack do?

publicPath is used by webpack for the replacing relative path defined in your css for refering image and font file.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

To install PDT (PHP Development Tools) for PHP development environment is better in Eclipse. The following are the steps to install PDT in Eclipse (I'm considering version 3.7 (Indigo)):

  1. Open Eclipse (in my case Eclipse Indigo).
  2. Go to Help --> Install New Software...
  3. Expand the "Work with" drop down and select "Indigo - http://download.eclipse.org/releases/indigo".
  4. Expand "Programming Languages" from the list.
  5. Check PHP Development Tools (PDT) SDK Feature.
  6. Click "Next >" at the bottom and follow the further instruction of Eclipse.
  7. After successful installation of PDT: Go to Window --> Preferences and see the list as PHP at left panel.

Eclipse IDE: How to zoom in on text?

To zoom on Eclipse you can use : CTRL SHIFT + OR -

Javascript : get <img> src and set as variable?

Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

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

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>

Launch programs whose path contains spaces

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("firefox")
Set objShell = Nothing

Please try this

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

It seems easy for me that use plt.savefig() function after plot() function:

import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

You can convert a string to a date easily by:

CAST(YourDate AS DATE)

jQuery if statement to check visibility

You can use .is(':visible') to test if something is visible and .is(':hidden') to test for the opposite:

$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));

Reference:

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:

fig, ax = plt.subplots()

is more concise than this:

fig = plt.figure()
ax = fig.add_subplot(111)

IP to Location using Javascript

It's quite easy with an API that maps IP address to location. Run the snippet to get city & country for the IP in the input box.

_x000D_
_x000D_
$('.send').on('click', function(){_x000D_
_x000D_
  $.getJSON('https://ipapi.co/'+$('.ip').val()+'/json', function(data){_x000D_
      $('.city').text(data.city);_x000D_
      $('.country').text(data.country);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input class="ip" value="8.8.8.8">_x000D_
<button class="send">Go</button>_x000D_
<br><br>_x000D_
<span class="city"></span>, _x000D_
<span class="country"></span>
_x000D_
_x000D_
_x000D_

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.

startActivity(new Intent(this,your-new-screen.class));
finishAffinity();

The finishAffinity(); method clears back button stack.

Laravel $q->where() between dates

Edited: Kindly note that
whereBetween('date',$start_date,$end_date)
is inclusive of the first date.

regex with space and letters only?

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this http://tools.netshiftmedia.com

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

What does __FILE__ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir anywhere else in your application, this path will expand incorrectly.

puts __FILE__
Dir.chdir '../../'
puts __FILE__

One workaround to this problem is to store the expanded value of __FILE__ outside of any application code. As long as your require statements are at the top of your definitions (or at least before any calls to Dir.chdir), this value will continue to be useful after changing directories.

$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))

# open class and do some stuff that changes directory

puts $MY_FILE_PATH

How to change permissions for a folder and its subfolders/files in one step?

The correct recursive command is:

sudo chmod -R 755 /opt/lampp/htdocs

-R: change every sub folder including the current folder

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

How can I dynamically add a directive in AngularJS?

Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

Important: Register the directives that you want to use with restrict: 'C'. Like this:

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

You can use like this:

<stroman class="my-directive other-class" randomProperty="8"></stroman>

To get this:

<div class="my-directive other-class" randomProperty="8">Hi there</div>

Protip. If you don't want to use directives based on classes then you can change '<div></div>' to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class.

How to redirect a page using onclick event in php?

Please try this

    <input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />

window.location.href example:

 window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

     window.open('http://www.google.com'); //This will open Google in a new window.

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

AngularJS ng-click stopPropagation

<ul class="col col-double clearfix">
 <li class="col__item" ng-repeat="location in searchLocations">
   <label>
    <input type="checkbox" ng-click="onLocationSelectionClicked($event)" checklist-model="selectedAuctions.locations" checklist-value="location.code" checklist-change="auctionSelectionChanged()" id="{{location.code}}"> {{location.displayName}}
   </label>



$scope.onLocationSelectionClicked = function($event) {
      if($scope.limitSelectionCountTo &&         $scope.selectedAuctions.locations.length == $scope.limitSelectionCountTo) {
         $event.currentTarget.checked=false;
      }
   };

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

Visual Studio loading symbols

Debug -> Delete All Breakpoints ( http://darrinbishop.com/blog/2010/06/sharepoint-2010-hangs-after-visual-studio-2010-f5-debugging ) After that you can use them again, but do it once. It will remove some kind of "invalid" breakpoints too and then loading symbols will be fast again. I was chasing this issue for days :(.

Getting selected value of a combobox

Try this:

private void cmbLineColor_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataRowView drv = (DataRowView)cmbLineColor.SelectedItem;
        int selectedValue = (int)drv.Row.ItemArray[1];
    }

What is a segmentation fault?

To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.

They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are

  1. Used before being properly initialised
  2. Used after the memory they point to has been realloced or deleted.
  3. Used in an indexed array where the index is outside of the array bounds. This is generally only when you're doing pointer math on traditional arrays or c-strings, not STL / Boost based collections (in C++.)

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Difference between WebStorm and PHPStorm

PhpStorm supports all the features of WebStorm but some are not bundled so you might need to install the corresponding plugin for some framework via Settings > Plugins > Install JetBrains Plugin.

Official comment - jetbrains.com

range() for floats

A solution without numpy etc dependencies was provided by kichik but due to the floating point arithmetics, it often behaves unexpectedly. As noted by me and blubberdiblub, additional elements easily sneak into the result. For example naive_frange(0.0, 1.0, 0.1) would yield 0.999... as its last value and thus yield 11 values in total.

A robust version is provided here:

def frange(x, y, jump=1.0):
    '''Range for floats.'''
    i = 0.0
    x = float(x)  # Prevent yielding integers.
    x0 = x
    epsilon = jump / 2.0
    yield x  # yield always first value
    while x + epsilon < y:
        i += 1.0
        x = x0 + i * jump
        yield x

Because the multiplication, the rounding errors do not accumulate. The use of epsilon takes care of possible rounding error of the multiplication, even though issues of course might rise in the very small and very large ends. Now, as expected:

> a = list(frange(0.0, 1.0, 0.1))
> a[-1]
0.9
> len(a)
10

And with somewhat larger numbers:

> b = list(frange(0.0, 1000000.0, 0.1))
> b[-1]
999999.9
> len(b)
10000000

The code is also available as a GitHub Gist.

How do I add a submodule to a sub-directory?

Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.

 cd ~/.janus/snipmate-snippets
 git submodule add <git@github ...> snippets

(Bouke Versteegh comments that you don't have to use /., as in snippets/.: snippets is enough)

See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:

submodule: drop the top-level requirement

Use the new rev-parse --prefix option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.

Since the interpretation of a relative submodule URL depends on whether or not "remote.origin.url" is configured, explicitly block relative URLs in "git submodule add" when not at the top level of the working tree.

Signed-off-by: John Keeping

Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f

This makes 'git rev-parse' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.

This is useful for shell scripts where we may want to cd to the top of the working tree but need to handle relative paths given by the user on the command line.

How can I selectively escape percent (%) in Python strings?

I have tried different methods to print a subplot title, look how they work. It's different when i use Latex.

It works with '%%' and 'string'+'%' in a typical case.

If you use Latex it worked using 'string'+'\%'

So in a typical case:

import matplotlib.pyplot as plt
fig,ax = plt.subplots(4,1)
float_number = 4.17
ax[0].set_title('Total: (%1.2f' %float_number + '\%)')
ax[1].set_title('Total: (%1.2f%%)' %float_number)
ax[2].set_title('Total: (%1.2f' %float_number + '%%)')
ax[3].set_title('Total: (%1.2f' %float_number + '%)')

Title examples with %

If we use latex:

import matplotlib.pyplot as plt
import matplotlib
font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 12}
matplotlib.rc('font', **font)
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.unicode'] = True
fig,ax = plt.subplots(4,1)
float_number = 4.17
#ax[0].set_title('Total: (%1.2f\%)' %float_number) This makes python crash
ax[1].set_title('Total: (%1.2f%%)' %float_number)
ax[2].set_title('Total: (%1.2f' %float_number + '%%)')
ax[3].set_title('Total: (%1.2f' %float_number + '\%)')

We get this: Title example with % and latex

jQuery count child elements

It is simply possible with childElementCount in pure javascript

_x000D_
_x000D_
var countItems = document.getElementsByTagName("ul")[0].childElementCount;_x000D_
console.log(countItems);
_x000D_
<div id="selected">_x000D_
  <ul>_x000D_
    <li>29</li>_x000D_
    <li>16</li>_x000D_
    <li>5</li>_x000D_
    <li>8</li>_x000D_
    <li>10</li>_x000D_
    <li>7</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java: export to an .jar file in eclipse

FatJar can help you in this case.

In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects

This is useful if your final exported jar includes other external jars.

If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.

After Ganymede, you have:

Export Jar

How to correctly assign a new string value?

Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

But you can call functions to help achieve what you want.

The strncpy() function could be used here. For maximum safety I suggest following this pattern:

strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case

Also have a look at the strncat() and memcpy() functions.

How to print formatted BigDecimal values?

 BigDecimal pi = new BigDecimal(3.14);
 BigDecimal pi4 = new BigDecimal(12.56);

 System.out.printf("%.2f",pi);

// prints 3.14

System.out.printf("%.0f",pi4);

// prints 13

PostgreSQL Error: Relation already exists

You cannot create a table with a name that is identical to an existing table or view in the cluster. To modify an existing table, use ALTER TABLE (link), or to drop all data currently in the table and create an empty table with the desired schema, issue DROP TABLE before CREATE TABLE.

It could be that the sequence you are creating is the culprit. In PostgreSQL, sequences are implemented as a table with a particular set of columns. If you already have the sequence defined, you should probably skip creating it. Unfortunately, there's no equivalent in CREATE SEQUENCE to the IF NOT EXISTS construct available in CREATE TABLE. By the looks of it, you might be creating your schema unconditionally, anyways, so it's reasonable to use

DROP TABLE IF EXISTS csd_relationship;
DROP SEQUENCE IF EXISTS csd_relationship_csd_relationship_id_seq;

before the rest of your schema update; In case it isn't obvious, This will delete all of the data in the csd_relationship table, if there is any

Force IE8 Into IE7 Compatiblity Mode

There is an HTTP header you can set that will force IE8 to use IE7-compatibility mode.

Get url without querystring

Request.RawUrl.Split('?')[0]

Just for url name only !!