Programs & Examples On #Event flow

Importing a long list of constants to a Python file

Sure, you can put your constants into a separate module. For example:

const.py:

A = 12
B = 'abc'
C = 1.2

main.py:

import const

print const.A, const.B, const.C

Note that as declared above, A, B and C are variables, i.e. can be changed at run time.

mkdir's "-p" option

-p|--parent will be used if you are trying to create a directory with top-down approach. That will create the parent directory then child and so on iff none exists.

-p, --parents no error if existing, make parent directories as needed

About rlidwka it means giving full or administrative access. Found it here https://itservices.stanford.edu/service/afs/intro/permissions/unix.

How do I convert a calendar week into a date in Excel?

If A1 has the week number and year as a 3 or 4 digit integer in the format wwYY then the formula would be:

=INT(A1/100)*7+DATE(MOD([A1,100),1,1)-WEEKDAY(DATE(MOD(A1,100),1,1))-5

the subtraction of the weekday ensures you return a consistent start day of the week. Use the final subtraction to adjust the start day.

Call to undefined function oci_connect()

Simple steps

You need to enable the below extension in your php.ini

;extension=php_oci8.dll
;extension=php_oci8_11.g.dll

by removing the ";" so that the results will below:

extension=php_oci8.dll
extension=php_oci8_11.g.dll

Download Oracle Instant Client:- Preferably 32 bit. 32 bit will also work on 64 bit. You can just google: download oracle instant client windows 32 bit. Use version 11 of the client because extension=php_oci8_11.g.dll won't work with 12. Unzip the package into a location such as C:\Oracle\instantclient_11_2.

Finally modify the System's PATH Environment Variable with end location, under system variables not user variables

Then you need to restart the System for PATH changes to fully propagate.

If you just restart XAMPP/WAMP without restarting the machine the Client's DLL files (i.e. OCL.dll) will not be loaded (nor found) by PHP's php_oci8_11g.dll extension.

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

Is ASCII code 7-bit or 8-bit?

when we call ASCII as 7 bit code, the left most bit is used as sign bit so with 7 bits we can write up to 127. that means from -126 to 127 because Max imam value of ASCII is 0 to 255. this can be only satisfied with the argument of 7 bit if last bit is considered as sign bit

DBCC CHECKIDENT Sets Identity to 0

Change statement to

  DBCC CHECKIDENT('TableName', RESEED, 1)

This will start from 2 (or 1 when you recreate table), but it will never be 0.

C# Return Different Types?

use the dynamic keyword as return type.

 private dynamic getValuesD<T>()
    {
        if (typeof(T) == typeof(int))
        {
            return 0;
        }
        else if (typeof(T) == typeof(string))
        {
            return "";
        }
        else if (typeof(T) == typeof(double))
        {
            return 0;
        }
        else
        {
            return false;
        }
    }

        int res = getValuesD<int>();
        string res1 = getValuesD<string>();
        double res2 = getValuesD<double>();
        bool res3 = getValuesD<bool>();

// dynamic keyword is preferable to use in this case instead of an object type

// because dynamic keyword keeps the underlying structure and data type so that // you can directly inspect and view the value.

// in object type, you have to cast the object to a specific data type to view // the underlying value.

regards,

Abhijit

Python3 project remove __pycache__ folders and .pyc files

Why not just use rm -rf __pycache__? Run git add -A afterwards to remove them from your repository and add __pycache__/ to your .gitignore file.

How to list only the file names that changed between two commits?

git diff --name-only SHA1 SHA2

where you only need to include enough of the SHA to identify the commits. You can also do, for example

git diff --name-only HEAD~10 HEAD~5

to see the differences between the tenth latest commit and the fifth latest (or so).

RESTful call in Java

Most Easy Solution will be using Apache http client library. refer following sample code.. this code uses basic security for authenticating.

Add following Dependency.

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("username", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpPost request = new HttpPost("https://api.plivo.com/v1/Account/MAYNJ3OT/Message/");HttpResponse response = client.execute(request);
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {    
    textView = textView + line;
    }
    System.out.println(textView);

Interface defining a constructor signature?

Beginning with C# 8.0, an interface member may declare a body. This is called a default implementation. Members with bodies permit the interface to provide a "default" implementation for classes and structs that don't provide an overriding implementation. In addition, beginning with C# 8.0, an interface may include:

Constants Operators Static constructor. Nested types Static fields, methods, properties, indexers, and events Member declarations using the explicit interface implementation syntax. Explicit access modifiers (the default access is public).

Converting byte array to String (Java)

You can try this.

String s = new String(bytearray);

How can I get the max (or min) value in a vector?

You can print it directly using max_element/min_element function. Eg:

  cout<<*max_element(v.begin(),v.end());

  cout<<*min_element(v.begin(),v.end());

Converting strings to floats in a DataFrame

NOTE: pd.convert_objects has now been deprecated. You should use pd.Series.astype(float) or pd.to_numeric as described in other answers.

This is available in 0.11. Forces conversion (or set's to nan) This will work even when astype will fail; its also series by series so it won't convert say a complete string column

In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))

In [11]: df
Out[11]: 
     A    B
0  1.0  1.0
1    1  foo

In [12]: df.dtypes
Out[12]: 
A    object
B    object
dtype: object

In [13]: df.convert_objects(convert_numeric=True)
Out[13]: 
   A   B
0  1   1
1  1 NaN

In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]: 
A    float64
B    float64
dtype: object

Rails 4 LIKE query - ActiveRecord adds quotes

If someone is using column names like "key" or "value", then you still see the same error that your mysql query syntax is bad. This should fix:

.where("`key` LIKE ?", "%#{key}%")

How to check if a string "StartsWith" another string?

You can use ECMAScript 6's String.prototype.startsWith() method, but it's not yet supported in all browsers. You'll want to use a shim/polyfill to add it on browsers that don't support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:

Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this:

_x000D_
_x000D_
   console.log("Hello World!".startsWith("He")); // true
    
var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false
_x000D_
_x000D_
_x000D_

Android EditText for password with android:hint

Actually, I found that if you put the the android:gravity="center" at the end of your xml line, the hint text shows up fine with the android:inputType="textVisiblePassword"

How do I split a string, breaking at a particular character?

With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

To set flashdata you need to redirect controller function

$this->session->set_flashdata('message_name', 'This is test message');

//redirect to some function
redirect("controller/function_name");

//echo in view or controller
$this->session->flashdata('message_name');

Does Python have “private” variables in classes?

Sorry guys for "resurrecting" the thread, but, I hope this will help someone:

In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:

class Simple:
    def __init__(self, str):
        print("inside the simple constructor")
        self.__s = str

    def show(self):
        print(self.__s)

    def showMsg(self, msg):
        print(msg + ':', self.show())

To instantiate this do:

ss = Simple("lol")
ss.show()

Note that: print(ss.__s) will throw an error.

In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.

But don't be afraid of it. It doesn't matter. It does the job too. ;)

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).

javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

Insert all data of a datagridview to database at once

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                        SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                        cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                        cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                        cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                        cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                        cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                        cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                        cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("Added successfully!");

What is the difference between task and thread?

Thread

The bare metal thing, you probably don't need to use it, you probably can use a LongRunning task and take the benefits from the TPL - Task Parallel Library, included in .NET Framework 4 (february, 2002) and above (also .NET Core).

Tasks

Abstraction above the Threads. It uses the thread pool (unless you specify the task as a LongRunning operation, if so, a new thread is created under the hood for you).

Thread Pool

As the name suggests: a pool of threads. Is the .NET framework handling a limited number of threads for you. Why? Because opening 100 threads to execute expensive CPU operations on a Processor with just 8 cores definitely is not a good idea. The framework will maintain this pool for you, reusing the threads (not creating/killing them at each operation), and executing some of them in parallel, in a way that your CPU will not burn.

OK, but when to use each one?

In resume: always use tasks.

Task is an abstraction, so it is a lot easier to use. I advise you to always try to use tasks and if you face some problem that makes you need to handle a thread by yourself (probably 1% of the time) then use threads.

BUT be aware that:

  • I/O Bound: For I/O bound operations (database calls, read/write files, APIs calls, etc) avoid using normal tasks, use LongRunning tasks (or threads if you need to). Because using tasks would lead you to a thread pool with a few threads busy and a lot of another tasks waiting for its turn to take the pool.
  • CPU Bound: For CPU bound operations just use the normal tasks (that internally will use the thread pool) and be happy.

405 method not allowed Web API

Old question but none of the answers worked for me.

This article solved my problem by adding the following lines to web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

Print "\n" or newline characters as part of the output on terminal

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

How to draw a path on a map using kml file?

Thank Mathias Lin, tested and it works!

In addition, sample implementation of Mathias's method in activity can be as follows.

public class DirectionMapActivity extends MapActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directionmap);

        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);

        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        String locationProvider = LocationManager.NETWORK_PROVIDER;
        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");//from
        urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
        urlString.append(",");
        urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
        urlString.append("&daddr=");//to
        urlString.append( Double.toString((double)dest[0]/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)dest[1]/1.0E6 ));
        urlString.append("&ie=UTF8&0&om=0&output=kml");

        try{
            // setup the url
            URL url = new URL(urlString.toString());
            // create the factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // create a parser
            SAXParser parser = factory.newSAXParser();
            // create the reader (scanner)
            XMLReader xmlreader = parser.getXMLReader();
            // instantiate our handler
            NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
            // assign our handler
            xmlreader.setContentHandler(navSaxHandler);
            // get our data via the url class
            InputSource is = new InputSource(url.openStream());
            // perform the synchronous parse           
            xmlreader.parse(is);
            // get the results - should be a fully populated RSSFeed instance, or null on error
            NavigationDataSet ds = navSaxHandler.getParsedData();

            // draw path
            drawPath(ds, Color.parseColor("#add331"), mapView );

            // find boundary by using itemized overlay
            GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
            GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
                                                ,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );

            Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
            MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
            OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
            OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
            bgItemizedOverlay.addOverlay(currentPixel);
            bgItemizedOverlay.addOverlay(destPixel);

            // center and zoom in the map
            MapController mc = mapView.getController();
            mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
            mc.animateTo(new GeoPoint(
                    (currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
                    , (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));

        } catch(Exception e) {
            Log.d("DirectionMap","Exception parsing kml.");
        }

    }
    // and the rest of the methods in activity, e.g. drawPath() etc...

MapItemizedOverlay.java

public class MapItemizedOverlay extends ItemizedOverlay{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;

    public MapItemizedOverlay(Drawable defaultMarker, Context context) {
          super(boundCenterBottom(defaultMarker));
          mContext = context;
    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }

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

}

Delete all items from a c++ std::vector

vector.clear() is effectively the same as vector.erase( vector.begin(), vector.end() ).

If your problem is about calling delete for each pointer contained in your vector, try this:

#include <algorithm>

template< typename T >
struct delete_pointer_element
{
    void operator()( T element ) const
    {
        delete element;
    }
};

// ...
std::for_each( vector.begin(), vector.end(), delete_pointer_element<int*>() );

Edit: Code rendered obsolete by C++11 range-for.

How do I show a running clock in Excel?

Found the code that I referred to in my comment above. To test it, do this:

  1. In Sheet1 change the cell height and width of say A1 as shown in the snapshot below.
  2. Format the cell by right clicking on it to show time format
  3. Add two buttons (form controls) on the worksheet and name them as shown in the snapshot
  4. Paste this code in a module
  5. Right click on the Start Timer button on the sheet and click on Assign Macros. Select StartTimer macro.
  6. Right click on the End Timer button on the sheet and click on Assign Macros. Select EndTimer macro.

Now click on Start Timer button and you will see the time getting updated in cell A1. To stop time updates, Click on End Timer button.

Code (TRIED AND TESTED)

Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long

Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long

'~~> Start Timer
Sub StartTimer()
    '~~ Set the timer for 1 second
    TimerSeconds = 1
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

'~~> End Timer
Sub EndTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
End Sub

Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
    '~~> Update value in Sheet 1
    Sheet1.Range("A1").Value = Time
End Sub

SNAPSHOT

enter image description here

How do I populate a JComboBox with an ArrayList?

Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox

See the JavaDoc and tutorial for more info.

Is there a way to @Autowire a bean that requires constructor arguments?

Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:

@Autowired 
private AutowireCapableBeanFactory autowireCapableBeanFactory;

public void doStuff() {
   YourObject obj = new YourObject("Value X", "etc");
   autowireCapableBeanFactory.autowireBean(obj);
}

In Perl, how can I read an entire file into a string?

From perlfaq5: How can I read in an entire file all at once?:


You can use the File::Slurp module to do it in one step.

use File::Slurp;

$all_of_it = read_file($filename); # entire file in scalar
@all_lines = read_file($filename); # one line per element

The customary Perl approach for processing all the lines in a file is to do so one line at a time:

open (INPUT, $file)     || die "can't open $file: $!";
while (<INPUT>) {
    chomp;
    # do something with $_
    }
close(INPUT)            || die "can't close $file: $!";

This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this:

@lines = <INPUT>;

you should think long and hard about why you need everything loaded at once. It's just not a scalable solution. You might also find it more fun to use the standard Tie::File module, or the DB_File module's $DB_RECNO bindings, which allow you to tie an array to a file so that accessing an element the array actually accesses the corresponding line in the file.

You can read the entire filehandle contents into a scalar.

{
local(*INPUT, $/);
open (INPUT, $file)     || die "can't open $file: $!";
$var = <INPUT>;
}

That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this:

$var = do { local $/; <INPUT> };

For ordinary files you can also use the read function.

read( INPUT, $var, -s INPUT );

The third argument tests the byte size of the data on the INPUT filehandle and reads that many bytes into the buffer $var.

How to call javascript from a href?

Using JQuery would be good;

<a href="#" id="youLink">Call JavaScript </a>



$("#yourLink").click(function(e){
//do what ever you want...
});

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

Replace contents of factor column in R dataframe

A more general solution that works with all the data frame at once and where you don't have to add new factors levels is:

data.mtx <- as.matrix(data.df)
data.mtx[which(data.mtx == "old.value.to.replace")] <- "new.value"
data.df <- as.data.frame(data.mtx)

A nice feature of this code is that you can assign as many values as you have in your original data frame at once, not only one "new.value", and the new values can be random values. Thus you can create a complete new random data frame with the same size as the original.

How can I check if mysql is installed on ubuntu?

You can use tool dpkg for managing packages in Debian operating system.

Example

dpkg --get-selections | grep mysql if it's listed as installed, you got it. Else you need to get it.

Add params to given URL in Python

If you are using the requests lib:

import requests
...
params = {'tag': 'python'}
requests.get(url, params=params)

How to return a dictionary | Python

def prepare_table_row(row):
    lst = [i.text for i in row if i != u'\n']
    return dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

Case-Insensitive List Search

I realise this is an old post, but just in case anyone else is looking, you can use Contains by providing the case insensitive string equality comparer like so:

using System.Linq;

// ...

if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Keyword Exists");
}

This has been available since .net 2.0 according to msdn.

Format Date output in JSF

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

Use JSTL forEach loop's varStatus as an ID

You can try this. similar result

 <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount.count}"></div>
 </c:forEach>

How do I find the time difference between two datetime objects in python?

This is how I get the number of hours that elapsed between two datetime.datetime objects:

before = datetime.datetime.now()
after  = datetime.datetime.now()
hours  = math.floor(((after - before).seconds) / 3600)

What is referencedColumnName used for in JPA?

  • name attribute points to the column containing the asociation, i.e. column name of the foreign key
  • referencedColumnName attribute points to the related column in asociated/referenced entity, i.e. column name of the primary key

You are not required to fill the referencedColumnName if the referenced entity has single column as PK, because there is no doubt what column it references (i.e. the Address single column ID).

@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() { return address; }

However if the referenced entity has PK that spans multiple columns the order in which you specify @JoinColumn annotations has significance. It might work without the referencedColumnName specified, but that is just by luck. So you should map it like this:

@ManyToOne
@JoinColumns({
    @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
    @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() { return address; }

or in case of ManyToMany:

@ManyToMany
@JoinTable(
    name="CUST_ADDR",
    joinColumns=
        @JoinColumn(name="CUST_ID"),
    inverseJoinColumns={
        @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
        @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
    }
)

Real life example

Two queries generated by Hibernate of the same join table mapping, both without referenced column specified. Only the order of @JoinColumn annotations were changed.

/* load collection Client.emails */ 
select 
emails0_.id_client as id1_18_1_,
emails0_.rev as rev18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_

from client_email emails0_ 
inner join email email1_ on emails0_.id_email=email1_.id_email 

where emails0_.id_client='2' and 
emails0_.rev='18'
/* load collection Client.emails */ 
select
emails0_.rev as rev18_1_,
emails0_.id_client as id2_18_1_,
emails0_.id_email as id3_1_, 
email1_.id_email as id1_6_0_

from client_email emails0_ 
inner join email email1_ on emails0_.id_email=email1_.id_email 

where emails0_.rev='2' and 
emails0_.id_client='18'

We are querying a join table to get client's emails. The {2, 18} is composite ID of Client. The order of column names is determined by your order of @JoinColumn annotations. The order of both integers is always the same, probably sorted by hibernate and that's why proper alignment with join table columns is required and we can't or should rely on mapping order.

The interesting thing is the order of the integers does not match the order in which they are mapped in the entity - in that case I would expect {18, 2}. So it seems the Hibernate is sorting the column names before it use them in query. If this is true and you would order your @JoinColumn in the same way you would not need referencedColumnName, but I say this only for illustration.

Properly filled referencedColumnName attributes result in exactly same query without the ambiguity, in my case the second query (rev = 2, id_client = 18).

How to change color and font on ListView

If u want to set background of the list then place the image before the < Textview>

< ImageView
android:background="@drawable/image_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

and if u want to change color then put color code on above textbox like this

 android:textColor="#ffffff"

MySQL: Large VARCHAR vs. TEXT?

Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.

I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.

Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.

Perform Button click event when user press Enter key in Textbox

You can do it with javascript/jquery:

<script>
    function runScript(e) {
        if (e.keyCode == 13) {
            $("#myButton").click(); //jquery
            document.getElementById("myButton").click(); //javascript
        }
    }
</script>

<asp:textbox id="txtUsername" runat="server" onkeypress="return runScript(event)" />

<asp:LinkButton id="myButton" text="Login" runat="server" />

Refused to apply inline style because it violates the following Content Security Policy directive

You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.

how to align all my li on one line?

Try putting white-space:nowrap; in your <ul> style

edit: and use 'inline' rather than 'inline-block' as other have pointed out (and I forgot)

adding .css file to ejs

You can use this

     var fs = require('fs');
     var myCss = {
         style : fs.readFileSync('./style.css','utf8');
     };

     app.get('/', function(req, res){
       res.render('index.ejs', {
       title: 'My Site',
       myCss: myCss
      });
     });

put this on template

   <%- myCss.style %>

just build style.css

  <style>
    body { 
     background-color: #D8D8D8;
     color: #444;
   }
  </style>

I try this for some custom css. It works for me

MySQL select one column DISTINCT, with corresponding other columns

Not sure if you can do this with MySQL, but you can use a CTE in T-SQL

; WITH tmpPeople AS (
 SELECT 
   DISTINCT(FirstName),
   MIN(Id)      
 FROM People
)
SELECT
 tP.Id,
 tP.FirstName,
 P.LastName
FROM tmpPeople tP
JOIN People P ON tP.Id = P.Id

Otherwise you might have to use a temporary table.

Convert a double to a QString

Check out the documentation

Quote:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

How to override the properties of a CSS class using another CSS class

You should override by increasing Specificity of your styling. There are different ways of increasing the Specificity. Usage of !important which effects specificity, is a bad practice because it breaks natural cascading in your style sheet.

Following diagram taken from css-tricks.com will help you produce right specificity for your element based on a points structure. Whichever specificity has higher points, will win. Sounds like a game - doesn't it?

enter image description here

Checkout sample calculations here on css-tricks.com. This will help you understand the concept very well and it will only take 2 minutes.

If you then like to produce and/or compare different specificities by yourself, try this Specificity Calculator: https://specificity.keegan.st/ or you can just use traditional paper/pencil.

For further reading try MDN Web Docs.

All the best for not using !important.

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

Saving the PuTTY session logging

It works fine for me, but it's a little tricky :)

  • First open the PuTTY configuration.
  • Select the session (right part of the window, Saved Sessions)
  • Click Load (now you have loaded Host Name, Port and Connection type)
  • Then click Logging (under Session on the left)
  • Change whatever settings you want
  • Go back to Session window and click the Save button

Now you have settings for this session set (every time you load session it will be logged).

How to pass command line argument to gnuplot?

@vagoberto's answer seems the best IMHO if you need positional arguments, and I have a small improvement to add.

vagoberto's suggestion:

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

which gets called by:

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

for those lazy typers like myself, one could make the script executable (chmod 755 script.gp)

then use the following:

#!/usr/bin/env gnuplot -c

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD
print "number of arguments: ", ARGC

and execute it as:

$ ./imb.plot a b c d
script name        : ./imb.plot
first argument     : a
third argument     : c
number of arguments: 4

Python : List of dict, if exists increment a dict value, if not append a new dict

This always works fine for me:

for url in list_of_urls:
    urls.setdefault(url, 0)
    urls[url] += 1

Escape double quotes in a string

No.

Either use verbatim string literals as you have, or escape the " using backslash.

string test = "He said to me, \"Hello World\" . How are you?";

The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.

Python: How to create a unique file name?

Maybe you need unique temporary file?

import tempfile

f = tempfile.NamedTemporaryFile(mode='w+b', delete=False)

print f.name
f.close()

f is opened file. delete=False means do not delete file after closing.

If you need control over the name of the file, there are optional prefix=... and suffix=... arguments that take strings. See https://docs.python.org/3/library/tempfile.html.

Creating a simple configuration file and parser in C++

A naive approach could look like this:

#include <map>
#include <sstream>
#include <stdexcept>
#include <string>

std::map<std::string, std::string> options; // global?

void parse(std::istream & cfgfile)
{
    for (std::string line; std::getline(cfgfile, line); )
    {
        std::istringstream iss(line);
        std::string id, eq, val;

        bool error = false;

        if (!(iss >> id))
        {
            error = true;
        }
        else if (id[0] == '#')
        {
            continue;
        }
        else if (!(iss >> eq >> val >> std::ws) || eq != "=" || iss.get() != EOF)
        {
            error = true;
        }

        if (error)
        {
            // do something appropriate: throw, skip, warn, etc.
        }
        else
        {
            options[id] = val;
        }
    }
}

Now you can access each option value from the global options map anywhere in your program. If you want castability, you could make the mapped type a boost::variant.

pandas: multiple conditions while indexing data frame - unexpected behavior

As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.

That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1:

df1 = df[(df.a != -1) & (df.b != -1)]

You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1.

For df2:

df2 = df[(df.a != -1) | (df.b != -1)]

You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1.

PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc.

How to detect scroll position of page using jQuery

GET Scroll Position:

var scrolled_val = window.scrollY;

DETECT Scroll Position:

$(window).scroll
(
     function (event) 
     {
          var scrolled_val = window.scrollY;
          alert(scrolled_val);
     }
 );

Android Webview - Webpage should fit the device screen

Making Changes to the answer by danh32 since the display.getWidth(); is now deprecated.

private int getScale(){
    Point p = new Point();
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    display.getSize(p);
    int width = p.x; 
    Double val = new Double(width)/new Double(PIC_WIDTH);
    val = val * 100d;
    return val.intValue();
}

Then use

WebView web = new WebView(this);
web.setPadding(0, 0, 0, 0);
web.setInitialScale(getScale());

Difference between numpy.array shape (R, 1) and (R,)

The data structure of shape (n,) is called a rank 1 array. It doesn't behave consistently as a row vector or a column vector which makes some of its operations and effects non intuitive. If you take the transpose of this (n,) data structure, it'll look exactly same and the dot product will give you a number and not a matrix. The vectors of shape (n,1) or (1,n) row or column vectors are much more intuitive and consistent.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

To have a good follow-up about all this, Twitter - one of the pioneers of hashbang URL's and single-page-interface - admitted that the hashbang system was slow in the long run and that they have actually started reversing the decision and returning to old-school links.

Article about this is here.

How to install a private NPM module without my own registry?

I use the following with a private github repository:

npm install github:mygithubuser/myproject

Parse JSON from JQuery.ajax success data

From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).

Or you can set the dataType to json to convert it automatically.

Google Script to see if text contains a value

I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.

function foo() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = ss.getSheetByName('spreadsheet-name');
    var r = s.getRange('A:A');
    var v = r.getValues();
    var searchTerm = 'needle';
    for(var i=v.length-1;i>=0;i--) {
        if(v[0,i].toString().indexOf(searchTerm) > -1) {
            // do something
        }
    }
};

Is there an addHeaderView equivalent for RecyclerView?

I made an implementation based on @hister's one for my personal purposes, but using inheritance.

I hide the implementation details mechanisms (like add 1 to itemCount, subtract 1 from position) in an abstract super class HeadingableRecycleAdapter, by implementing required methods from Adapter like onBindViewHolder, getItemViewType and getItemCount, making that methods final, and providing new methods with hidden logic to client:

  • onAddViewHolder(RecyclerView.ViewHolder holder, int position),
  • onCreateViewHolder(ViewGroup parent),
  • itemCount()

Here are the HeadingableRecycleAdapter class and a client. I left the header layout a bit hard-coded because it fits my needs.

public abstract class HeadingableRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int HEADER_VIEW_TYPE = 0;

    @LayoutRes
    private int headerLayoutResource;
    private String headerTitle;
    private Context context;

    public HeadingableRecycleAdapter(@LayoutRes int headerLayoutResourceId, String headerTitle, Context context) {
        this.headerLayoutResource = headerLayoutResourceId;
        this.headerTitle = headerTitle;
        this.context = context;
    }

    public Context context() {
        return context;
    }

    @Override
    public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == HEADER_VIEW_TYPE) {
            return new HeaderViewHolder(LayoutInflater.from(context).inflate(headerLayoutResource, parent, false));
        }
        return onCreateViewHolder(parent);
    }

    @Override
    public final void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        if (viewType == HEADER_VIEW_TYPE) {
            HeaderViewHolder vh = (HeaderViewHolder) holder;
            vh.bind(headerTitle);
        } else {
            onAddViewHolder(holder, position - 1);
        }
    }

    @Override
    public final int getItemViewType(int position) {
        return position == 0 ? 0 : 1;
    }

    @Override
    public final int getItemCount() {
        return itemCount() + 1;
    }

    public abstract int itemCount();

    public abstract RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent);

    public abstract void onAddViewHolder(RecyclerView.ViewHolder holder, int position);

}



@PerActivity
public class IngredientsAdapter extends HeadingableRecycleAdapter {
    public static final String TITLE = "Ingredients";
    private List<Ingredient> itemList;


    @Inject
    public IngredientsAdapter(Context context) {
        super(R.layout.layout_generic_recyclerview_cardified_header, TITLE, context);
    }

    public void setItemList(List<Ingredient> itemList) {
        this.itemList = itemList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
        return new ViewHolder(LayoutInflater.from(context()).inflate(R.layout.item_ingredient, parent, false));
    }

    @Override
    public void onAddViewHolder(RecyclerView.ViewHolder holder, int position) {
        ViewHolder vh = (ViewHolder) holder;
        vh.bind(itemList.get(position));
    }

    @Override
    public int itemCount() {
        return itemList == null ? 0 : itemList.size();
    }

    private String getQuantityFormated(double quantity, String measure) {
        if (quantity == (long) quantity) {
            return String.format(Locale.US, "%s %s", String.valueOf(quantity), measure);
        } else {
            return String.format(Locale.US, "%.1f %s", quantity, measure);
        }
    }


    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.text_ingredient)
        TextView txtIngredient;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void bind(Ingredient ingredient) {
            String ingredientText = ingredient.getIngredient();
            txtIngredient.setText(String.format(Locale.US, "%s %s ", getQuantityFormated(ingredient.getQuantity(),
                    ingredient.getMeasure()), Character.toUpperCase(ingredientText.charAt(0)) +
                    ingredientText
                            .substring(1)));
        }
    }
}

How to copy a collection from one database to another in MongoDB

In case some heroku users stumble here and like me want to copy some data from staging database to the production database or vice versa here's how you do it very conveniently (N.B. I hope there's no typos in there, can't check it atm., I'll try confirm the validity of the code asap):

to_app="The name of the app you want to migrate data to"
from_app="The name of the app you want to migrate data from"
collection="the collection you want to copy"
mongohq_url=`heroku config:get --app "$to_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
to_token=${parts[0]}; to_url=${parts[1]}; to_db=${parts[2]}
mongohq_url=`heroku config:get --app "$from_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
from_token=${parts[0]}; from_url=${parts[1]}; from_db=${parts[2]}
mongodump -h "$from_url" -u heroku -d "$from_db" -p"$from_token" -c "$collection" -o col_dump
mongorestore -h "$prod_url" -u heroku -d "$to_app" -p"$to_token" --dir col_dump/"$col_dump"/$collection".bson -c "$collection"

What's a good (free) visual merge tool for Git? (on windows)

Another free option is jmeld: http://keeskuip.home.xs4all.nl/jmeld/

It's a java tool and could therefore be used on several platforms.

But (as Preet mentioned in his answer), free is not always the best option. The best diff/merge tool I ever came across is Araxis Merge. Standard edition is available for 99 EUR which is not that much.

They also provide a documentation for how to integrate Araxis with msysGit.

If you want to stick to a free tool, JMeld comes pretty close to Araxis.

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

How to strip HTML tags from string in JavaScript?

I know this question has an accepted answer, but I feel that it doesn't work in all cases.

For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):

http://phpjs.org/functions/strip_tags:535

It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script /> tag above.

How to parse this string in Java?

In this case, why not use new File("prefix/dir1/dir2/dir3/dir4") and go from there?

sendKeys() in Selenium web driver

The simplest solution is Go to Build Path > Configure Build Path > Java Compiler and then select the 'Compiler compliance level:' to the latest one from 1.4 (probably you have this).

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

*.h or *.hpp for your class definitions

The extension of the source file may have meaning to your build system, for example, you might have a rule in your makefile for .cpp or .c files, or your compiler (e.g. Microsoft cl.exe) might compile the file as C or C++ depending on the extension.

Because you have to provide the whole filename to the #include directive, the header file extension is irrelevant. You can include a .c file in another source file if you like, because it's just a textual include. Your compiler might have an option to dump the preprocessed output which will make this clear (Microsoft: /P to preprocess to file, /E to preprocess to stdout, /EP to omit #line directives, /C to retain comments)

You might choose to use .hpp for files that are only relevant to the C++ environment, i.e. they use features that won't compile in C.

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

I just tested your snippet, and their is no double spacing line here. The end-of-line are \r\n, so what i would check in your case is:

  1. your editor is reading correctly DOS file
  2. no \n exist in values of your rows dict.

(Note that even by putting a value with \n, DictWriter automaticly quote the value.)

Add a column to existing table and uniquely number them on MS SQL Server

for oracle you could do something like below

alter table mytable add (myfield integer);

update mytable set myfield = rownum;

How to convert FormData (HTML5 object) to JSON

If you need support for serializing nested fields, similar to how PHP handles form fields, you can use the following function

_x000D_
_x000D_
function update(data, keys, value) {_x000D_
  if (keys.length === 0) {_x000D_
    // Leaf node_x000D_
    return value;_x000D_
  }_x000D_
_x000D_
  let key = keys.shift();_x000D_
  if (!key) {_x000D_
    data = data || [];_x000D_
    if (Array.isArray(data)) {_x000D_
      key = data.length;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Try converting key to a numeric value_x000D_
  let index = +key;_x000D_
  if (!isNaN(index)) {_x000D_
    // We have a numeric index, make data a numeric array_x000D_
    // This will not work if this is a associative array _x000D_
    // with numeric keys_x000D_
    data = data || [];_x000D_
    key = index;_x000D_
  }_x000D_
  _x000D_
  // If none of the above matched, we have an associative array_x000D_
  data = data || {};_x000D_
_x000D_
  let val = update(data[key], keys, value);_x000D_
  data[key] = val;_x000D_
_x000D_
  return data;_x000D_
}_x000D_
_x000D_
function serializeForm(form) {_x000D_
  return Array.from((new FormData(form)).entries())_x000D_
    .reduce((data, [field, value]) => {_x000D_
      let [_, prefix, keys] = field.match(/^([^\[]+)((?:\[[^\]]*\])*)/);_x000D_
_x000D_
      if (keys) {_x000D_
        keys = Array.from(keys.matchAll(/\[([^\]]*)\]/g), m => m[1]);_x000D_
        value = update(data[prefix], keys, value);_x000D_
      }_x000D_
      data[prefix] = value;_x000D_
      return data;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
document.getElementById('output').textContent = JSON.stringify(serializeForm(document.getElementById('form')), null, 2);
_x000D_
<form id="form">_x000D_
  <input name="field1" value="Field 1">_x000D_
  <input name="field2[]" value="Field 21">_x000D_
  <input name="field2[]" value="Field 22">_x000D_
  <input name="field3[a]" value="Field 3a">_x000D_
  <input name="field3[b]" value="Field 3b">_x000D_
  <input name="field3[c]" value="Field 3c">_x000D_
  <input name="field4[x][a]" value="Field xa">_x000D_
  <input name="field4[x][b]" value="Field xb">_x000D_
  <input name="field4[x][c]" value="Field xc">_x000D_
  <input name="field4[y][a]" value="Field ya">_x000D_
  <input name="field5[z][0]" value="Field z0">_x000D_
  <input name="field5[z][]" value="Field z1">_x000D_
  <input name="field6.z" value="Field 6Z0">_x000D_
  <input name="field6.z" value="Field 6Z1">_x000D_
</form>_x000D_
_x000D_
<h2>Output</h2>_x000D_
<pre id="output">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Replace first occurrence of pattern in a string

public string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

here is an Extension Method that could also work as well per VoidKing request

public static class StringExtensionMethods
{
    public static string ReplaceFirst(this string text, string search, string replace)
    {
      int pos = text.IndexOf(search);
      if (pos < 0)
      {
        return text;
      }
      return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

Adding a line break in MySQL INSERT INTO text

In SQL or MySQL you can use the char or chr functions to enter in an ASCII 13 for carriage return line feed, the \n equivilent. But as @David M has stated, you are most likely looking to have the HTML show this break and a br is what will work.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

How to define a circle shape in an Android XML drawable file?

You can use VectorDrawable as below :

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="200dp"
    android:viewportHeight="64"
    android:viewportWidth="64">

    <path
        android:fillColor="#ff00ff"
        android:pathData="M22,32
        A10,10 0 1,1 42,32
        A10,10 0 1,1 22,32 Z" />
</vector>

The above xml renders as :

enter image description here

Working with time DURATION, not time of day

The best way I found to resolve this issue was by using a combination of the above. All my cells were entered as a Custom Format to only show "HH:MM" - if I entered in "4:06" (being 4 minutes and 6 seconds) the field would show the numbers I entered correctly - but the data itself would represent HH:MM in the background.

Fortunately time is based on factors of 60 (60 seconds = 60 minutes). So 7H:15M / 60 = 7M:15S - I hope you can see where this is going. Accordingly, if I take my 4:06 and divide by 60 when working with the data (eg. to total up my total time or average time across 100 cells I would use the normal SUM or AVERAGE formulas and then divide by 60 in the formula.

Example =(SUM(A1:A5))/60. If my data was across the 5 time tracking fields was the 4:06, 3:15, 9:12, 2:54, 7:38 (representing MM:SS for us, but the data in the background is actually HH:MM) then when I work out the sum of those 5 fields are, what I want should be 27M:05S but what shows instead is 1D:03H:05M:00S. As mentioned above, 1D:3H:5M divided by 60 = 27M:5S ... which is the sum I am looking for.

Further examples of this are: =(SUM(G:G))/60 and =(AVERAGE(B2:B90)/60) and =MIN(C:C) (this is a direct check so no /60 needed here!).

Note that your "formula" or "calculation" fields (average, total time, etc) MUST have the custom format of MM:SS once you have divided by 60 as Excel's default thinking is in HH:MM (hence this issue). Your data fields where you are entering in your times should need to be changed from "General" or "Number" format to the custom format of HH:MM.

This process is still a little bit cumbersome to use - but it does mean that your data entry is still entered in very easy and is "correctly" displayed on screen as 4:06 (which most people would view as minutes:seconds when under a "Minutes" header). Generally there will only be a couple of fields needing to be used for formulas such as "best time", "average time", "total time" etc when tracking times and they will not usually be changed once the formula is entered so this will be a "one off" process - I use this for my call tracking sheet at work to track "average call", "total call time for day".

Replacing characters in Ant property

Two possibilities :

via script task and builtin javascript engine (if using jdk >= 1.6)

<project>

 <property name="propA" value="This is a value"/>

 <script language="javascript">
  project.setProperty('propB', project.getProperty('propA').
   replace(" ", "_"));
 </script>
 <echo>$${propB} => ${propB}</echo>

</project>

or using Ant addon Flaka

<project xmlns:fl="antlib:it.haefelinger.flaka">

 <property name="propA" value="This is a value"/>

 <fl:let> propB := replace('${propA}', '_', ' ')</fl:let>

 <echo>$${propB} => ${propB}</echo>

</project>

to overwrite exisiting property propA simply replace propB with propA

How to get a random value from dictionary?

To select 50 random key values from a dictionary set dict_data:

sample = random.sample(set(dict_data.keys()), 50)

Checking for duplicate strings in JavaScript array

   var elems = ['f', 'a','b','f', 'c','d','e','f','c'];

    elems.sort();

    elems.forEach(function (value, index, arr){

        let first_index = arr.indexOf(value);
        let last_index = arr.lastIndexOf(value);

         if(first_index !== last_index){

         console.log('Duplicate item in array ' + value);

         }else{

         console.log('unique items in array ' + value);

         }

    });

How to unit test abstract classes: extend with stubs?

One of the main motivations for using an abstract class is to enable polymorphism within your application -- i.e: you can substitute a different version at runtime. In fact, this is very much the same thing as using an interface except the abstract class provides some common plumbing, often referred to as a Template pattern.

From a unit testing perspective, there are two things to consider:

  1. Interaction of your abstract class with it related classes. Using a mock testing framework is ideal for this scenario as it shows that your abstract class plays well with others.

  2. Functionality of derived classes. If you have custom logic that you've written for your derived classes, you should test those classes in isolation.

edit: RhinoMocks is an awesome mock testing framework that can generate mock objects at runtime by dynamically deriving from your class. This approach can save you countless hours of hand-coding derived classes.

Getting the current Fragment instance in the viewpager

Current Fragment:

This works if you created a project with the fragments tabbar template.

Fragment f = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());

Note that this works with the default tabbed activity template implementation.

ImportError: No module named MySQLdb

It depends on Python Version as well in my experience.

If you are using Python 3, @DazWorrall answer worked fine for me.

However, if you are using Python 2, you should

sudo pip install mysql-python

which would install 'MySQLdb' module without having to change the SQLAlchemy URI.

querySelectorAll with multiple conditions

With pure JavaScript you can do this (such as SQL) and anything you need, basically:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input type='button' value='F3' class="c2" id="btn_1">_x000D_
<input type='button' value='F3' class="c3" id="btn_2">_x000D_
<input type='button' value='F1' class="c2" id="btn_3">_x000D_
_x000D_
<input type='submit' value='F2' class="c1" id="btn_4">_x000D_
<input type='submit' value='F1' class="c3" id="btn_5">_x000D_
<input type='submit' value='F2' class="c1" id="btn_6">_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<script>_x000D_
    function myFunction() _x000D_
    {_x000D_
        var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
_x000D_
            arrFiltered.forEach(function (el)_x000D_
            {                _x000D_
                var node = document.createElement("p");_x000D_
                _x000D_
                node.innerHTML = el.getAttribute('id');_x000D_
_x000D_
                window.document.body.appendChild(node);_x000D_
            });_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

get client time zone from browser

I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):

var ClientTZ = {
    UTCoffset:  0,          // Browser time offset from UTC in minutes
    UTCoffsetT: '+0000S',   // Browser time offset from UTC in '±hhmmD' form
    hasDST:     false,      // Browser time observes DST

    // Determine browser's timezone and DST
    getBrowserTZ: function () {
        var self = ClientTZ;

        // Determine UTC time offset
        var now = new Date();
        var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0);    // Jan
        var diff1 = -date1.getTimezoneOffset();
        self.UTCoffset = diff1;

        // Determine DST use
        var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0);    // Jun
        var diff2 = -date2.getTimezoneOffset();
        if (diff1 != diff2) {
            self.hasDST = true;
            if (diff1 - diff2 >= 0)
                self.UTCoffset = diff2;     // East of GMT
        }

        // Convert UTC offset to ±hhmmD form
        diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
        var hr = Math.floor(diff2);
        var min = diff2 - hr;
        diff2 = hr * 100 + min * 60;
        self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');

        return self.UTCoffset;
    }
};

// Onload
ClientTZ.getBrowserTZ();

Upon loading, the ClientTZ.getBrowserTZ() function is executed, which sets:

  • ClientTZ.UTCoffset to the browser time offset from UTC in minutes (e.g., CST is -360 minutes, which is -6.0 hours from UTC);
  • ClientTZ.UTCoffsetT to the offset in the form '±hhmmD' (e.g., '-0600D'), where the suffix is D for DST and S for standard (non-DST);
  • ClientTZ.hasDST (to true or false).

The ClientTZ.UTCoffset is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).

The intent behind ClientTZ.UTCoffsetT is to use it as a key into a table of timezones (not provided here), such as for a drop-down <select> list.

View stored procedure/function definition in MySQL

If you want to know the list of procedures you can run the following command -

show procedure status;

It will give you the list of procedures and their definers Then you can run the show create procedure <procedurename>;

jquery clone div and append it after specific div

try this out

$("div[id^='car']:last").after($('#car2').clone());

How to use a client certificate to authenticate and authorize in a Web API

Make sure HttpClient has access to the full client certificate (including the private key).

You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.

Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).

How to use ng-repeat without an html element

The above is correct but for a more general answer it is not enough. I needed to nest ng-repeat, but stay on the same html level, meaning write the elements in the same parent. The tags array contain tag(s) that also have a tags array. It is actually a tree.

[{ name:'name1', tags: [
  { name: 'name1_1', tags: []},
  { name: 'name1_2', tags: []}
  ]},
 { name:'name2', tags: [
  { name: 'name2_1', tags: []},
  { name: 'name2_2', tags: []}
  ]}
]

So here is what I eventually did.

<div ng-repeat-start="tag1 in tags" ng-if="false"></div>
    {{tag1}},
  <div ng-repeat-start="tag2 in tag1.tags" ng-if="false"></div>
    {{tag2}},
  <div ng-repeat-end ng-if="false"></div>
<div ng-repeat-end ng-if="false"></div>

Note the ng-if="false" that hides the start and end divs.

It should print

name1,name1_1,name1_2,name2,name2_1,name2_2,

How to create full compressed tar file using Python?

import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
    tar.add(name)
tar.close()

If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2".

How to create a HTTP server in Android?

Another server you can try http://tjws.sf.net, actually it already provides Android enabled version.

How to import Maven dependency in Android Studio/IntelliJ?

I am using the springframework android artifact as an example

open build.gradle

Then add the following at the same level as apply plugin: 'android'

apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
   compile group: 'org.springframework.android', name: 'spring-android-rest-template', version: '1.0.1.RELEASE'
}

you can also use this notation for maven artifacts

compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'

Your IDE should show the jar and its dependencies under 'External Libraries' if it doesn't show up try to restart the IDE (this happened to me quite a bit)

here is the example that you provided that works

buildscript { 
    repositories { 
        maven { 
            url 'repo1.maven.org/maven2'; 
        } 
    } 
    dependencies { 
        classpath 'com.android.tools.build:gradle:0.4' 
    } 
} 
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies { 
    compile files('libs/android-support-v4.jar') 
    compile group:'com.squareup.picasso', name:'picasso', version:'1.0.1' 
} 
android { 
    compileSdkVersion 17 
    buildToolsVersion "17.0.0" 
    defaultConfig { 
        minSdkVersion 14 
        targetSdkVersion 17 
    } 
} 

Jquery: Find Text and replace

$("#id1 p:contains('dog')").html("doll");

that'll do it.

http://jsfiddle.net/pgDFQ/

Copy rows from one table to another, ignoring duplicates

Have you tried SELECT DISTINCT ?

INSERT INTO destTable
SELECT DISTINCT * FROM srcTable

Change background color on mouseover and remove it after mouseout

Set the original background-color in you CSS file:

.forum{
    background-color:#f0f;
}?

You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.

$(function() {
    $(".forum").hover(
    function() {
        $(this).css('background-color', '#ff0')
    }, function() {
        $(this).css('background-color', '')
    });
});?

How to automatically generate unique id in SQL like UID12345678?

Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

How to convert PDF files to images

You can use Ghostscript to convert PDF to images.

To use Ghostscript from .NET you can take a look at Ghostscript.NET library (managed wrapper around the Ghostscript library).

To produce image from the PDF by using Ghostscript.NET, take a look at RasterizerSample.

To combine multiple images into the single image, check out this sample: http://www.niteshluharuka.com/2012/08/combine-several-images-to-form-a-single-image-using-c/#

How can I monitor the thread count of a process on linux?

Here is one command that displays the number of threads of a given process :

ps -L -o pid= -p <pid> | wc -l

Unlike the other ps based answers, there is here no need to substract 1 from its output as there is no ps header line thanks to the -o pid=option.

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

How do I convert from a string to an integer in Visual Basic?

You can try these:

Dim valueStr as String = "10"

Dim valueIntConverted as Integer = CInt(valueStr)

Another example:

Dim newValueConverted as Integer = Val("100")

Add JsonArray to JsonObject

I'm starting to learn about this myself, being very new to android development and I found this video very helpful.

https://www.youtube.com/watch?v=qcotbMLjlA4

It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.

Code from the video for JSONArray to JSONObject:

JSONArray queryArray = quoteJSONObject.names();

ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < queryArray.length(); i++){
    list.add(queryArray.getString(i));
}

for(String item : list){
    Log.v("JSON ARRAY ITEMS ", item);
}

Git: Could not resolve host github.com error while cloning remote repository in git

I guess my case was very rare, but GitHub was out down. Check their webpage to see if it loads properly.

GitHub

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

  • The execution of maven command required pom.xml file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.

  • Make sure that porject should contains pom.xml at the root level.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Best way to convert string to bytes in Python 3?

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

grep output to show only matching file

You can use the Unix-style -l switch – typically terse and cryptic – or the equivalent --files-with-matches – longer and more readable.

The output of grep --help is not easy to read, but it's there:

-l, --files-with-matches  print only names of FILEs containing matches

IN Clause with NULL or IS NULL

SELECT *
FROM tbl_name
WHERE coalesce(id_field,'unik_null_value') 
IN ('value1', 'value2', 'value3', 'unik_null_value')

So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.

Google access token expiration time

From Google OAuth2.0 for Client documentation,

  • expires_in -- The number of seconds left before the token becomes invalid.

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

Python3 integer division

Try this:

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

How do I prevent Eclipse from hanging on startup?

I had no snap files. Going through the help menu installation list, at least 90% of my plugins had the uninstall button deactivated so I could not handle it through there. Under startup/shutdown most of plugins were not listed. Instead, I had to manually remove items from my plugins folder. Wow, the startup time is much faster for me now. So if everything else does not work and you have plugins that are disposable, this could be the ultimate solution to use.

A valid provisioning profile for this executable was not found... (again)

After spending the day I realized it was a simple change in Project Settings

File -> Project Settings... -> Build System -> Legacy Build System.

In a project setting, you will see Build System named drop down and in that drop down select Legacy Build System

How to get only the date value from a Windows Forms DateTimePicker control?

I'm assuming you mean a datetime picker in a winforms application.

in your code, you can do the following:

string theDate = dateTimePicker1.Value.ToShortDateString();

or, if you'd like to specify the format of the date:

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

How to close off a Git Branch?

We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).

My fingers have memorized our process:

git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

First you use a full stop, then you hold down alt and press the letter H and put in another full stop. .?.

Get value of input field inside an iframe

Yes it should be possible, even if the site is from another domain.

For example, in an HTML page on my site I have an iFrame whose contents are sourced from another website. The iFrame content is a single select field.

I need to be able to read the selected value on my site. In other words, I need to use the select list from another domain inside my own application. I do not have control over any server settings.

Initially therefore we might be tempted to do something like this (simplified):

HTML in my site:

<iframe name='select_frame' src='http://www.othersite.com/select.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>

HTML contents of iFrame (loaded from select.php on another domain):

<select id='select_name'>
    <option value='john'>John</option>
    <option value='jim' selected>Jim</option>
</select>

jQuery:

$('input:button[name=save]').click(function() {
    var name = $('iframe[name=select_frame]').contents().find('#select_name').val();
});

However, I receive this javascript error when I attempt to read the value:

Blocked a frame with origin "http://www.myownsite.com" from accessing a frame with origin "http://www.othersite.com". Protocols, domains, and ports must match.

To get around this problem, it seems that you can indirectly source the iFrame from a script in your own site, and have that script read the contents from the other site using a method like file_get_contents() or curl etc.

So, create a script (for example: select_local.php in the current directory) on your own site with contents similar to this:

PHP content of select_local.php:

<?php
    $url = "http://www.othersite.com/select.php?" . $_SERVER['QUERY_STRING'];
    $html_select = file_get_contents($url);
    echo $html_select;
?>

Also modify the HTML to call this local (instead of the remote) script:

<iframe name='select_frame' src='select_local.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>

Now your browser should think that it is loading the iFrame content from the same domain.

List all indexes on ElasticSearch server?

I'll give you the query which you can run on kibana.

GET /_cat/indices?v

and the CURL version will be

CURL -XGET http://localhost:9200/_cat/indices?v

How do I replace NA values with zeros in an R dataframe?

You can use replace()

For example:

> x <- c(-1,0,1,0,NA,0,1,1)
> x1 <- replace(x,5,1)
> x1
[1] -1  0  1  0  1  0  1  1

> x1 <- replace(x,5,mean(x,na.rm=T))
> x1
[1] -1.00  0.00  1.00  0.00  0.29  0.00 1.00  1.00

String field value length in mongoDB

For MongoDB 3.6 and newer:

The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows:

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] } 
})

For MongoDB 3.4 and newer:

You can also use the aggregation framework with the $redact pipeline operator that allows you to proccess the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient.

As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.


Consider running the following aggregate operation which demonstrates the above concept:

db.usercollection.aggregate([
    { "$match": { "name": { "$exists": true } } },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$name" }, 40] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    },
    { "$limit": 2 }
])

If using $where, try your query without the enclosing brackets:

db.usercollection.find({$where: "this.name.length > 40"}).limit(2);

A better query would be to to check for the field's existence and then check the length:

db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2); 

or:

db.usercollection.find({name: {$exists: true}, $where: "this.name.length > 
40"}).limit(2); 

MongoDB evaluates non-$where query operations before $where expressions and non-$where query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where will be much slower compared to that. It's recommended to use JavaScript expressions and the $where operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.


A different and faster approach that avoids the use of the $where operator is the $regex operator. Consider the following pattern which searches for

db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2); 

Note - From the docs:

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.

Programmatically close aspx page from code behind

For closing a asp.net windows application,

  • Just drag a button into the design page
  • Then write the below given code inside its click event

           "   this.close();  "
    

ie:

 private void button2_Click(object sender, EventArgs e)  
 {
        this.Close();
 }

Error 'tunneling socket' while executing npm install

I also ran into the similar issue and was using CNTLM for proxy configuration. In my case HTTP_PROXY and HTTPS_PROXY are taking higher precedence over http_proxy and https_proxy so be aware of changing all proxy variables.

env|grep -i proxy

and make sure all of the below proxy variables should point to the same proxy.

HTTP-PROXY = "http://localhost:3128"
HTTPS-PROXY = "https://localhost:3128"
HTTPS_PROXY = "http://localhost:3128"
HTTP_PROXY = "http://localhost:3128"
PROXY = "http://localhost:3128"
http-proxy = "http://localhost:3128"
http_proxy = "http://localhost:3128"
https-proxy = "https://localhost:3128/"
https_proxy = "https://localhost:3128"
proxy = "http://localhost:3128/"

I know some variables are unneccessary but I'm not sure which is using what.

Why do you use typedef when declaring an enum in C++?

In some C codestyle guide the typedef version is said to be preferred for "clarity" and "simplicity". I disagree, because the typedef obfuscates the real nature of the declared object. In fact, I don't use typedefs because when declaring a C variable I want to be clear about what the object actually is. This choice helps myself to remember faster what an old piece of code actually does, and will help others when maintaining the code in the future.

How to change an Android app's name?

  1. Go to Strings.xml file under values.
  2. Change the app_name tag to your app_name to want and it is all set, you will be able to see the name you change now.

Copy or rsync command

Keep in mind that while transferring files internally on a machine i.e not network transfer, using the -z flag can have a massive difference in the time taken for the transfer.

Transfer within same machine

Case 1: With -z flag:
    TAR took: 9.48345208168
    Encryption took: 2.79352903366
    CP took = 5.07273387909
    Rsync took = 30.5113282204

Case 2: Without the -z flag:
    TAR took: 10.7535531521
    Encryption took: 3.0386879921
    CP took = 4.85565590858
    Rsync took = 4.94515299797

Checking if a key exists in a JS object

Use the in operator:

testArray = 'key1' in obj;

Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.

how to change text in Android TextView

@user264892

I found that when using a String variable I needed to either prefix with an String of "" or explicitly cast to CharSequence.

So instead of:

String Status = "Asking Server...";
txtStatus.setText(Status);

try:

String Status = "Asking Server...";
txtStatus.setText((CharSequence) Status);

or:

String Status = "Asking Server...";    
txtStatus.setText("" + Status);

or, since your string is not dynamic, even better:

txtStatus.setText("AskingServer...");

Gradle version 2.2 is required. Current version is 2.10

Just Change in build.gradle file

 classpath 'com.android.tools.build:gradle:1.3.0'

To

 classpath 'com.android.tools.build:gradle:2.0.0'
  1. Now GoTo -> menu choose File -> Invalidate Caches/Restart...

  2. Choose first option: Invalidate and Restart

    Android Studio would restart.

    After this, it should work normally.

Get current clipboard content?

Use the new clipboard API, via navigator.clipboard. It can be used like this:

navigator.clipboard.readText()
  .then(text => {
    console.log('Pasted content: ', text);
  })
  .catch(err => {
    console.error('Failed to read clipboard contents: ', err);
  });

Or with async syntax:

const text = await navigator.clipboard.readText();

Keep in mind that this will prompt the user with a permission request dialog box, so no funny business possible.

The above code will not work if called from the console. It only works when you run the code in an active tab. To run the code from your console you can set a timeout and click in the website window quickly:

setTimeout(async () => {
  const text = await navigator.clipboard.readText();
  console.log(text);
}, 2000);

Read more on the API and usage in the Google developer docs.

Spec

Google Maps: How to create a custom InfoWindow?

I'm not sure how FWIX.com is doing it specifically, but I'd wager they are using Custom Overlays.

Disabling Log4J Output in Java

In addition, it is also possible to turn logging off programmatically:

Logger.getRootLogger().setLevel(Level.OFF);

Or

Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

These use imports:

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.NullAppender;

How to use struct timeval to get the execution time?

You have two typing errors in your code:

 struct timeval,

should be

 struct timeval

and after the printf() parenthesis you need a semicolon.

Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.

Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec and subtract "before" tv_usec. You gain nothing by casting an integer number of seconds to a float.

I'd suggest checking out the man page for struct timeval.

This is the code:

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;
    }

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;
}

CSS center content inside div

Try using flexbox. As an example, the following code shows the CSS for the container div inside which the contents needs to be centered aligned:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;

}

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

THE FINAL ANSWER FOR THOSE WHO USES ANGULAR 6:

Add the below command in your *.service.ts file"

import { map } from "rxjs/operators";

**********************************************Example**Below**************************************
getPosts(){
this.http.get('http://jsonplaceholder.typicode.com/posts')
.pipe(map(res => res.json()));
}
}

I am using windows 10;

angular6 with typescript V 2.3.4.0

How do I find files that do not contain a given string pattern?

Problem

I need to refactor a large project which uses .phtml files to write out HTML using inline PHP code. I want to use Mustache templates instead. I want to find any .phtml giles which do not contain the string new Mustache as these still need to be rewritten.

Solution

find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

Explanation

Before the pipes:

Find

find . Find files recursively, starting in this directory

-iname '*.phtml' Filename must contain .phtml (the i makes it case-insensitive)

-exec 'grep -H -E -o -c 'new Mustache' {}' Run the grep command on each of the matched paths

Grep

-H Always print filename headers with output lines.

-E Interpret pattern as an extended regular expression (i.e. force grep to behave as egrep).

-o Prints only the matching part of the lines.

-c Only a count of selected lines is written to standard output.


This will give me a list of all file paths ending in .phtml, with a count of the number of times the string new Mustache occurs in each of them.

$> find . -iname '*.phtml$' -exec 'grep -H -E -o -c 'new Mustache' {}'\;

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/orders.phtml:1
./app/MyApp/Customer/View/Account/banking.phtml:1
./app/MyApp/Customer/View/Account/applycomplete.phtml:1
./app/MyApp/Customer/View/Account/catalogue.phtml:1
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The first pipe grep :0$ filters this list to only include lines ending in :0:

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The second pipe sed 's/..$//' strips off the final two characters of each line, leaving just the file paths.

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml
./app/MyApp/Customer/View/Account/studio.phtml
./app/MyApp/Customer/View/Account/classadd.phtml
./app/MyApp/Customer/View/Account/orders-trade.phtml

Changing the default icon in a Windows Forms application

On the solution explorer, right click on the project title and select the 'Properties' on the context menu to open the 'Project Property' form. In the 'Application' tab, on the 'Resources' group box there is a entry field where you can select the icon file you want for your application.

How to remove a class from elements in pure JavaScript?

It's 2021... keep it simple.

Times have changed and now the cleanest and most readable way to do this is:

Array.from(document.querySelectorAll('widget hover')).forEach((el) => el.classList.remove('hover'));

If you can't support arrow functions then just convert it like this:

Array.from(document.querySelectorAll('widget hover')).forEach(function(el) { 
    el.classList.remove('hover');
});

Additionally if you need to support extremely old browsers then use a polyfil for the forEach and Array.from and move on with your life.

Rails: How to reference images in CSS within Rails 4

In css

background: url("/assets/banner.jpg");

although the original path is /assets/images/banner.jpg, by convention you have to add just /assets/ in the url method

MySQL VARCHAR size?

100 characters.

This is the var (variable) in varchar: you only store what you enter (and an extra 2 bytes to store length upto 65535)

If it was char(200) then you'd always store 200 characters, padded with 100 spaces

See the docs: "The CHAR and VARCHAR Types"

How to redirect output of an already running process

You can also do it using reredirect (https://github.com/jerome-pouiller/reredirect/).

The command bellow redirects the outputs (standard and error) of the process PID to FILE:

reredirect -m FILE PID

The README of reredirect also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.

The tool also provides relink, a script allowing to redirect the outputs to the current terminal:

relink PID
relink PID | grep usefull_content

(reredirect seems to have same features than Dupx described in another answer but, it does not depend on Gdb).

Which is the preferred way to concatenate a string in Python?

While somewhat dated, Code Like a Pythonista: Idiomatic Python recommends join() over + in this section. As does PythonSpeedPerformanceTips in its section on string concatenation, with the following disclaimer:

The accuracy of this section is disputed with respect to later versions of Python. In CPython 2.5, string concatenation is fairly fast, although this may not apply likewise to other Python implementations. See ConcatenationTestCode for a discussion.

List of Java class file format major version numbers?

If you're having some problem about "error compiler of class file", it's possible to resolve this by changing the project's JRE to its correspondent through Eclipse.

  1. Build path
  2. Configure build path
  3. Change library to correspondent of table that friend shows last.
  4. Create "jar file" and compile and execute.

I did that and it worked.

How to serialize an object into a string

How about persisting the object as a blob

How to create a self-signed certificate for a domain name for development?

Another option is to create a self-signed certificate that allows you to specify the domain name per website. This means you can use it across many domain names.

In IIS Manager

  1. Click machine name node
  2. Open Server Certificates
  3. In Actions panel, choose 'Create Self-Signed Certificate'
  4. In 'Specify a friendly name...' name it *Dev (select 'Personal' from type list)
  5. Save

Now, on your website in IIS...

  1. Manage the bindings
  2. Create a new binding for Https
  3. Choose your self-signed certificate from the list
  4. Once selected, the domain name box will become enabled and you'll be able to input your domain name.

enter image description here

android - save image into gallery

You can create a directory inside the camera folder and save the image. After that, you can simply perform your scan. It will instantly show your image in the gallery.

String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()+ "/Camera/Your_Directory_Name";
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name + ".png";
File file = new File(myDir, fname);
System.out.println(file.getAbsolutePath());
if (file.exists()) file.delete();
    Log.i("LOAD", root + fname);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
       e.printStackTrace();
    }

MediaScannerConnection.scanFile(context, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);

RecyclerView onClick

If you want to catch click event On Individual items then just implement OnClickListener in ViewHolder class and then set click listeners on individual views or whole itemView.

Following example shows the same

public  class ContactViewHolder extends RecyclerView.ViewHolder implements OnClickListener
    {
        TextView txt_title,txt_name,txt_email;

        public ContactViewHolder(View itemView) 
        {
            super(itemView);
            txt_title = (TextView)itemView.findViewById(R.id.txt_title);
            txt_name  = (TextView)itemView.findViewById(R.id.txt_name);
            txt_email = (TextView)itemView.findViewById(R.id.txt_email);

            txt_name.setOnClickListener(this);
            txt_email.setOnClickListener(this);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if(v == itemView)
            {
                Toast.makeText(RecyclerDemoActivity.this, "Visiting Card Clicked is ==>"+txt_name.getText(), Toast.LENGTH_SHORT).show();
            }

            if(v == txt_name)
            {
                Toast.makeText(RecyclerDemoActivity.this, "Name ==>"+txt_name.getText(), Toast.LENGTH_SHORT).show();
            }

            if(v == txt_email)
            {
                Toast.makeText(RecyclerDemoActivity.this, "Email ==>"+txt_email.getText(), Toast.LENGTH_SHORT).show();
            }
        }

    }
} 

Selenium WebDriver and DropDown Boxes

You can use this

(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");

How does HTTP file upload work?

Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):

POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"

100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--

NOTE: each boundary string must be prefixed with an extra --, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.

Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.

In the example above, you can see the input MAX_FILE_SIZE with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition header.

The full details are here.

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

Bootstrap full responsive navbar with logo or brand name text

I set .navbar-brand { min-height: inherit } which solved the issue for me (thanks @creimers for inspiration).

How to programmatically send SMS on the iPhone?

Restrictions

If you could send an SMS within a program on the iPhone, you'll be able to write games that spam people in the background. I'm sure you really want to have spams from your friends, "Try out this new game! It roxxers my boxxers, and yours will be too! roxxersboxxers.com!!!! If you sign up now you'll get 3,200 RB points!!"

Apple has restrictions for automated (or even partially automated) SMS and dialing operations. (Imagine if the game instead dialed 911 at a particular time of day)

Your best bet is to set up an intermediate server on the internet that uses an online SMS sending service and send the SMS via that route if you need complete automation. (ie, your program on the iPhone sends a UDP packet to your server, which sends the real SMS)

iOS 4 Update

iOS 4, however, now provides a viewController you can import into your application. You prepopulate the SMS fields, then the user can initiate the SMS send within the controller. Unlike using the "SMS:..." url format, this allows your application to stay open, and allows you to populate both the to and the body fields. You can even specify multiple recipients.

This prevents applications from sending automated SMS without the user explicitly aware of it. You still cannot send fully automated SMS from the iPhone itself, it requires some user interaction. But this at least allows you to populate everything, and avoids closing the application.

The MFMessageComposeViewController class is well documented, and tutorials show how easy it is to implement.

iOS 5 Update

iOS 5 includes messaging for iPod touch and iPad devices, so while I've not yet tested this myself, it may be that all iOS devices will be able to send SMS via MFMessageComposeViewController. If this is the case, then Apple is running an SMS server that sends messages on behalf of devices that don't have a cellular modem.

iOS 6 Update

No changes to this class.

iOS 7 Update

You can now check to see if the message medium you are using will accept a subject or attachments, and what kind of attachments it will accept. You can edit the subject and add attachments to the message, where the medium allows it.

iOS 8 Update

No changes to this class.

iOS 9 Update

No changes to this class.

iOS 10 Update

No changes to this class.

iOS 11 Update

No significant changes to this class

Limitations to this class

Keep in mind that this won't work on phones without iOS 4, and it won't work on the iPod touch or the iPad, except, perhaps, under iOS 5. You must either detect the device and iOS limitations prior to using this controller, or risk restricting your app to recently upgraded 3G, 3GS, and 4 iPhones.

However, an intermediate server that sends SMS will allow any and all of these iOS devices to send SMS as long as they have internet access, so it may still be a better solution for many applications. Alternately, use both, and only fall back to an online SMS service when the device doesn't support it.

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

How do I remove all .pyc files from a project?

Further, people usually want to remove all *.pyc, *.pyo files and __pycache__ directories recursively in the current directory.

Command:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

PHP: HTTP or HTTPS?

If the request was sent with HTTPS you will have a extra parameter in the $_SERVER superglobal - $_SERVER['HTTPS']. You can check if it is set or not

if( isset($_SERVER['HTTPS'] ) ) {

Web scraping with Java

jsoup

Extracting the title is not difficult, and you have many options, search here on Stack Overflow for "Java HTML parsers". One of them is Jsoup.

You can navigate the page using DOM if you know the page structure, see http://jsoup.org/cookbook/extracting-data/dom-navigation

It's a good library and I've used it in my last projects.

How can I get selector from jQuery object

Try this:

$("*").click(function(event){
    console.log($(event.handleObj.selector));
 });

Why can't I display a pound (£) symbol in HTML?

This works in all chrome, IE, Firefox.

In Database > table > field type .for example set the symbol column TO varchar(2) utf8_bin php code:

$symbol = '£';
echo mb_convert_encoding($symbol, 'UTF-8', 'HTML-ENTITIES');
or 
html_entity_decode($symbol, ENT_NOQUOTES, 'UTF-8');

And also make sure set the HTML OR XML encoding to encoding="UTF-8"

Note: You should make sure that database, document type and php code all have a same encoding

How ever the better solution would be using &pound;

Loop through JSON object List

I have the following call:

$('#select_box_id').change(function() {
        var action = $('#my_form').attr('action');
    $.get(action,{},function(response){
        $.each(response.result,function(i) {

            alert("key is: " + i + ", val is: " + response.result[i]);

        });
    }, 'json');
    });

The structure coming back from the server look like:

{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}

Connecting an input stream to an outputstream

How about just using

void feedInputToOutput(InputStream in, OutputStream out) {
   IOUtils.copy(in, out);
}

and be done with it?

from jakarta apache commons i/o library which is used by a huge amount of projects already so you probably already have the jar in your classpath already.

How can I create database tables from XSD files?

I use XSLT to do that. Write up your XSD then pass your data models through a hand written XSLT that outputs SQL commands. Writing an XSLT is way faster and reusable than a custom program /script you may write.

At least thats how I do it at work, and thanks to that I got time to hang out on SO :)

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

Angular: Can't find Promise, Map, Set and Iterator

Another good solution. You need create a file typings.json in root directory of project with content:

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

Then install global or local typings package, if it not installed (i am install it global):

sudo npm install --global typings

In project root directory run command:

typings install

After that problem is solved. Not needed to change tsconfig target to es6 or es7. Your web application do not support after that some old version of browsers.

Importing files from different folder

I bumped into the same question several times, so I would like to share my solution.

Python Version: 3.X

The following solution is for someone who develops your application in Python version 3.X because Python 2 is not supported since Jan/1/2020.

Project Structure

In python 3, you don't need __init__.py in your project subdirectory due to the Implicit Namespace Packages. See Is init.py not required for packages in Python 3.3+

Project 
+-- main.py
+-- .gitignore
|
+-- a
|   +-- file_a.py
|
+-- b
    +-- file_b.py

Problem Statement

In file_b.py, I would like to import a class A in file_a.py under the folder a.

Solutions

#1 A quick but dirty way

Without installing the package like you are currently developing a new project

Using the try catch to check if the errors. Code example:

import sys
try:
    # The insertion index should be 1 because index 0 is this file
    sys.path.insert(1, '/absolute/path/to/folder/a')  # the type of path is string
    # because the system path already have the absolute path to folder a
    # so it can recognize file_a.py while searching 
    from file_a import A
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

#2 Install your package

Once you installed your application (in this post, the tutorial of installation is not included)

You can simply

try:
    from __future__ import absolute_import
    # now it can reach class A of file_a.py in folder a 
    # by relative import
    from ..a.file_a import A  
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

Happy coding!

Shell script to delete directories older than n days

If you want to delete all subdirectories under /path/to/base, for example

/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3

but you don't want to delete the root /path/to/base, you have to add -mindepth 1 and -maxdepth 1 options, which will access only the subdirectories under /path/to/base

-mindepth 1 excludes the root /path/to/base from the matches.

-maxdepth 1 will ONLY match subdirectories immediately under /path/to/base such as /path/to/base/dir1, /path/to/base/dir2 and /path/to/base/dir3 but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:

/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1

and so forth.

So , to delete all the sub-directories under /path/to/base which are older than 10 days;

find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf

C++ floating point to integer type conversions

the easiest technique is to just assign float to int, for example:

int i;
float f;
f = 34.0098;
i = f;

this will truncate everything behind floating point or you can round your float number before.

How can I count the numbers of rows that a MySQL query returned?

Getting total rows in a query result...

You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.

This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:

$link = mysqli_connect("localhost", "user", "password", "database");

$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);

echo "$num_rows Rows\n";

Getting a count of rows matching some criteria...

Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:

SELECT COUNT(*) FROM foo WHERE bar= 'value';

Get total rows when LIMIT is used...

If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();

SELECT SQL_CALC_FOUND_ROWS * FROM foo
   WHERE bar="value" 
   LIMIT 10;

SELECT FOUND_ROWS();

For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

You are missing the python mysqldb library. Use this command (for Debian/Ubuntu) to install it: sudo apt-get install python-mysqldb

ValueError: unconverted data remains: 02:05

You have to parse all of the input string, you cannot just ignore parts.

from datetime import date, datetime

for item in j:
    st = datetime.strptime(item['start'], '%A %d %B %H:%M')

    if st.date() == date.today():
        item['start'] = st.time()

Here, we compare the date to today's date by using more datetime objects instead of trying to use strings.

The alternative is to only pass in part of the item['start'] string (splitting out just the time), but there really is no point here, not when you could just parse everything in one step first.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

In my case, the issue was with my Xcode build scheme. When you run react-native run-ios you may see something like,

  • info Found Xcode workspace "myproject.xcworkspace"*

  • info Building (using "xcodebuild -workspace myproject.xcworkspace -configuration Debug -scheme myproject -destination id=xxxxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxxx -derivedDataPath build/myproject")*


In this case, there should be a scheme named myproject in your ios configurations. The way I fixed it is,

Double clicked on myproject.xcworkspace in ios directory (to open workspace with Xcode)

Navigate into Product > Scheme > Manage Schemes...

Created a Scheme appropriately with name myproject (this name is case-sensitive)

Ran react-native run-ios in project directory

How to validate phone numbers using regex

If at all possible, I would recommend to have four separate fields—Area Code, 3-digit prefix, 4 digit part, extension—so that the user can input each part of the address separately, and you can verify each piece individually. That way you can not only make verification much easier, you can store your phone numbers in a more consistent format in the database.

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Limiting the number of characters in a JTextField

It's weird that the Swing toolkit doesn't include this functionality, but here's the best answer to your question:

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

I use this in a fun guessing game example in my Udemy.com course "Learn Java Like a Kid". Cheers - Bryson

PHP header() redirect with POST variables

Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:

if(correct){
    header("Location: passed.php");
} else {
    $smarty->assign("variables", $_POST);
    $smarty->display("register_error.php");
    exit;
}

I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.

If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it

ex.

register.php?name=mr_jones&address==......
echo $_GET[name];

How can I access Google Sheet spreadsheets only with Javascript?

I have created a simple javascript library that retrieves google spreadsheet data (if they are published) via the JSON api:

https://github.com/mikeymckay/google-spreadsheet-javascript

You can see it in action here:

http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html

Ruby capitalize every word first letter

try this:

puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')

#=> One Two Three Four

or

puts 'one TWO three foUR'.split.map(&:capitalize)*' '

Check if a string is a valid date using DateTime.TryParse

Try using

DateTime.ParseExact(
    txtPaymentSummaryBeginDate.Text.Trim(),
    "MM/dd/yyyy", 
    System.Globalization.CultureInfo.InvariantCulture
);

It throws an exception if the input string is not in proper format, so in the catch section you can return false;

Function to check if a string is a date

Here's a different approach without using a regex:

function check_your_datetime($x) {
    return (date('Y-m-d H:i:s', strtotime($x)) == $x);
}

Insert array into MySQL database with PHP

$query= "INSERT INTO table ( " . implode(', ',array_keys($insData)) . ") VALUES (" . implode(', ',array_values($insData)) . ")";

Only need to write this line to insert an array into a database.

implode(', ',array_keys($insData)) : Gives you all keys as string format

implode(', ',array_values($insData)) : Gives you all values as string format

How to include JavaScript file or library in Chrome console?

I use this to load ko knockout object in console

document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");

or host locally

document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");

Making the Android emulator run faster

I would like to suggest giving Genymotion a spin. It runs in Oracle's VirtualBox, and will legitimately hit 60 fps on a moderate system.

Here's a screencap from one of my workshops, running on a low-end 2012 model MacBook Air:

Nexus 7 emulator running at 56.6 fps

If you can't read the text, it's a Nexus 7 emulator running at 56.6 fps. The additional (big!) bonus is that Google Play and Google Play Services come packaged with the virtual machines.

(The source of the demoed animation can be found here.)

ScrollTo function in AngularJS

Thanks Andy for the example, this was very helpful. I ended implementing a slightly different strategy since I am developing a single-page scroll and did not want Angular to refresh when using the hashbang URL. I also want to preserve the back/forward action of the browser.

Instead of using the directive and the hash, I am using a $scope.$watch on the $location.search, and obtaining the target from there. This gives a nice clean anchor tag

<a ng-href="#/?scroll=myElement">My element</a>

I chained the watch code to the my module declaration in app.js like so:

.run(function($location, $rootScope) {
   $rootScope.$watch(function() { return $location.search() }, function(search) { 
     var scrollPos = 0;
     if (search.hasOwnProperty('scroll')) {
       var $target = $('#' + search.scroll);
       scrollPos = $target.offset().top;
     }   
     $("body,html").animate({scrollTop: scrollPos}, "slow");
   });
})

The caveat with the code above is that if you access by URL directly from a different route, the DOM may not be loaded in time for jQuery's $target.offset() call. The solution is to nest this code within a $viewContentLoaded watcher. The final code looks something like this:

.run(function($location, $rootScope) {
  $rootScope.$on('$viewContentLoaded', function() {
     $rootScope.$watch(function() { return $location.search() }, function(search) {
       var scrollPos = 0 
       if (search.hasOwnProperty('scroll')) {
         var $target = $('#' + search.scroll);
         var scrollPos = $target.offset().top;
       }
       $("body,html").animate({scrollTop: scrollPos}, "slow");                                                                                                                                                                    
     });  
   });    
 })

Tested with Chrome and FF

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}