Programs & Examples On #Datagridtextcolumn

Represents a DataGrid column that hosts textual content in its cells.

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Date formatting in WPF datagrid

If your bound property is DateTime, then all you need is

Binding={Property, StringFormat=d}

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The correct solution seems to be:

<Window.Resources>
    <CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
    <DataGridComboBoxColumn Header="Column With Predefined Values"
                            ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
                            SelectedValueBinding="{Binding MyItemId}"
                            SelectedValuePath="Id"
                            DisplayMemberPath="StatusCode" />
</DataGrid>

The layout above works perfectly fine for me, and should work for others. This design choice also makes sense, though it isn't very well explained anywhere. But if you have a data column with predefined values, those values typically don't change during run-time. So creating a CollectionViewSource and initializing the data once makes sense. It also gets rid of the longer bindings to find an ancestor and bind on it's data context (which always felt wrong to me).

I am leaving this here for anyone else who struggled with this binding, and wondered if there was a better way (As this page is obviously still coming up in search results, that's how I got here).

DataGrid get selected rows' column values

I used a similar way to solve this problem using the animescm sugestion, indeed we can obtain the specific cells values from a group of selected cells using an auxiliar list:

private void dataGridCase_SelectionChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach (var item in e.AddedCells)
        {
            var col = item.Column as DataGridColumn;
            var fc = col.GetCellContent(item.Item);
            lstTxns.Items.Add((fc as TextBlock).Text);
        }
    }

How do I bind a List<CustomObject> to a WPF DataGrid?

if you do not expect that your list will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource this property in WPF is usually named ItemsSource):

this.dataGrid1.ItemsSource = list;

But if you would like to replace your list with new collection instance then you should consider using databinding.

How do I bind a WPF DataGrid to a variable number of columns?

You might be able to do this with AutoGenerateColumns and a DataTemplate. I'm not positive if it would work without a lot of work, you would have to play around with it. Honestly if you have a working solution already I wouldn't make the change just yet unless there's a big reason. The DataGrid control is getting very good but it still needs some work (and I have a lot of learning left to do) to be able to do dynamic tasks like this easily.

How to make an unaware datetime timezone aware in python

Python 3.9 adds the zoneinfo module so now only the standard library is needed!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

Attach a timezone:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

Attach the system's local timezone:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

Subsequently it is properly converted to other timezones:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

Wikipedia list of available time zones


Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use of zoneinfo in Python 3.6 to 3.8:

pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

sending email via php mail function goes to spam

Try changing your headers to this:

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: [email protected]" . "\r\n" .
"Reply-To: [email protected]" . "\r\n" .
"X-Mailer: PHP/" . phpversion();

For a few reasons.

  • One of which is the need of a Reply-To and,

  • The use of apostrophes instead of double-quotes. Those two things in my experience with forms, is usually what triggers a message ending up in the Spam box.

You could also try changing the $from to:

$from = "[email protected]";


EDIT:

See these links I found on the subject https://stackoverflow.com/a/9988544/1415724 and https://stackoverflow.com/a/16717647/1415724 and https://stackoverflow.com/a/9899837/1415724

https://stackoverflow.com/a/5944155/1415724 and https://stackoverflow.com/a/6532320/1415724

  • Try using the SMTP server of your ISP.

    Using this apparently worked for many: X-MSMail-Priority: High

http://www.webhostingtalk.com/showthread.php?t=931932

"My host helped me to enable DomainKeys and SPF Records on my domain and now when I send a test message to my Hotmail address it doesn't end up in Junk. It was actually really easy to enable these settings in cPanel under Email Authentication. I can't believe I never saw that before. It only works with sending through SMTP using phpmailer by the way. Any other way it still is marked as spam."

PHPmailer sending mail to spam in hotmail. how to fix http://pastebin.com/QdQUrfax

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

How to display the current time and date in C#

In WPF you'll need to use the Content property instead:

label1.Content = DateTime.Now.ToString();

Environment variables for java installation

Java SE Development Kit 8u112 on a 64-bit Windows 7 or Windows 8

Set the following user environment variables (== environment variables of type user variables)

  • JAVA_HOME : C:\Program Files\Java\jdk1.8.0_112
  • JDK_HOME : %JAVA_HOME%
  • JRE_HOME : %JAVA_HOME%\jre
  • CLASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
  • PATH : your-unique-entries;%JAVA_HOME%\bin (make sure that the longish your-unique-entries does not contain any other references to another Java installation folder.

Note for Windows users on 64-bit systems:

Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'

Notice that these environment variables are derived from the "root" environment variable JAVA_HOME. This makes it easy to update your environment variables when updating the JDK. Just point JAVA_HOME to the fresh installation.

There is a blogpost explaining the rationale behind all these environment variables.

Optional recommendations

  • Add an user environment variable JAVA_TOOL_OPTIONS with value -Dfile.encoding="UTF-8". This ensures that Java (and tools such as Maven) will run with a Charset.defaultCharset() of UTF-8 (instead of the default Windows-1252). This has saved a lot of headaches when wirking with my own code and that of others, which unfortunately often assume the (sane) default encoding UTF-8.
  • When JDK is installed, it adds to the system environment variable Path an entry C:\ProgramData\Oracle\Java\javapath;. I anecdotally noticed that the links in that directory didn't get updated during an JDK installation update. So it's best to remove C:\ProgramData\Oracle\Java\javapath; from the Path system environment variable in order to have a consistent environment.

Java array assignment (multiple values)

Yes:

float[] values = {0.1f, 0.2f, 0.3f};

This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:

values = new float[3];

or

values = new float[] {0.1f, 0.2f, 0.3f};

Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

Kendo grid is good as well as Wijmo. I know Kendo comes with Angular bindings for their datasource and I think Wijmo has an Angular plugin. Neither are free though.

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Installing framework 4.0 redistributable is also enough to create application pool. You can download it from here.

How to replace a hash key with another key

you can do

hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}

This should work for your case!

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

using windows 10

I was facing issue .. then I removed JAVA_HOME variable completly and just added %JAVA_HOME%\bin in PATH then it worked!!! for mee

‘ant’ is not recognized as an internal or external command

I had a similar issue, but the reason that %ANT_HOME% wasn't resolving is that I had added it as a USER variable, not a SYSTEM one. Sorted now, thanks to this post.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

I'm aware this is quite old but I just had the same problem with Visual Studio 2010 all patched up so others may still run into this.

Adding my project path to "Exluded Items" in my AVG anti-virus settings appears to have fixed the problem for me.

Try disabling any anti-virus/resident shield and see if it fixes the problem. If so, add your project path to excluded directories in your AV config.

How can I generate random alphanumeric strings?

I don't know how cryptographically sound this is, but it's more readable and concise than the more intricate solutions by far (imo), and it should be more "random" than System.Random-based solutions.

return alphabet
    .OrderBy(c => Guid.NewGuid())
    .Take(strLength)
    .Aggregate(
        new StringBuilder(),
        (builder, c) => builder.Append(c))
    .ToString();

I can't decide if I think this version or the next one is "prettier", but they give the exact same results:

return new string(alphabet
    .OrderBy(o => Guid.NewGuid())
    .Take(strLength)
    .ToArray());

Granted, it isn't optimized for speed, so if it's mission critical to generate millions of random strings every second, try another one!

NOTE: This solution doesn't allow for repetitions of symbols in the alphabet, and the alphabet MUST be of equal or greater size than the output string, making this approach less desirable in some circumstances, it all depends on your use-case.

How to add property to object in PHP >= 5.3 strict mode without generating error

Do it like this:

$foo = new stdClass();
$foo->{"bar"} = '1234';

now try:

echo $foo->bar; // should display 1234

Python BeautifulSoup extract text between element

soup = BeautifulSoup(html)
for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
  hit = hit.text.strip()
  print hit

This will print: THIS IS MY TEXT Try this..

Apache won't start in wamp

My solution was that 2 .dll files(msvcp110.dll, msvcr110.dll) were missing from the directory : C:\wamp\bin\apache\apache2.4.9\bin So I copied these 2 files to all these locations just in case and restarted wamp it worked C:\wamp C:\wamp\bin\apache\apache2.4.9\bin C:\wamp\bin\apache\apache2.4.9 C:\wamp\bin\mysql\mysql5.6.17 C:\wamp\bin\php\php5.5.12

I hope this helps someone out.

Angular: How to update queryParams without changing route

I ended up combining urlTree with location.go

const urlTree = this.router.createUrlTree([], {
       relativeTo: this.route,
       queryParams: {
           newParam: myNewParam,
       },
       queryParamsHandling: 'merge',
    });

    this.location.go(urlTree.toString());

Not sure if toString can cause problems, but unfortunately location.go, seems to be string based.

convert nan value to zero

You could use np.where to find where you have NaN:

import numpy as np

a = np.array([[   0,   43,   67,    0,   38],
              [ 100,   86,   96,  100,   94],
              [  76,   79,   83,   89,   56],
              [  88,   np.nan,   67,   89,   81],
              [  94,   79,   67,   89,   69],
              [  88,   79,   58,   72,   63],
              [  76,   79,   71,   67,   56],
              [  71,   71,   np.nan,   56,  100]])

b = np.where(np.isnan(a), 0, a)

In [20]: b
Out[20]: 
array([[   0.,   43.,   67.,    0.,   38.],
       [ 100.,   86.,   96.,  100.,   94.],
       [  76.,   79.,   83.,   89.,   56.],
       [  88.,    0.,   67.,   89.,   81.],
       [  94.,   79.,   67.,   89.,   69.],
       [  88.,   79.,   58.,   72.,   63.],
       [  76.,   79.,   71.,   67.,   56.],
       [  71.,   71.,    0.,   56.,  100.]])

How does the bitwise complement operator (~ tilde) work?

The bit-wise operator is a unary operator which works on sign and magnitude method as per my experience and knowledge.

For example ~2 would result in -3.

This is because the bit-wise operator would first represent the number in sign and magnitude which is 0000 0010 (8 bit operator) where the MSB is the sign bit.

Then later it would take the negative number of 2 which is -2.

-2 is represented as 1000 0010 (8 bit operator) in sign and magnitude.

Later it adds a 1 to the LSB (1000 0010 + 1) which gives you 1000 0011.

Which is -3.

How to calculate Date difference in Hive

datediff(to_date(String timestamp), to_date(String timestamp))

For example:

SELECT datediff(to_date('2019-08-03'), to_date('2019-08-01')) <= 2;

Using os.walk() to recursively traverse directories in Python

Would be the best way

def traverse_dir_recur(dir):
    import os
    l = os.listdir(dir)
    for d in l:
        if os.path.isdir(dir + d):
            traverse_dir_recur(dir+  d +"/")
        else:
            print(dir + d)

How do I add a resources folder to my Java project in Eclipse

To answer your question posted in the title of this topic...

Step 1--> Right Click on Java Project, Select the option "Properties" Step 1--> Right Click on Java Project, Select the option "Properties"

Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder" Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window Click the option "Create New Folder..." available at the bottom of the window

Step 4--> Enter the name of the new folder as "resources" and then click "Finish" Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project
Now you should be able to see the new folder "resources" under your java project

@Nullable annotation usage

Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

Command-line tool for finding out who is locking a file

Handle didn't find that WhatsApp is holding lock on a file .tmp.node in temp folder. ProcessExplorer - Find works better Look at this answer https://superuser.com/a/399660

Hash table runtime complexity (insert, search and delete)

Some hash tables (cuckoo hashing) have guaranteed O(1) lookup

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Java "user.dir" property - what exactly does it mean?

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

SVG drop shadow using css3

I'm not aware of a CSS-only solution.

As you mentioned, filters are the canonical approach to creating drop shadow effects in SVG. The SVG specification includes an example of this.

What does the [Flags] Enum Attribute mean in C#?

You can also do this

[Flags]
public enum MyEnum
{
    None   = 0,
    First  = 1 << 0,
    Second = 1 << 1,
    Third  = 1 << 2,
    Fourth = 1 << 3
}

I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time

How to return a table from a Stored Procedure?

It's VERY important to include:

 SET NOCOUNT ON;

into SP, In First line, if you do INSERT in SP, the END SELECT can't return values.

THEN, in vb60 you can:

SET RS = CN.EXECUTE(SQL)

OR:

RS.OPEN CN, RS, SQL

AngularJS: How to make angular load script inside ng-include?

I tried neemzy's approach, but it didn't work for me using 1.2.0-rc.3. The script tag would be inserted into the DOM, but the javascript path would not be loaded. I suspect it was because the javascript i was trying to load was from a different domain/protocol. So I took a different approach, and this is what I came up with, using google maps as an example: (Gist)

angular.module('testApp', []).
    directive('lazyLoad', ['$window', '$q', function ($window, $q) {
        function load_script() {
            var s = document.createElement('script'); // use global document since Angular's $document is weak
            s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
            document.body.appendChild(s);
        }
        function lazyLoadApi(key) {
            var deferred = $q.defer();
            $window.initialize = function () {
                deferred.resolve();
            };
            // thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
            if ($window.attachEvent) {  
                $window.attachEvent('onload', load_script); 
            } else {
                $window.addEventListener('load', load_script, false);
            }
            return deferred.promise;
        }
        return {
            restrict: 'E',
            link: function (scope, element, attrs) { // function content is optional
            // in this example, it shows how and when the promises are resolved
                if ($window.google && $window.google.maps) {
                    console.log('gmaps already loaded');
                } else {
                    lazyLoadApi().then(function () {
                        console.log('promise resolved');
                        if ($window.google && $window.google.maps) {
                            console.log('gmaps loaded');
                        } else {
                            console.log('gmaps not loaded');
                        }
                    }, function () {
                        console.log('promise rejected');
                    });
                }
            }
        };
    }]);

I hope it's helpful for someone.

Is there a way to programmatically minimize a window

Form myForm;
myForm.WindowState = FormWindowState.Minimized;

Set a:hover based on class

One common error is leaving a space before the class names. Even if this was the correct syntax:

.menu a:hover .main-nav-item

it never would have worked.

Therefore, you would not write

.menu a .main-nav-item:hover

it would be

.menu a.main-nav-item:hover

System.Timers.Timer vs System.Threading.Timer

The two classes are functionally equivalent, except that System.Timers.Timer has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.

When you drag a System.Timers.Timer onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.

How to get access to raw resources that I put in res folder?

For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.

How do I delete an exported environment variable?

unset is the command you're looking for.

unset GNUPLOT_DRIVER_DIR

Replace whitespace with a comma in a text file in Linux

If you want to replace an arbitrary sequence of blank characters (tab, space) with one comma, use the following:

sed 's/[\t ]+/,/g' input_file > output_file

or

sed -r 's/[[:blank:]]+/,/g' input_file > output_file

If some of your input lines include leading space characters which are redundant and don't need to be converted to commas, then first you need to get rid of them, and then convert the remaining blank characters to commas. For such case, use the following:

sed 's/ +//' input_file | sed 's/[\t ]+/,/g' > output_file

Python MYSQL update statement

It should be:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

You can also do it with basic string manipulation,

cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))

but this way is discouraged because it leaves you open for SQL Injection. As it's so easy (and similar) to do it the right waytm. Do it correctly.

The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).

Connection string with relative path to the database file

This worked for me:

string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
    + HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
    + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";

I'm querying an XLSX file so don't worry about any of the other stuff in the connection string but the Data Source.

So my answer is:

HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")

Can't append <script> element

This works:

$('body').append($("<script>alert('Hi!');<\/script>")[0]);

It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.

VBA - Select columns using numbers?

Columns("A:E").Select

Can be directly replaced by

Columns(1).Resize(, 5).EntireColumn.Select

Where 1 can be replaced by a variable

n = 5
Columns(n).Resize(, n+4).EntireColumn.Select

In my opinion you are best dealing with a block of columns rather than looping through columns n to n + 4 as it is more efficient.

In addition, using select will slow your code down. So instead of selecting your columns and then performing an action on the selection try instead to perform the action directly. Below is an example to change the colour of columns A-E to yellow.

Columns(1).Resize(, 5).EntireColumn.Interior.Color = 65535

Git's famous "ERROR: Permission to .git denied to user"

I had the same problem as you. After a long time spent Googling, I found out my error was caused by multiple users that had added the same key in their accounts.

So, here is my solution: delete the wrong-user's ssh-key (I can do it because the wrong-user is also my account). If the wrong-user isn't your account, you may need to change your ssh-key, but I don't think this gonna happen.

And I think your problem may be caused by a mistyping error in your accounts name.

Unable to find valid certification path to requested target - error even after cert imported

My problem was that a Cloud Access Security Broker, NetSkope, was installed on my work laptop through a software update. This was altering the certificate chain and I was still not able to connect to the server through my java client after importing the entire chain to my cacerts keystore. I disabled NetSkope and was able to successfully connect.

Is there a way to create and run javascript in Chrome?

Usually one uses text editor to create source files (like JavaScript). I use VisualStudio which have intellisence supprt for JavaScript, but any other editor will do (vim or notepad on Windows are both fine).

To run JavaScript by itself you need something that can do that. I.e. on Windows you can directly run script from console using CScript script.js command. There are other ways to run JavaScript on Windows and other OS.

Browsers (like Chrome) do not run JavaScript by itself, only as part of a page or extensions. It is unclear what one would expect of browser to do with JavaScript by itself.

Javascript Regex: How to put a variable inside a regular expression?

Here's an pretty useless function that return values wrapped by specific characters. :)

jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/

function getValsWrappedIn(str,c1,c2){
    var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g"); 
    return str.match(rg);
    }

var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results =  getValsWrappedIn(exampleStr,"(",")")

// Will return array ["5","19","thingy"]
console.log(results)

Is there any way to install Composer globally on Windows?

Start > Computer : Properties > Change Settings > Advanced > Environment Variables > PATH : Edit [add this string (without "") at the end of line ";C:\<path to php folder>\php5.5.3"].. open cmd and type composer thats it :-)

Why shouldn't I use "Hungarian Notation"?

I've always thought that a prefix or two in the right place wouldn't hurt. I think if I can impart something useful, like "Hey this is an interface, don't count on specific behaviour" right there, as in IEnumerable, I oughtta do it. Comment can clutter things up much more than just a one or two character symbol.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

How to change MySQL timezone in a database connection using Java?

Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone.

Flex-box: Align last row to grid

Assuming:

  • You want 4 column grid layout with wrapping
  • The number of items is not necessarily a multiple of 4

Set a left margin on every item except 1st, 5th and 9th item and so on. If the left margin is 10px then each row will have 30px margin distributed among 4 items. The percentage width for item is calculated as follows:

100% / 4 - horizontal-border - horizontal-padding - left-margin * (4 - 1) / 4

This is a decent workaround for issues involving last row of flexbox.

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-wrap: wrap;_x000D_
  margin: 1em 0 3em;_x000D_
  background-color: peachpuff;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  margin-left: 10px;_x000D_
  border: 1px solid;_x000D_
  padding: 10px;_x000D_
  width: calc(100% / 4 - 2px - 20px - 10px * (4 - 1) / 4);_x000D_
  background-color: papayawhip;_x000D_
}_x000D_
_x000D_
.item:nth-child(4n + 1) {_x000D_
  margin-left: 0;_x000D_
}_x000D_
_x000D_
.item:nth-child(n + 5) {_x000D_
  margin-top: 10px;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
</div>_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
</div>_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Pipenv: Command Not Found

That happens because you are not installing it globally (system wide). For it to be available in your path you need to install it using sudo, like this:

$ sudo pip install pipenv

Url decode UTF-8 in Python

If you are using Python 3, you can use urllib.parse

url = """example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0"""

import urllib.parse
urllib.parse.unquote(url)

gives:

'example.com?title=????????+??????'

Asp.net MVC ModelState.Clear

Got it in the end. My Custom ModelBinder which was not being registered and does this :

var mymsPage = new MyCmsPage();

NameValueCollection frm = controllerContext.HttpContext.Request.Form;

myCmsPage.SeoTitle = (!String.IsNullOrEmpty(frm["seoTitle"])) ? frm["seoTitle"] : null;

So something that the default model binding was doing must have been causing the problem. Not sure what, but my problem is at least fixed now that my custom model binder is being registered.

How can I add a column that doesn't allow nulls in a Postgresql database?

This worked for me: :)

ALTER TABLE your_table_name ADD COLUMN new_column_name int;

Connect to external server by using phpMyAdmin

To set up an external DB and still use your local DB, you need to edit the config.inc.php file:

On Ubuntu: sudo gedit /etc/phpmyadmin/config.inc.php

The file is roughly set up like this:

if (!empty($dbname)) {

    //Your local db setup

     $i++;
}

What you need to do is duplicate the "your local db setup" by copying and pasting it outside of the IF statement I've shown in the code below, and change the host to you external IP. Mine for example is:

$cfg['Servers'][$i]['host'] = '10.10.1.90:23306';

You can leave the defaults (unless you know you need to change them)

Save and refresh your PHPMYADMIN login page and a new dropdown should appear. You should be good to go.


EDIT: if you want to give the server a name to select at login page, rather than having just the IP address to select, add this to the server setup:

$cfg['Servers'][$i]['verbose'] = 'Name to show when selecting your server'; 

It's good if you have multiple server configs.

Accessing elements of Python dictionary by index

Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:

>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

And getting how many of them are American (16), do like this:

>>> mydict["Apple"]["American"]
'16'

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In XSLT the same <xsl:variable> can be declared only once and can be given a value only at its declaration. If more than one variables are declared at the same time, they are in fact different variables and have different scope.

Therefore, the way to achieve the wanted conditional setting of the variable and producing its value is the following:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="class">
    <xsl:variable name="subexists">
            <xsl:choose>
                <xsl:when test="joined-subclass">true</xsl:when>
                <xsl:otherwise>false</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        subexists:  <xsl:text/>    
        <xsl:value-of select="$subexists" />
    </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the following XML document:

<class>
 <joined-subclass/>
</class>

the wanted result is produced:

    subexists:  true

Can I underline text in an Android layout?

I know this is a late answer, but I came up with a solution that works pretty well... I took the answer from Anthony Forloney for underlining text in code and created a subclass of TextView that handles that for you. Then you can just use the subclass in XML whenever you want to have an underlined TextView.

Here is the class I created:

import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created with IntelliJ IDEA.
 * User: Justin
 * Date: 9/11/13
 * Time: 1:10 AM
 */
public class UnderlineTextView extends TextView
{
    private boolean m_modifyingText = false;

    public UnderlineTextView(Context context)
    {
        super(context);
        init();
    }

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

    public UnderlineTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

    private void init()
    {
        addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
                //Do nothing here... we don't care
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //Do nothing here... we don't care
            }

            @Override
            public void afterTextChanged(Editable s)
            {
                if (m_modifyingText)
                    return;

                underlineText();
            }
        });

        underlineText();
    }

    private void underlineText()
    {
        if (m_modifyingText)
            return;

        m_modifyingText = true;

        SpannableString content = new SpannableString(getText());
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        setText(content);

        m_modifyingText = false;
    }
}

Now... whenever you want to create an underlined textview in XML, you just do the following:

<com.your.package.name.UnderlineTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:gravity="center"
    android:text="This text is underlined"
    android:textColor="@color/blue_light"
    android:textSize="12sp"
    android:textStyle="italic"/>

I have added additional options in this XML snippet to show that my example works with changing the text color, size, and style...

Hope this helps!

How do I initialize a TypeScript Object with a JSON-Object?

TLDR: TypedJSON (working proof of concept)


The root of the complexity of this problem is that we need to deserialize JSON at runtime using type information that only exists at compile time. This requires that type-information is somehow made available at runtime.

Fortunately, this can be solved in a very elegant and robust way with decorators and ReflectDecorators:

  1. Use property decorators on properties which are subject to serialization, to record metadata information and store that information somewhere, for example on the class prototype
  2. Feed this metadata information to a recursive initializer (deserializer)

 

Recording Type-Information

With a combination of ReflectDecorators and property decorators, type information can be easily recorded about a property. A rudimentary implementation of this approach would be:

function JsonMember(target: any, propertyKey: string) {
    var metadataFieldKey = "__propertyTypes__";

    // Get the already recorded type-information from target, or create
    // empty object if this is the first property.
    var propertyTypes = target[metadataFieldKey] || (target[metadataFieldKey] = {});

    // Get the constructor reference of the current property.
    // This is provided by TypeScript, built-in (make sure to enable emit
    // decorator metadata).
    propertyTypes[propertyKey] = Reflect.getMetadata("design:type", target, propertyKey);
}

For any given property, the above snippet will add a reference of the constructor function of the property to the hidden __propertyTypes__ property on the class prototype. For example:

class Language {
    @JsonMember // String
    name: string;

    @JsonMember// Number
    level: number;
}

class Person {
    @JsonMember // String
    name: string;

    @JsonMember// Language
    language: Language;
}

And that's it, we have the required type-information at runtime, which can now be processed.

 

Processing Type-Information

We first need to obtain an Object instance using JSON.parse -- after that, we can iterate over the entires in __propertyTypes__ (collected above) and instantiate the required properties accordingly. The type of the root object must be specified, so that the deserializer has a starting-point.

Again, a dead simple implementation of this approach would be:

function deserialize<T>(jsonObject: any, Constructor: { new (): T }): T {
    if (!Constructor || !Constructor.prototype.__propertyTypes__ || !jsonObject || typeof jsonObject !== "object") {
        // No root-type with usable type-information is available.
        return jsonObject;
    }

    // Create an instance of root-type.
    var instance: any = new Constructor();

    // For each property marked with @JsonMember, do...
    Object.keys(Constructor.prototype.__propertyTypes__).forEach(propertyKey => {
        var PropertyType = Constructor.prototype.__propertyTypes__[propertyKey];

        // Deserialize recursively, treat property type as root-type.
        instance[propertyKey] = deserialize(jsonObject[propertyKey], PropertyType);
    });

    return instance;
}
var json = '{ "name": "John Doe", "language": { "name": "en", "level": 5 } }';
var person: Person = deserialize(JSON.parse(json), Person);

The above idea has a big advantage of deserializing by expected types (for complex/object values), instead of what is present in the JSON. If a Person is expected, then it is a Person instance that is created. With some additional security measures in place for primitive types and arrays, this approach can be made secure, that resists any malicious JSON.

 

Edge Cases

However, if you are now happy that the solution is that simple, I have some bad news: there is a vast number of edge cases that need to be taken care of. Only some of which are:

  • Arrays and array elements (especially in nested arrays)
  • Polymorphism
  • Abstract classes and interfaces
  • ...

If you don't want to fiddle around with all of these (I bet you don't), I'd be glad to recommend a working experimental version of a proof-of-concept utilizing this approach, TypedJSON -- which I created to tackle this exact problem, a problem I face myself daily.

Due to how decorators are still being considered experimental, I wouldn't recommend using it for production use, but so far it served me well.

Difference between SRC and HREF

after going through the HTML 5.1 ducumentation (1 November 2016):


part 4 (The elements of HTML)

chapter 2 (Document metadata)

section 4 (The link element) states that:

The destination of the link(s) is given by the href attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If the href attribute is absent, then the element does not define a link.

does not contain the src attribute ...

witch is logical because it is a link .


chapter 12 (Scripting)

section 1 (The script element) states that:

Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.

it doesn't even mention the href attribute ...

this indicates that while using script tags always use the src attribute !!!


chapter 7 (Embedded content)

section 5 (The img element)

The image given by the src and srcset attributes, and any previous sibling source element's srcset attributes if the parent is a picture element, is the embedded content.

also doesn't mention the href attribute ...

this indicates that when using img tags the src attribute should be used aswell ...


Reference link to the W3C Recommendation

Batch not-equal (inequality) operator

Use NEQ instead.

if "asdf" NEQ "fdas" echo asdf

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

What's the use of ob_start() in php?

Following things are not mentioned in the existing answers : Buffer size configuration HTTP Header and Nesting.

Buffer size configuration for ob_start :

ob_start(null, 4096); // Once the buffer size exceeds 4096 bytes, PHP automatically executes flush, ie. the buffer is emptied and sent out.

The above code improve server performance as PHP will send bigger chunks of data, for example, 4KB (wihout ob_start call, php will send each echo to the browser).

If you start buffering without the chunk size (ie. a simple ob_start()), then the page will be sent once at the end of the script.

Output buffering does not affect the HTTP headers, they are processed in different way. However, due to buffering you can send the headers even after the output was sent, because it is still in the buffer.

ob_start();  // turns on output buffering
$foo->bar();  // all output goes only to buffer
ob_clean();  // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents();  // buffer content is now an empty string
ob_end_clean();  // turn off output buffering

Nicely explained here : https://phpfashion.com/everything-about-output-buffering-in-php

Handling a Menu Item Click Event - Android

This code is work for me

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

     if (id == R.id.action_settings) {
  // add your action here that you want
        return true;
    }

    else if (id==R.id.login)
     {
         // add your action here that you want
     }


    return super.onOptionsItemSelected(item);
}

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

The latest version of sqlcmd adds the -w option to remove extra space after the field value; however, it does not put quotes around strings, which can be a problem with CSV files when importing a field value that contains a comma.

How to convert BigDecimal to Double in Java?

You can convert BigDecimal to double using .doubleValue(). But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal objects directly. Precision loss in these calculations are big time problems in currency related calculations.

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

What's the difference between "&nbsp;" and " "?

The entity &nbsp; produces a non-breaking space, which is used when you don't want an automatic line break at that position. The regular space has the character code 32, while the non-breaking space has the character code 160.

For example when you display numbers with space as thousands separator: 1 234 567, then you use non-breaking spaces so that the number can't be split on separate lines. If you display currency and there is a space between the amount and the currency: 42 SEK, then you use a non-breaking space so that you don't get the amount on one line and the currency on the next.

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

How to match all occurrences of a regex

You can use string.scan(your_regex).flatten. If your regex contains groups, it will return in a single plain array.

string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]

Regex can be a named group as well.

string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten

You can also use gsub, it's just one more way if you want MatchData.

str.gsub(/\d/).map{ Regexp.last_match }

Java Timer vs ExecutorService?

ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.

An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...

Just look at what each offers to decide.

Writing handler for UIAlertAction

Syntax change in swift 3.0

alert.addAction(UIAlertAction(title: "Okay",
                style: .default,
                handler: { _ in print("Foo") } ))

How to check String in response body with mockMvc

You can use getContentAsString method to get the response data as string.

    String payload = "....";
    String apiToTest = "....";
    
    MvcResult mvcResult = mockMvc.
                perform(post(apiToTest).
                content(payload).
                contentType(MediaType.APPLICATION_JSON)).
                andReturn();
    
    String responseData = mvcResult.getResponse().getContentAsString();

You can refer this link for test application.

Can't type in React input text field

i'm also facing that problem now solved.Give the onChange to the searchTool. then that problem will solve for you.

Set height 100% on absolute div

http://jsbin.com/ubalax/1/edit .You can see the results here

body {
    position: relative;
    float: left;
    height: 3000px;
    width: 100%;
}
body div {
    position: absolute;
    height: 100%;
    width: 100%;
    top:0;
    left:0;
    background-color: yellow;
}

javascript push multidimensional array

In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.

Instead, declare valueToPush as an object and push that onto cookie_value_add:

// Create valueToPush as an object {} rather than an array []
var valueToPush = {};

// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;

cookie_value_add.push(valueToPush);

// View the structure of cookie_value_add
console.dir(cookie_value_add);

How to create empty text file from a batch file?

One more to add to the books - short and sweet to type.

break>file.txt
break>"file with spaces in name.txt"

Is there a Java API that can create rich Word documents?

You can use a Java COM bridge like JACOB. If it is from client side, another option would be to use Javascript.

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

How do I clone a single branch in Git?

Using Git version 1.7.3.1 (on Windows), here's what I do ($BRANCH is the name of the branch I want to checkout and $REMOTE_REPO is the URL of the remote repository I want to clone from):

mkdir $BRANCH
cd $BRANCH
git init
git remote add -t $BRANCH -f origin $REMOTE_REPO
git checkout $BRANCH

The advantage of this approach is that subsequent git pull (or git fetch) calls will also just download the requested branch.

Best way to require all files from a directory in ruby?

I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:

Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }

Creating random numbers with no duplicates

The most easy way is use nano DateTime as long format. System.nanoTime();

How to have stored properties in Swift, the same way I had on Objective-C?

So I think I found a method that works cleaner than the ones above because it doesn't require any global variables. I got it from here: http://nshipster.com/swift-objc-runtime/

The gist is that you use a struct like so:

extension UIViewController {
    private struct AssociatedKeys {
        static var DescriptiveName = "nsh_DescriptiveName"
    }

    var descriptiveName: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.DescriptiveName,
                    newValue as NSString?,
                    UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                )
            }
        }
    }
}

UPDATE for Swift 2

private struct AssociatedKeys {
    static var displayed = "displayed"
}

//this lets us check to see if the item is supposed to be displayed or not
var displayed : Bool {
    get {
        guard let number = objc_getAssociatedObject(self, &AssociatedKeys.displayed) as? NSNumber else {
            return true
        }
        return number.boolValue
    }

    set(value) {
        objc_setAssociatedObject(self,&AssociatedKeys.displayed,NSNumber(bool: value),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}

Example JavaScript code to parse CSV data

Here's another solution. This uses:

  • a coarse global regular expression for splitting the CSV string (which includes surrounding quotes and trailing commas)
  • fine-grained regular expression for cleaning up the surrounding quotes and trailing commas
  • also, has type correction differentiating strings, numbers and boolean values

For the following input string:

"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true

The code outputs:

[
  "This is, a value",
  "Hello",
  4,
  -123,
  3.1415,
  "This is also, possible",
  true
]

Here's my implementation of parseCSVLine() in a runnable code snippet:

_x000D_
_x000D_
function parseCSVLine(text) {
  return text.match( /\s*(\".*?\"|'.*?'|[^,]+)\s*(,|$)/g ).map( function (text) {
    let m;
    if (m = text.match(/^\s*\"(.*?)\"\s*,?$/)) return m[1]; // Double Quoted Text
    if (m = text.match(/^\s*'(.*?)'\s*,?$/)) return m[1]; // Single Quoted Text
    if (m = text.match(/^\s*(true|false)\s*,?$/)) return m[1] === "true"; // Boolean
    if (m = text.match(/^\s*((?:\+|\-)?\d+)\s*,?$/)) return parseInt(m[1]); // Integer Number
    if (m = text.match(/^\s*((?:\+|\-)?\d*\.\d*)\s*,?$/)) return parseFloat(m[1]); // Floating Number
    if (m = text.match(/^\s*(.*?)\s*,?$/)) return m[1]; // Unquoted Text
    return text;
  } );
}

let data = `"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true`;
let obj = parseCSVLine(data);
console.log( JSON.stringify( obj, undefined, 2 ) );
_x000D_
_x000D_
_x000D_

C# How to change font of a label

You can't change a Font once it's created - so you need to create a new one:

  mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

PHP passing $_GET in linux command prompt

At the command line paste the following

export QUERY_STRING="param1=abc&param2=xyz" ;  
POST_STRING="name=John&lastname=Doe" ; php -e -r 
'parse_str($_SERVER["QUERY_STRING"], $_GET); parse_str($_SERVER["POST_STRING"], 
$_POST);  include "index.php";'

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

it works for me.

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)? Math.ceil(from) : Math.floor(from);
    if (from < 0)
    from += len;

    for (; from < len; from++) {
      if (from in this && this[from] === elt)
        return from;
    }
    return -1;
  };
}

Boxplot in R showing the mean

With ggplot2:

p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)

How to calculate the sum of the datatable column in asp.net?

Try this

int sum = 0;
foreach (DataRow dr in dt.Rows)
{
     dynamic value = dr[index].ToString();
     if (!string.IsNullOrEmpty(value))
     { 
         sum += Convert.ToInt32(value);
     }
}

PHP Pass by reference in foreach

I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.

There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.

for example in

$a = array('zero', 'one', 'two', 'three');

if we do

$v = &$a[0]

the 0th element ($a[0]) becomes a reference variable. $v points towards that variable; therefore, if we make any change to $v, it will be reflected in $a[0] and vice versa.

now if we do

$v = &$a[1]

$a[1] will become a reference variable and $a[0] will become a normal variable (Since no one else is pointing to $a[0] it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)

This is what happens in the first loop

foreach ($a as &$v) {

}

After the last iteration $a[3] is a reference variable.

Since $v is pointing to $a[3] any change to $v results in a change to $a[3]

in the second loop,

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

in each iteration as $v changes, $a[3] changes. (because $v still points to $a[3]). This is the reason why $a[3] changes on each iteration.

In the iteration before the last iteration, $v is assigned the value 'two'. Since $v points to $a[3], $a[3] now gets the value 'two'. Keep this in mind.

In the last iteration, $v (which points to $a[3]) now has the value of 'two', because $a[3] was set to two in the previous iteration. two is printed. This explains why 'two' is repeated when $v is printed in the last iteration.

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

How to make the checkbox unchecked by default always

Well I guess you can use checked="false". That is the html way to leave a checkbox unchecked. You can refer to http://www.w3schools.com/jsref/dom_obj_checkbox.asp.

Display only 10 characters of a long string?

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

How to add buttons at top of map fragment API v2 layout

You can use the below code to change the button to Left side.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zakasoft.mymap.MapsActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|top"
        android:text="Send"
        android:padding="10dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"/>

</fragment>

How To limit the number of characters in JTextField?

Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. But, here's a great answer from my Udemy.com course "Learn Java Like a Kid":

txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) { 
        if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
            e.consume(); 
    }  
});

This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.

What does the Visual Studio "Any CPU" target mean?

I think most of the important stuff has been said, but I just thought I'd add one thing: If you compile as Any CPU and run on an x64 platform, then you won't be able to load 32-bit DLL files, because your application wasn't started in WoW64, but those DLL files need to run there.

If you compile as x86, then the x64 system will run your application in WoW64, and you'll be able to load 32-bit DLL files.

So I think you should choose "Any CPU" if your dependencies can run in either environment, but choose x86 if you have 32-bit dependencies. This article from Microsoft explains this a bit:

/CLRIMAGETYPE (Specify Type of CLR Image)

Incidentally, this other Microsoft documentation agrees that x86 is usually a more portable choice:

Choosing x86 is generally the safest configuration for an app package since it will run on nearly every device. On some devices, an app package with the x86 configuration won't run, such as the Xbox or some IoT Core devices. However, for a PC, an x86 package is the safest choice and has the largest reach for device deployment. A substantial portion of Windows 10 devices continue to run the x86 version of Windows.

Insert HTML with React Variable Statements (JSX)

Note that dangerouslySetInnerHTML can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.

It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.

Example:

import DOMPurify from 'dompurify'

const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
    );
}

Use dynamic variable names in JavaScript

You can use the window object to get at it .

window['myVar']

window has a reference to all global variables and global functions you are using.

How can I get a user's media from Instagram without authenticating as a user?

This works using a simple ajax call and iterating image paths.

        var name = "nasa";
        $.get("https://www.instagram.com/" + name + "/?__a=1", function (data, status) {
            console.log('IG_NODES', data.user.media.nodes);
            $.each(data.user.media.nodes, function (n, item) {
                console.log('ITEMS', item.display_src);
                $('body').append(
                    "<div class='col-md-4'><img class='img-fluid d-block' src='" + item.display_src + "'></div>"
                );
            });
        })

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')

sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')

How do I create a unique ID in Java?

If you want short, human-readable IDs and only need them to be unique per JVM run:

private static long idCounter = 0;

public static synchronized String createID()
{
    return String.valueOf(idCounter++);
}    

Edit: Alternative suggested in the comments - this relies on under-the-hood "magic" for thread safety, but is more scalable and just as safe:

private static AtomicLong idCounter = new AtomicLong();

public static String createID()
{
    return String.valueOf(idCounter.getAndIncrement());
}

Android: Reverse geocoding - getFromLocation

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Creating a PHP header/footer

You can do it by using include_once() function in php. Construct a header part in the name of header.php and construct the footer part by footer.php. Finally include all the content in one file.

For example:

header.php

<html>
<title>
<link href="sample.css">

footer.php

</html>

So the final files look like

include_once("header.php") 

body content(The body content changes based on the file dynamically)

include_once("footer.php") 

Open a URL without using a browser from a batch file

Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:

powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"

Copy a file in a sane, safe and efficient way

Qt has a method for copying files:

#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");

Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.

Add a string of text into an input field when user clicks a button

Don't forget to keep the input field on focus for future typing with input.focus(); inside the function.

Can promises have multiple arguments to onFulfilled?

Here is a CoffeeScript solution.

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

the answer of this guy Florian

promise = deferred.promise

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

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

return promise 

And to use it:

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

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

Is there 'byte' data type in C++?

Yes, there is std::byte (defined in <cstddef>).

C++ 17 introduced it.

Mac OS X and multiple Java versions

The cleanest way to manage multiple java versions on Mac is to use Homebrew.

And within Homebrew, use:

  • homebrew-cask to install the versions of java
  • jenv to manage the installed versions of java

As seen on http://hanxue-it.blogspot.ch/2014/05/installing-java-8-managing-multiple.html , these are the steps to follow.

  1. install homebrew
  2. install homebrew jenv
  3. install homebrew-cask
  4. install a specific java version using cask (see "homebrew-cask versions" paragraph below)
  5. add this version for jenv to manage it
  6. check the version is correctly managed by jenv
  7. repeat steps 4 to 6 for each version of java you need

homebrew-cask versions

Add the homebrew/cask-versions tap to homebrew using:

brew tap homebrew/cask-versions

Then you can look at all the versions available:

brew search java

Then you can install the version(s) you like:

brew cask install java7
brew cask install java6

And add them to be managed by jenv as usual.

jenv add <javaVersionPathHere>

I think this is the cleanest & simplest way to go about it.


Another important thing to note, as mentioned in Mac OS X 10.6.7 Java Path Current JDK confusing :

For different types of JDKs or installations, you will have different paths

You can check the paths of the versions installed using /usr/libexec/java_home -V, see How do I check if the Java JDK is installed on Mac?

On Mac OS X Mavericks, I found as following:

1) Built-in JRE default: /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

2) JDKs downloaded from Apple: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/

3) JDKs downloaded from Oracle: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home


Resources

Run-time error '1004' - Method 'Range' of object'_Global' failed

When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.

If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.

inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.

The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like

With ThisWorkbook.Worksheets("Template")
    .Range(inputTemplateHeader).Value = NO_ENTRY
    .Range(inputTemplateContent).Value = NO_ENTRY
End With

Adjust the workbook and worksheet references to fit your particular situation.

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

Calculate distance between 2 GPS coordinates

you can find a implementation of this (with some good explanation) in F# on fssnip

here are the important parts:


let GreatCircleDistance<[<Measure>] 'u> (R : float<'u>) (p1 : Location) (p2 : Location) =
    let degToRad (x : float<deg>) = System.Math.PI * x / 180.0<deg/rad>

    let sq x = x * x
    // take the sin of the half and square the result
    let sinSqHf (a : float<rad>) = (System.Math.Sin >> sq) (a / 2.0<rad>)
    let cos (a : float<deg>) = System.Math.Cos (degToRad a / 1.0<rad>)

    let dLat = (p2.Latitude - p1.Latitude) |> degToRad
    let dLon = (p2.Longitude - p1.Longitude) |> degToRad

    let a = sinSqHf dLat + cos p1.Latitude * cos p2.Latitude * sinSqHf dLon
    let c = 2.0 * System.Math.Atan2(System.Math.Sqrt(a), System.Math.Sqrt(1.0-a))

    R * c

Rails: How can I rename a database column in a Ruby on Rails migration?

If you need to switch column names you will need to create a placeholder to avoid a duplicate column name error. Here's an example:

class SwitchColumns < ActiveRecord::Migration
  def change
    rename_column :column_name, :x, :holder
    rename_column :column_name, :y, :x
    rename_column :column_name, :holder, :y
  end
end

Chrome: Uncaught SyntaxError: Unexpected end of input

Trying to parse an empty JSON can be the cause of this error.

When you receive a response from the server or whatever, check first if it's not empty. For example:

function parseJSON(response) {
    if (response.status === 204 || response.status === 205) {
        return null;
    }
    return response.json();
}

Then you can fetch with:

fetch(url, options).then(parseJSON); 

How to set up file permissions for Laravel?

This worked for me:

cd [..LARAVEL PROJECT ROOT]
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo chmod -R 777 ./storage
sudo chmod -R 777 ./bootstrap/cache/

Only if you use npm (VUE, compiling SASS, etc..) add this:

sudo chmod -R 777 ./node_modules/

What it does:

  • Change all file permissions to 644
  • Change all folder permissions to 755
  • For storage and bootstrap cache (special folders used by laravel for creating and executing files, not available from outside) set permission to 777, for anything inside
  • For nodeJS executable, same as above

Note: Maybe you can not, or don't need, to do it with sudo prefix. it depends on your user's permissions, group, etc...

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

T-SQL get SELECTed value of stored procedure

There is also a combination, you can use a return value with a recordset:

--Stored Procedure--

CREATE PROCEDURE [TestProc]

AS
BEGIN

    DECLARE @Temp TABLE
    (
        [Name] VARCHAR(50)
    )

    INSERT INTO @Temp VALUES ('Mark') 
    INSERT INTO @Temp VALUES ('John') 
    INSERT INTO @Temp VALUES ('Jane') 
    INSERT INTO @Temp VALUES ('Mary') 

    -- Get recordset
    SELECT * FROM @Temp

    DECLARE @ReturnValue INT
    SELECT @ReturnValue = COUNT([Name]) FROM @Temp

    -- Return count
    RETURN @ReturnValue

END

--Calling Code--

DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc] 

SELECT @SelectedValue

--Results--

enter image description here

PHP preg_match - only allow alphanumeric strings and - _ characters

Here is one equivalent of the accepted answer for the UTF-8 world.

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • p{N} => matches any kind of numeric character
  • _- => matches underscore and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Just for the record if somebody needs a way to handle signals on Windows. I had a requirement to handle from prog A calling prog B through os/exec but prog B never was able to terminate gracefully because sending signals through ex. cmd.Process.Signal(syscall.SIGTERM) or other signals are not supported on Windows. The way I handled is by creating a temp file as a signal ex. .signal.term through prog A and prog B needs to check if that file exists on interval base, if file exists it will exit the program and handle a cleanup if needed, I'm sure there are other ways but this did the job.

How do you count the elements of an array in java

What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

How do I import .sql files into SQLite 3?

Use sqlite3 database.sqlite3 < db.sql. You'll need to make sure that your files contain valid SQL for SQLite.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

It may be because of any third party lib which may include that permission so from my experience in this field You have to add the privacy policy regarding to that particular information it means if you ask get accounts permission in your app than you have to declare that with your privacy policy file we use that data i.e. email address or whatever with reasons like to login in google play game.

Also can do this

<uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" />

Hope This Will Guide you What You can do for this warning create privacy policy for your app and attach that with store listing.

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

How to access remote server with local phpMyAdmin client?

In Windows with Wamp Server Installed you may find the configuration file

C:\wamp64\apps\phpmyadmin4.8.4\config.inc.php

Change the bolow line as appropriate

$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['port'] = 3306;//$wampConf['mysqlPortUsed'];
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
$cfg['Servers'][$i]['password'] = '';

C# Convert a Base64 -> byte[]

This may be helpful

byte[] bytes = System.Convert.FromBase64String(stringInBase64);

Call break in nested if statements

But there is switch-case :)

switch (true) {
    case true:
        console.log("Yes, its ture :) Break from the switch-case");
        break;
    case false:
        console.log("Nope, but if the condition was set to false this would be used and then break");
        break;

    default:
        console.log("If all else fails");
        break;
}

Create database from command line

PostgreSQL Create Database - Steps to create database in Postgres.

  1. Login to server using postgres user.
    su - postgres
  2. Connect to postgresql database.
bash-4.1$ psql
psql (12.1)
Type "help" for help.
postgres=#
  1. Execute below command to create database.
CREATE DATABASE database_name;

Check for detailed information below: https://orahow.com/postgresql-create-database/

How do I view an older version of an SVN file?

Update to a specific revision:

svn up -r1234 file

How can I get a count of the total number of digits in a number?

static void Main(string[] args)
{
    long blah = 20948230498204;
    Console.WriteLine(blah.ToString().Length);
}

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

Configure active profile in SpringBoot via Maven

There are multiple ways to set profiles for your springboot application.

  1. You can add this in your property file:

    spring.profiles.active=dev
    
  2. Programmatic way:

    SpringApplication.setAdditionalProfiles("dev");
    
  3. Tests make it very easy to specify what profiles are active

    @ActiveProfiles("dev")
    
  4. In a Unix environment

    export spring_profiles_active=dev
    
  5. JVM System Parameter

    -Dspring.profiles.active=dev
    

Example: Running a springboot jar file with profile.

java -jar -Dspring.profiles.active=dev application.jar

Java ArrayList for integers

How about creating an ArrayList of a set amount of Integers?

The below method returns an ArrayList of a set amount of Integers.

public static ArrayList<Integer> createRandomList(int sizeParameter)
{
    // An ArrayList that method returns
    ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
    // Random Object helper
    Random randomHelper = new Random();
    
    for (int x = 0; x < sizeParameter; x++)
    {
        setIntegerList.add(randomHelper.nextInt());
    }   // End of the for loop
    
    return setIntegerList;
}

Variables not showing while debugging in Eclipse

I was running into this problem because eclipse thinks that the code that is executing is commented out. There is an #ifndef wrapper, and the condition evaluates to false in part of the project. Unfortunately, CDT wasn't quite smart enough (Helios or Keppler) to realize that it's not always false, and when stepping through that portion of the code, the variables window doesn't work. I can still inspect individual variable values.

Get the ID of a drawable in ImageView

As of today, there is no support on this function. However, I found a little hack on this one.

 imageView.setImageResource(R.drawable.ic_star_black_48dp);
 imageView.setTag(R.drawable.ic_star_black_48dp);

So if you want to get the ID of the view, just get it's tag.

if (imageView.getTag() != null) {
   int resourceID = (int) imageView.getTag();

   //
   // drawable id.
   //   
}

Returning Promises from Vuex actions

actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.

Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously

actions: {
    myAction(context, data) {
        return new Promise((resolve, reject) => {
            // Do something here... lets say, a http call using vue-resource
            this.$http("/api/something").then(response => {
                // http success, call the mutator and change something in state
                resolve(response);  // Let the calling function know that http is done. You may send some data back
            }, error => {
                // http failed, let the calling function know that action did not work out
                reject(error);
            })
        })
    }
}

Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:

export default {
    mounted: function() {
        // This component just got created. Lets fetch some data here using an action
        this.$store.dispatch("myAction").then(response => {
            console.log("Got some data, now lets show something in this component")
        }, error => {
            console.error("Got nothing from server. Prompt user to check internet connection and try again")
        })
    }
}

As you can see above, it is highly beneficial for actions to return a Promise. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.

And a last note regarding mutators - as you rightly pointed out, they are synchronous. They change stuff in the state, and are usually called from actions. There is no need to mix Promises with mutators, as the actions handle that part.

Edit: My views on the Vuex cycle of uni-directional data flow:

If you access data like this.$store.state["your data key"] in your components, then the data flow is uni-directional.

The promise from action is only to let the component know that action is complete.

The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"] which is unidirectional and follows the vuex data lifecycle.

The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data), once the http call is completed in your action.

jQuery click events firing multiple times

Try that way:

<a href="javascript:void(0)" onclick="this.onclick = false; fireThisFunctionOnlyOnce()"> Fire function </a>

What is the best way to insert source code examples into a Microsoft Word document?

Use this - http://hilite.me/

hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.

How: Just copy the source code to the left pane, select the language and the color scheme, and click "Highlight!". The HTML from the right pane can now be pasted to your blog or email, no external CSS or Javascript files are required.

For Microsoft Word document: Copy the the content from the Preview section and paste to your Microsoft Word document.

3 sections : Source Code , HTML and Preview

Put a Delay in Javascript

I just had an issue where I needed to solve this properly.

Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.

the code I ended up with:

$.each(messages, function(idx, el){
  window.setTimeout(function(){
    doSomething(el);
  },Math.floor(idx+1)*10000);
});

Basically, think of the timeouts as a "timeline" of your script.

This is what we WANT to code:

DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();

This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:

At Runtime 0    : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();

Hope this helps.

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

How to check if an alert exists using WebDriver?

public static void handleAlert(){
    if(isAlertPresent()){
        Alert alert = driver.switchTo().alert();
        System.out.println(alert.getText());
        alert.accept();
    }
}
public static boolean isAlertPresent(){
      try{
          driver.switchTo().alert();
          return true;
      }catch(NoAlertPresentException ex){
          return false;
      }
}

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

Use FB static method getCurrentProfile() of Profile class to retrieve those info.

 Profile profile = Profile.getCurrentProfile();
 String firstName = profile.getFirstName());
 System.out.println(profile.getProfilePictureUri(20,20));
 System.out.println(profile.getLinkUri());

CSS: borders between table columns only

There's no easy way of doing this, other than doing something like class="lastCell" on the last td in each tr, and then setting your css up like this:

#table td {
    border-right: 5px solid red
}

.lastCell {
    border-right: none;
}

Add numpy array as column to Pandas data frame

Here is other example:

import numpy as np
import pandas as pd

""" This just creates a list of touples, and each element of the touple is an array"""
a = [ (np.random.randint(1,10,10), np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]

""" Panda DataFrame will allocate each of the arrays , contained as a touple 
element , as column"""
df = pd.DataFrame(data =a,columns=['random_num','sequential_num'])

The secret in general is to allocate the data in the form a = [ (array_11, array_12,...,array_1n),...,(array_m1,array_m2,...,array_mn) ] and panda DataFrame will order the data in n columns of arrays. Of course , arrays of arrays could be used instead of touples, in that case the form would be : a = [ [array_11, array_12,...,array_1n],...,[array_m1,array_m2,...,array_mn] ]

This is the output if you print(df) from the code above:

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

Other variation of the example above:

b = [ (i,"text",[14, 5,], np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]
df = pd.DataFrame(data=b,columns=['Number','Text','2Elemnt_array','10Element_array'])

Output of df:

   Number  Text 2Elemnt_array                 10Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want to add other columns of arrays, then:

df['3Element_array']=[([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3])]

The final output of df will be:

   Number  Text 2Elemnt_array                 10Element_array 3Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]

What exactly does the .join() method do?

There is a good explanation of why it is costly to use + for concatenating a large number of strings here

Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

''.join([a, b, c]) trick is a performance optimization.

How can I add a key/value pair to a JavaScript object?

You could use either of these (provided key3 is the acutal key you want to use)

arr[ 'key3' ] = value3;

or

arr.key3 = value3;

If key3 is a variable, then you should do:

var key3 = 'a_key';
var value3 = 3;
arr[ key3 ] = value3;

After this, requesting arr.a_key would return the value of value3, a literal 3.

How to print star pattern in JavaScript in a very simple manner?

_x000D_
_x000D_
            /** --------------_x000D_
_x000D_
                    *_x000D_
                   **_x000D_
                  ***_x000D_
                 ****_x000D_
                *****_x000D_
               ******_x000D_
              *******_x000D_
             ********_x000D_
            *********_x000D_
_x000D_
_x000D_
            ----------------*/_x000D_
_x000D_
            let y = 10;_x000D_
            let x = 10;_x000D_
_x000D_
            let str = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i + j >= y){_x000D_
                        str = str.concat("*");_x000D_
                    }else{_x000D_
                        str = str.concat(" ")_x000D_
                    }_x000D_
                }_x000D_
                str = str.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str)_x000D_
_x000D_
_x000D_
            /**________________________x000D_
_x000D_
_x000D_
_x000D_
            *********_x000D_
             ********_x000D_
              *******_x000D_
               ******_x000D_
                *****_x000D_
                 ****_x000D_
                  ***_x000D_
                   **_x000D_
                    *_x000D_
_x000D_
_x000D_
             _______________________*/_x000D_
_x000D_
            let str2 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i <= j ){_x000D_
                        str2 = str2.concat("*");_x000D_
                    }else{_x000D_
                        str2 = str2.concat(" ")_x000D_
                    }_x000D_
                }_x000D_
                str2 = str2.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str2)_x000D_
_x000D_
_x000D_
            /**----------------------_x000D_
_x000D_
_x000D_
            *_x000D_
            **_x000D_
            ***_x000D_
            ****_x000D_
            *****_x000D_
            ******_x000D_
            *******_x000D_
            ********_x000D_
_x000D_
_x000D_
             -------------------------*/_x000D_
_x000D_
_x000D_
            let str3 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i >= j ){_x000D_
                        str3 = str3.concat("*");_x000D_
                    }_x000D_
                }_x000D_
                str3 = str3.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str3)_x000D_
_x000D_
            /**-------------------------_x000D_
_x000D_
_x000D_
             *********_x000D_
             ********_x000D_
             *******_x000D_
             ******_x000D_
             *****_x000D_
             ****_x000D_
             ***_x000D_
             **_x000D_
             *_x000D_
_x000D_
             ---------------------------*/_x000D_
            let str4 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if( j >= i ){_x000D_
                        str4 = str4.concat("*");_x000D_
                    }_x000D_
                }_x000D_
                str4 = str4.concat("\n")_x000D_
            }_x000D_
_x000D_
            console.log(str4)_x000D_
_x000D_
            /**--------------------_x000D_
             Diamond of Asterisks_x000D_
_x000D_
                 *_x000D_
                ***_x000D_
               *****_x000D_
              *******_x000D_
             *********_x000D_
              *******_x000D_
               *****_x000D_
                ***_x000D_
                 *_x000D_
_x000D_
_x000D_
             ---------------------*/_x000D_
_x000D_
            let str5 = "";_x000D_
_x000D_
            for(let i = 1; i < y; i++ ){_x000D_
                for(let j = 1; j < x; j++){_x000D_
                    if(i <= y / 2 && j >= (y / 2) - (i - 1) && j <= (y / 2) + (i - 1) ){_x000D_
                        str5 = str5.concat("*");_x000D_
                    }else if(i >= y / 2_x000D_
                      && j > ((y / 2) -  i) * (-1)_x000D_
                      && j < (y - ((y / 2) -  i) * (-1))){_x000D_
                        str5 = str5.concat("*");_x000D_
                    }_x000D_
                    else {_x000D_
                        str5 = str5.concat(" ");_x000D_
                    }_x000D_
                }_x000D_
                str5 = str5.concat("\n");_x000D_
            }_x000D_
_x000D_
            console.log(str5)
_x000D_
_x000D_
_x000D_

Best database field type for a URL

varchar(max) for SQLServer2005

varchar(65535) for MySQL 5.0.3 and later

This will allocate storage as need and shouldn't affect performance.

Python iterating through object attributes

UPDATED

For python 3, you should use items() instead of iteritems()

PYTHON 2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

'names', [a list with names]
'tweet', [a list with tweet]

How to resolve "local edit, incoming delete upon update" message

I just got this same issue and I found that

$ svn revert foo bar

solved the problem.

svn resolve did not work for me:

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working
svn: Try 'svn help' for more info
svn: Not enough arguments provided

$ svn resolve --accept working .

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working foo
Resolved conflicted state of 'foo'

$ svn st
!  +    foo
!  +  C bar
      >   local edit, incoming delete upon update

Vagrant ssh authentication failure

I resolved the issue in the following manner. 1. Create new SSH key using Git Bash

$ ssh-keygen -t rsa -b 4096 -C "vagrant@localhost"
# Creates a new ssh key, using the provided email as a label
Generating public/private rsa key pair.
  1. When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

    Enter a file in which to save the key (/Users/[you]/.ssh/id_rsa): [Press enter]

  2. At the prompt, type a secure passphrase. You can leave empty and press enter if you do not need a passphrase.

    Enter a file in which to save the key (/Users/[you]/.ssh/id_rsa): [Press enter]

  3. To connect to your Vagrant VM type following command

    ssh vagrant@localhost -p 2222

When you get following message type “yes” and press enter.

The authenticity of host 'github.com (192.30.252.1)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)?
  1. Now to establish a SSH connection type : $ vagrant ssh

  2. Copy the host public key into authorized_keys file in Vagrant VM. For that, go to “Users/[you]/.ssh” folder and copy the content in id_rsa.pub file in host machine and past into “~/.ssh/authorized_keys” file in Vagrant VM.

  3. Change permission on SSH folder and authorized_keys file in Vagrant VM
  4. Restart vagrant with : $ vagrant reload

Difference between res.send and res.json in Express.js

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2);
app.set('json replacer', replacer);

And passed to a JSON.stringify() like so:

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

This is the code in the res.json() method that the send method doesn't have:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

The method ends up as a res.send() in the end:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

How can I change the app display name build with Flutter?

First Rename your AndroidManifest.xml file

android:label="Your App Name"

Second Rename Your Application Name in Pubspec.yaml file name: Your Application Name

Third Change Your Application logo

flutter_icons:
   android: "launcher_icon"
   ios: true
   image_path: "assets/path/your Application logo.formate"

Fourth Run

flutter pub pub run flutter_launcher_icons:main

Leverage browser caching, how on apache or .htaccess?

I took my chance to provide full .htaccess code to pass on Google PageSpeed Insight:

  1. Enable compression
  2. Leverage browser caching
# Enable Compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
</IfModule>
<IfModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

# Leverage Browser Caching
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/html "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</IfModule>

There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.

optimized page score

How to check a radio button with jQuery?

Try this.

To check Radio button using Value use this.

$('input[name=type][value=2]').attr('checked', true); 

Or

$('input[name=type][value=2]').attr('checked', 'checked');

Or

$('input[name=type][value=2]').prop('checked', 'checked');

To check Radio button using ID use this.

$('#radio_1').attr('checked','checked');

Or

$('#radio_1').prop('checked','checked');

Change background color on mouseover and remove it after mouseout

This should be set directly in the CSS.

.forum {background-color: #123456}
.forum:hover {background-color: #380606}

If you are worried about the fact the IE6 will not accept hover over elements which are not links, you can use the hover event of jQuery for compatibility.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

Answer for MYSQL USERS:

ALTER TABLE ChildTableName 
DROP FOREIGN KEY `fk_table`;
ALTER TABLE ChildTableName 
ADD CONSTRAINT `fk_t1_t2_tt`
  FOREIGN KEY (`parentTable`)
  REFERENCES parentTable (`columnName`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

Check whether a path is valid

private bool IsValidPath(string path)
{
    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
    if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
    string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
    strTheseAreInvalidFileNameChars += @":/?*" + "\"";
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
    if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
        return false;

    DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
    if (!dir.Exists)
        dir.Create();
    return true;
}

json_decode returns NULL after webservice call

Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.

Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error() function to determine the error it will return integer but here are those int described:

0 = JSON_ERROR_NONE

1 = JSON_ERROR_DEPTH

2 = JSON_ERROR_STATE_MISMATCH

3 = JSON_ERROR_CTRL_CHAR

4 = JSON_ERROR_SYNTAX

5 = JSON_ERROR_UTF8

In my case I got output of json_last_error() as number 4 so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:

'\'title\' error ...'

After that is really just an easy fix.

$json = json_decode(stripslashes($response));
if (json_last_error() == 0) { // you've got an object in $json}

Android Webview gives net::ERR_CACHE_MISS message

I tried above solution, but the following code help me to close this issue.

if (18 < Build.VERSION.SDK_INT ){
    //18 = JellyBean MR2, KITKAT=19
    mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

AWK: Access captured group from line pattern

You can use GNU awk:

$ cat hta
RewriteCond %{HTTP_HOST} !^www\.mysite\.net$
RewriteRule (.*) http://www.mysite.net/$1 [R=301,L]

$ gawk 'match($0, /.*(http.*?)\$/, m) { print m[1]; }' < hta
http://www.mysite.net/

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Node.js Web Application examples/tutorials

The closest thing is likely Dav Glass's experimental work using node.js, express and YUI3. Basically, he explains how YUI3 is used to render markup on the server side, then sent to the client where binding to event and data occurs. The beauty is YUI3 is used as-is on both the client and the server. Makes a lot of sense. The one big issue is there is not yet a production ready server-side DOM library.

screencast

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

How can I override Bootstrap CSS styles?

It should not effect the load time much since you are overriding parts of the base stylesheet.

Here are some best practices I personally follow:

  1. Always load custom CSS after the base CSS file (not responsive).
  2. Avoid using !important if possible. That can override some important styles from the base CSS files.
  3. Always load bootstrap-responsive.css after custom.css if you don't want to lose media queries. - MUST FOLLOW
  4. Prefer modifying required properties (not all).

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

Automatically pass $event with ng-click?

As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).

The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:

<clickable>
  <h1>Hello World!</h1>
</clickable>

Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):

app.directive('clickable', function() {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div ng-transclude ng-click="handleClick($event)"></div>'
    };
});

Finally in my controller I have the click event ready to go:

$scope.handleClick = function($event) {
    var i = 0;
};

Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.

Hope that helps!

How to access child's state in React?

If you already have onChange handler for the individual FieldEditors I don't see why you couldn't just move the state up to the FormEditor component and just pass down a callback from there to the FieldEditors that will update the parent state. That seems like a more React-y way to do it, to me.

Something along the line of this perhaps:

const FieldEditor = ({ value, onChange, id }) => {
  const handleChange = event => {
    const text = event.target.value;
    onChange(id, text);
  };

  return (
    <div className="field-editor">
      <input onChange={handleChange} value={value} />
    </div>
  );
};

const FormEditor = props => {
  const [values, setValues] = useState({});
  const handleFieldChange = (fieldId, value) => {
    setValues({ ...values, [fieldId]: value });
  };

  const fields = props.fields.map(field => (
    <FieldEditor
      key={field}
      id={field}
      onChange={handleFieldChange}
      value={values[field]}
    />
  ));

  return (
    <div>
      {fields}
      <pre>{JSON.stringify(values, null, 2)}</pre>
    </div>
  );
};

// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
  const fields = ["field1", "field2", "anotherField"];

  return <FormEditor fields={fields} />;
};

Original - pre-hooks version:

_x000D_
_x000D_
class FieldEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleChange = this.handleChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleChange(event) {_x000D_
    const text = event.target.value;_x000D_
    this.props.onChange(this.props.id, text);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="field-editor">_x000D_
        <input onChange={this.handleChange} value={this.props.value} />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class FormEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {};_x000D_
_x000D_
    this.handleFieldChange = this.handleFieldChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleFieldChange(fieldId, value) {_x000D_
    this.setState({ [fieldId]: value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    const fields = this.props.fields.map(field => (_x000D_
      <FieldEditor_x000D_
        key={field}_x000D_
        id={field}_x000D_
        onChange={this.handleFieldChange}_x000D_
        value={this.state[field]}_x000D_
      />_x000D_
    ));_x000D_
_x000D_
    return (_x000D_
      <div>_x000D_
        {fields}_x000D_
        <div>{JSON.stringify(this.state)}</div>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
// Convert to class component and add ability to dynamically add/remove fields by having it in state_x000D_
const App = () => {_x000D_
  const fields = ["field1", "field2", "anotherField"];_x000D_
_x000D_
  return <FormEditor fields={fields} />;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<App />, document.body);
_x000D_
_x000D_
_x000D_

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

cartesian product in pandas

Use pd.MultiIndex.from_product as an index in an otherwise empty dataframe, then reset its index, and you're done.

a = [1, 2, 3]
b = ["a", "b", "c"]

index = pd.MultiIndex.from_product([a, b], names = ["a", "b"])

pd.DataFrame(index = index).reset_index()

out:

   a  b
0  1  a
1  1  b
2  1  c
3  2  a
4  2  b
5  2  c
6  3  a
7  3  b
8  3  c

Validate decimal numbers in JavaScript - IsNumeric()

Arrrgh! Don't listen to the regular expression answers. RegEx is icky for this, and I'm not talking just performance. It's so easy to make subtle, impossible to spot mistakes with your regular expression.

If you can't use isNaN(), this should work much better:

function IsNumeric(input)
{
    return (input - 0) == input && (''+input).trim().length > 0;
}

Here's how it works:

The (input - 0) expression forces JavaScript to do type coercion on your input value; it must first be interpreted as a number for the subtraction operation. If that conversion to a number fails, the expression will result in NaN. This numeric result is then compared to the original value you passed in. Since the left hand side is now numeric, type coercion is again used. Now that the input from both sides was coerced to the same type from the same original value, you would think they should always be the same (always true). However, there's a special rule that says NaN is never equal to NaN, and so a value that can't be converted to a number (and only values that cannot be converted to numbers) will result in false.

The check on the length is for a special case involving empty strings. Also note that it falls down on your 0x89f test, but that's because in many environments that's an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that's your reason for not using isNaN() then just wrap your own function around isNaN() that can also do the additional check.

In summary, if you want to know if a value can be converted to a number, actually try to convert it to a number.


I went back and did some research for why a whitespace string did not have the expected output, and I think I get it now: an empty string is coerced to 0 rather than NaN. Simply trimming the string before the length check will handle this case.

Running the unit tests against the new code and it only fails on the infinity and boolean literals, and the only time that should be a problem is if you're generating code (really, who would type in a literal and check if it's numeric? You should know), and that would be some strange code to generate.

But, again, the only reason ever to use this is if for some reason you have to avoid isNaN().

Capturing Groups From a Grep RegEx

This is a solution that uses gawk. It's something I find I need to use often so I created a function for it

function regex1 { gawk 'match($0,/'$1'/, ary) {print ary['${2:-'1'}']}'; }

to use just do

$ echo 'hello world' | regex1 'hello\s(.*)'
world

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

replacing text in a file with Python

This is a short and simple example I just used:

If:

fp = open("file.txt", "w")

Then:

fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"

Not:

line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

How to make a transparent border using CSS?

Well if you want fully transparent than you can use

border: 5px solid transparent;

If you mean opaque/transparent, than you can use

border: 5px solid rgba(255, 255, 255, .5);

Here, a means alpha, which you can scale, 0-1.

Also some might suggest you to use opacity which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba seems better than using opacity.

For older browsers, always declare the background color using #(hex) just as a fall back, so that if old browsers doesn't recognize the rgba, they will apply the hex color to your element.

Demo

Demo 2 (With a background image for nested div)

Demo 3 (With an img tag instead of a background-image)

body {
    background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);   
}

div.wrap {
    border: 5px solid #fff; /* Fall back, not used in fiddle */
    border: 5px solid rgba(255, 255, 255, .5);
    height: 400px;
    width: 400px;
    margin: 50px;
    border-radius: 50%;
}

div.inner {
    background: #fff; /* Fall back, not used in fiddle */
    background: rgba(255, 255, 255, .5);
    height: 380px;
    width: 380px;
    border-radius: 50%; 
    margin: auto; /* Horizontal Center */
    margin-top: 10px; /* Vertical Center ... Yea I know, that's 
                         manually calculated*/
}

Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.

Ansible: filter a list by its attributes

I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"

would return:

ok: [localhost] => {
    "msg": [
        "172.16.1.100"
    ]
}

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

error: ‘NULL’ was not declared in this scope

NULL can also be found in:

#include <string.h>

String.h will pull in the NULL from somewhere else.

Java String import

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

How to copy and edit files in Android shell?

To copy dirs, it seems you can use adb pull <remote> <local> if you want to copy file/dir from device, and adb push <local> <remote> to copy file/dir to device. Alternatively, just to copy a file, you can use a simple trick: cat source_file > dest_file. Note that this does not work for user-inaccessible paths.

To edit files, I have not found a simple solution, just some possible workarounds. Try this, it seems you can (after the setup) use it to edit files like busybox vi <filename>. Nano seems to be possible to use too.

Remove all special characters except space from a string using JavaScript

_x000D_
_x000D_
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' # _x000D_
Test27919<[email protected]> #elseif_1 $(PR_CONTRACT_START_DATE) ==  '20-09-2019' #_x000D_
Sender539<[email protected]> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #_x000D_
AdestraSID<[email protected]> #else_1#Test27919<[email protected]>#endif_1#`;_x000D_
const replaceString = input.split('$(').join('->').split(')').join('<-');_x000D_
_x000D_
_x000D_
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
_x000D_
_x000D_
_x000D_

jQuery - multiple $(document).ready ...?

$(document).ready(); is the same as any other function. it fires once the document is ready - ie loaded. the question is about what happens when multiple $(document).ready()'s are fired not when you fire the same function within multiple $(document).ready()'s

//this
<div id="target"></div>

$(document).ready(function(){
   jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 3<br>');
});

//is the same as
<div id="target"></div>

$(document).ready(function(){

    jQuery('#target').append('target edit 1<br>');

    jQuery('#target').append('target edit 2<br>');

    jQuery('#target').append('target edit 3<br>');

});

both will behave exactly the same. the only difference is that although the former will achieve the same results. the latter will run a fraction of a second faster and requires less typing. :)

in conclusion where ever possible only use 1 $(document).ready();

//old answer

They will both get called in order. Best practice would be to combine them. but dont worry if its not possible. the page will not explode.

Guzzle 6: no more json() method for responses

$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces

getBody() returns StreamInterface:

/**
 * Gets the body of the message.
 *
 * @return StreamInterface Returns the body as a stream.
 */
public function getBody();

StreamInterface implements __toString() which does

Reads all data from the stream into a string, from the beginning to end.

Therefore, to read body as string, you have to cast it to string:

$stringBody = (string) $response->getBody()


Gotchas

  1. json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
  2. Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.

Navigation bar show/hide

This code will help you.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] 
initWithTarget:self action:@selector(showHideNavbar:)];
[self.view addGestureRecognizer:tapGesture];

-(void) showHideNavbar:(id) sender 
{ 
// write code to show/hide nav bar here 
// check if the Navigation Bar is shown
if (self.navigationController.navigationBar.hidden == NO)
{
// hide the Navigation Bar
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
// if Navigation Bar is already hidden
else if (self.navigationController.navigationBar.hidden == YES)
{
// Show the Navigation Bar
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

Try putting the following in the environment variables for the scheme under run(debug)

OS_ACTIVITY_MODE = disable

Multiple Indexes vs Multi-Column Indexes

Yes. I recommend you check out Kimberly Tripp's articles on indexing.

If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.

Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.

You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.

500 internal server error at GetResponse()

From that error, I would say that your code is fine, at least the part that calls the webservice. The error seems to be in the actual web service.

To get the error from the web server, add a try catch and catch a WebException. A WebException has a property called Response which is a HttpResponse. you can then log anything that is returned, and upload you code. Check back later in the logs and see what is actually being returned.

How to read existing text files without defining path

When you provide a path, it can be absolute/rooted, or relative. If you provide a relative path, it will be resolved by taking the working directory of the running process.

Example:

string text = File.ReadAllText("Some\\Path.txt"); // relative path

The above code has the same effect as the following:

string text = File.ReadAllText(
    Path.Combine(Environment.CurrentDirectory, "Some\\Path.txt"));

If you have files that are always going to be in the same location relative to your application, just include a relative path to them, and they should resolve correctly on different computers.