Programs & Examples On #Properties.settings

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

MVC: How to Return a String as JSON

The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object.

What you are passing to the controller's Json method, though, is a JSON-formatted string object, so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem).

I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available.

return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here, 
//  or if that is done automatically

Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas\EnterpriseLibrary.Configuration.xsd

CONTEXT

  • Visual Studio 2010
  • Enterprise Library 5

STEPS TO REMOVE THE WARNINGS

  1. open app.config in your Visual Studio project
  2. right click in the XML Document editor, select "Properties"
  3. add the fully qualified path to the "EnterpriseLibrary.Configuration.xsd"

ASIDE

It is worth repeating that these "Error List" "Messages" ("Could not find schema information for the element") are only visible when you open the app.config file. If you "Close All Documents" and compile... no messages will be reported.

reading from app.config file

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:

  • Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
  • OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]

Hope this helps

Where are the Properties.Settings.Default stored?

thanks for pointing me in the right direction. I found user.config located at this monstrosity: c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.

I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.

Change connection string & reload app.config at run time

You can also refresh the configuration in it's entirety:

ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName];

if (importToConnectionString == null)
{
    importToConnectionString = new ConnectionStringSettings();
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
    importToConnectionString.Name = newName;
    currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString);
}
else
{
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
}

Properties.Settings.Default.Reload();

How do I replace a character at a particular index in JavaScript?

this is easily achievable with RegExp!

const str = 'Hello RegEx!';
const index = 11;
const replaceWith = 'p';

//'Hello RegEx!'.replace(/^(.{11})(.)/, `$1p`);
str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ replaceWith }`);

//< "Hello RegExp"

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Good question.

  • @@IDENTITY: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT, and the trigger executes another INSERT statement).

  • SCOPE_IDENTITY(): returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).

  • IDENT_CURRENT(): returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).

  • IDENTITY(): used when declaring a column in a table as an identity column.

For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.

To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY().

This Activity already has an action bar supplied by the window decor

If you want to combine some activities with actionbar and others not, you should use the base theme have actionbar enabled and then create a sub theme that you gonna use it on activities that don't require actionbar

For example you can use a sub style like this

             <style name="AppTheme.NoActionBar">
               <item name="windowActionBar">false</item>
               <item name="windowNoTitle">true</item>
            </style>

While the base theme extends say

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

and then use the non actionbar theme in the AndroidManifest File within the activity tag say

   <activity
        android:name="com.example.NonActionBarActivity"
        android:theme="@style/AppTheme.NoActionBar"

you must apply this to each individual activity that don't need actionbar so if your project requires fewer action bar activities than non, then it's better to apply this on the base theme level

How to get the filename without the extension in Java?

Here is the consolidated list order by my preference.

Using apache commons

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
                          
                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

Using Google Guava (If u already using it)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

Files.getNameWithoutExtension

Or using Core Java

1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

Liferay API

import com.liferay.portal.kernel.util.FileUtil; 
String fileName = FileUtil.stripExtension(file.getName());

Sorting a vector of custom objects

typedef struct Freqamp{
    double freq;
    double amp;
}FREQAMP;

bool struct_cmp_by_freq(FREQAMP a, FREQAMP b)
{
    return a.freq < b.freq;
}

main()
{
    vector <FREQAMP> temp;
    FREQAMP freqAMP;

    freqAMP.freq = 330;
    freqAMP.amp = 117.56;
    temp.push_back(freqAMP);

    freqAMP.freq = 450;
    freqAMP.amp = 99.56;
    temp.push_back(freqAMP);

    freqAMP.freq = 110;
    freqAMP.amp = 106.56;
    temp.push_back(freqAMP);

    sort(temp.begin(),temp.end(), struct_cmp_by_freq);
}

if compare is false, it will do "swap".

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:

ng update @angular/core @angular/cli

That will update your local angular version to 9. Then, just to sync material, run: ng update @angular/material

Debug vs Release in CMake

With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt in the root of your project. Then from the root of your project:

mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make

And for Debug (again from the root of your project):

mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make

Release / Debug will add the appropriate flags for your compiler. There are also RelWithDebInfo and MinSizeRel build configurations.


You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT variables, e.g.:

set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")

See CMAKE_BUILD_TYPE for more details.


As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Your system can have many different tomcat versions. You can try to solve it.

Right Click on Project then Select Properties, Select Project Facets and on the right section, Select right Apache Tomcat versions as Runtimes and click ok

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

How does DISTINCT work when using JPA and Hibernate

I would use JPA's constructor expression feature. See also following answer:

JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped

Following the example in the question, it would be something like this.

SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:

>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])

Or, to sum over rows:

>>> a.sum(axis=1)
array([ 3, 12, 21, 30])

Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.

From the Tentative Numpy Tutorial:

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

How do I get current scope dom-element in AngularJS controller?

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

Android toolbar center title and custom font

Even though adding a text view to the toolbar can solve the problem of the restriction of title styling, there is an issue with it. Since we are not adding it to a layout, we do not have too much control over its width. We can either use wrap_content or match_parent.

Now consider a scenario where we have a searchView as a button on the right edge of the toolbar. If the title contents are more, it will go on top of the button obscuring it. There is no way of controlling this short of setting a width to the label and is something you don't want to do if you want to have a responsive design.

So, here is a solution that worked for me which is slightly different from adding a textview to the toolbar. Instead of that, add the toolbar and text view to a relative layout and ensure that the text view is on top of the toolbar. Then we can use appropriate margins and make sure the text view shows up where we want it to show up.

Make sure you set the toolbar to not show the title.

Here is the XML for this solution:

<RelativeLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="?attr/colorPrimary">

                    <android.support.v7.widget.Toolbar
                        android:theme="@style/ThemeOverlay.AppCompat.Dark"
                        android:id="@+id/activity_toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        android:background="?attr/colorPrimary"
                        android:titleTextAppearance="@style/AppTheme.TitleTextView"
                        android:layout_marginRight="40dp"
                        android:layoutMode="clipBounds">

                        <android.support.v7.widget.SearchView
                            android:id="@+id/search_view"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="right"
                            android:layout_centerVertical="true"
                            android:layout_alignParentRight="true"
                            android:foregroundTint="@color/white" />
                        </android.support.v7.widget.Toolbar>

                    <TextView
                        android:id="@+id/toolbar_title"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="90dp"
                        android:text="@string/app_name"
                        android:textSize="@dimen/title_text_size"
                        android:textColor="@color/white"
                        android:lines="1"
                        android:layout_marginLeft="72dp"
                        android:layout_centerVertical="true" />

                </RelativeLayout>

Solves the issue @ankur-chaudhary mentioned above.

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your Json CustomerJson:

public class CustomerJson
{
    [JsonProperty("customer")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [JsonProperty("first_name")]
    public string Firstname { get; set; }

    [JsonProperty("last_name")]
    public string Lastname { get; set; }

    ...
}

And you can deserialize your json easily :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Hope it helps !

Documentation: Serializing and Deserializing JSON

How to detect internet speed in JavaScript?

I needed a quick way to determine if the user connection speed was fast enough to enable/disable some features in a site I’m working on, I made this little script that averages the time it takes to download a single (small) image a number of times, it's working pretty accurately in my tests, being able to clearly distinguish between 3G or Wi-Fi for example, maybe someone can make a more elegant version or even a jQuery plugin.

_x000D_
_x000D_
var arrTimes = [];_x000D_
var i = 0; // start_x000D_
var timesToTest = 5;_x000D_
var tThreshold = 150; //ms_x000D_
var testImage = "http://www.google.com/images/phd/px.gif"; // small image in your server_x000D_
var dummyImage = new Image();_x000D_
var isConnectedFast = false;_x000D_
_x000D_
testLatency(function(avg){_x000D_
  isConnectedFast = (avg <= tThreshold);_x000D_
  /** output */_x000D_
  document.body.appendChild(_x000D_
    document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast)_x000D_
  );_x000D_
});_x000D_
_x000D_
/** test and average time took to download image from server, called recursively timesToTest times */_x000D_
function testLatency(cb) {_x000D_
  var tStart = new Date().getTime();_x000D_
  if (i<timesToTest-1) {_x000D_
    dummyImage.src = testImage + '?t=' + tStart;_x000D_
    dummyImage.onload = function() {_x000D_
      var tEnd = new Date().getTime();_x000D_
      var tTimeTook = tEnd-tStart;_x000D_
      arrTimes[i] = tTimeTook;_x000D_
      testLatency(cb);_x000D_
      i++;_x000D_
    };_x000D_
  } else {_x000D_
    /** calculate average of array items then callback */_x000D_
    var sum = arrTimes.reduce(function(a, b) { return a + b; });_x000D_
    var avg = sum / arrTimes.length;_x000D_
    cb(avg);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

How to repeat last command in python interpreter shell?

You don't need a custom script like pyfunc's answer for OSX (at least on mavericks). In Idle click on Idle -> Preferences -> Keys, locate "history-next" and "history-previous", and either leave them with their default keyboard shortcut or assign "up arrow" and "down arrow" per typical expected terminal behavior.

This is on Idle 2.7 on OSX Mavericks.

string decode utf-8

the core functions are getBytes(String charset) and new String(byte[] data). you can use these functions to do UTF-8 decoding.

UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String() is the byte array, which calling is equal to new String(bytes, "UTF-8")

Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.

The decoding sentence should be

String decoded = new String(encoded.getBytes("ISO-8859-1"));

Why does overflow:hidden not work in a <td>?

Here is the same problem.

You need to set table-layout:fixed and a suitable width on the table element, as well as overflow:hidden and white-space: nowrap on the table cells.


Examples

Fixed width columns

The width of the table has to be the same (or smaller) than the fixed width cell(s).

With one fixed width column:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 100px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

With multiple fixed width columns:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 200px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Fixed and fluid width columns

A width for the table must be set, but any extra width is simply taken by the fluid cell(s).

With multiple columns, fixed width and fluid width:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
}
td {
  background: #F00;
  padding: 20px;
  border: solid 1px #000;
}
tr td:first-child {
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

How can I get the URL of the current tab from a Google Chrome extension?

This Solution is already TESTED.

set permissions for API in manifest.json

"permissions": [ ...
   "tabs",
    "activeTab",
    "<all_urls>"
]

On first load call function. https://developer.chrome.com/extensions/tabs#event-onActivated

chrome.tabs.onActivated.addListener((activeInfo) => {  
  sendCurrentUrl()
})

On change call function. https://developer.chrome.com/extensions/tabs#event-onSelectionChanged

chrome.tabs.onSelectionChanged.addListener(() => {
  sendCurrentUrl()
})

the function to get the URL

function sendCurrentUrl() {
  chrome.tabs.getSelected(null, function(tab) {
    var tablink = tab.url
    console.log(tablink)
  })

REST URI convention - Singular or plural name of resource while creating it

I prefer using singular form for both simplicity and consistency.

For example, considering the following url:

/customer/1

I will treat customer as customer collection, but for simplicity, the collection part is removed.

Another example:

/equipment/1

In this case, equipments is not the correct plural form. So treating it as a equipment collection and removing collection for simplicity makes it consistent with the customer case.

Why number 9 in kill -9 command in unix?

There were 8 other signals they came up with first.

Returning pointer from a function

It is not allocating memory at assignment of value 12 to integer pointer. Therefore it crashes, because it's not finding any memory.

You can try this:

#include<stdio.h>
#include<stdlib.h>
int *fun();

int main()
{
    int *ptr;
    ptr=fun();
    printf("\n\t\t%d\n",*ptr);
}

int *fun()
{
    int ptr;
    ptr=12;
    return(&ptr);
}

Importing Excel into a DataTable Quickly

Caling .Value2 is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:

object[,] data = Range.Value2;

// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
    textBox3.Text = cCnt.ToString();

    var Column = new DataColumn();
    Column.DataType = System.Type.GetType("System.String");
    Column.ColumnName = cCnt.ToString();
    DT.Columns.Add(Column);

    // Create row for Data Table
    for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
    {
        textBox2.Text = rCnt.ToString();

        string CellVal = String.Empty;
        try
        {
            cellVal = (string)(data[rCnt, cCnt]);
        }
        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
        {
            ConvertVal = (double)(data[rCnt, cCnt]);
            cellVal = ConvertVal.ToString();
        }

        DataRow Row;

        // Add to the DataTable
        if (cCnt == 1)
        {

            Row = DT.NewRow();
            Row[cCnt.ToString()] = cellVal;
            DT.Rows.Add(Row);
        }
        else
        {

            Row = DT.Rows[rCnt + 1];
            Row[cCnt.ToString()] = cellVal;

        }
    }
} 

How to center content in a bootstrap column?

This is a simple way.

<div class="row">
  <div class="col-md-6 mx-auto">
    <p>My text</p>
  </div>
</div>

The number 6 controls the width of the column.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

How can I change the date format in Java?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());

This should do the trick

How can I edit a .jar file?

This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.

http://classeditor.sourceforge.net/

how to align text vertically center in android

The problem is the padding of the font on the textview. Just add to your textview:

android:includeFontPadding="false"

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

A non well formed numeric value encountered

if $_GET['start_date'] is a string then convert it in integer or double to deal numerically.

$int = (int) $_GET['start_date']; //Integer
$double = (double) $_GET['start_date']; //It takes in floating value with 2 digits

Name does not exist in the current context

I solved mine by using an Import directive under my Page directive. You may also want to add the namespace to your Inherits attribute of your Page directive.

Since it appears that your default namespace is "stman.Members", try: <%@ Page Title="" Language="C#" MasterPageFile="~/Members/Members.master" AutoEventWireup="true" CodeFile="Jobs.aspx.cs" Inherits="stman.Members.Members_Jobs" %> <%@ Import Namespace="stman.Members"%>

Additionally, data that I wanted to pass between aspx.cs and aspx, I put inside a static class inside the namespace. That static class was available to move data around in the name space and no longer has a "not in context" error.

Http 415 Unsupported Media type error with JSON

Add Content-Type: application/json and Accept: application/json

Get values from a listbox on a sheet

The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.

Here is what I suggest instead:

Private Sub CommandButton2_Click()
    Dim lItem As Long

    For lItem = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(lItem) = True Then
            MsgBox(ListBox1.List(lItem))
        End If
    Next
End Sub

Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm

Calculate time difference in minutes in SQL Server

Apart from the DATEDIFF you can also use the TIMEDIFF function or the TIMESTAMPDIFF.

EXAMPLE

SET @date1 = '2010-10-11 12:15:35', @date2 = '2010-10-10 00:00:00';

SELECT 
TIMEDIFF(@date1, @date2) AS 'TIMEDIFF',
TIMESTAMPDIFF(hour, @date1, @date2) AS 'Hours',
TIMESTAMPDIFF(minute, @date1, @date2) AS 'Minutes',
TIMESTAMPDIFF(second, @date1, @date2) AS 'Seconds';

RESULTS

TIMEDIFF : 36:15:35
Hours : -36
Minutes : -2175
Seconds : -130535

What is "406-Not Acceptable Response" in HTTP?

Your operation did not fail.

Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.

Ref: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

  1. Find out the response (content type) returned by Service.
  2. Provide this (content type) in your request Accept header.

http://en.wikipedia.org/wiki/HTTP_status_code -> 406

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Alternatively, you can switch to JRockit which handling permgen differently then sun's jvm. It generally has better performance as well.

http://www.oracle.com/technetwork/middleware/jrockit/overview/index.html

psql: FATAL: database "<user>" does not exist

I faced the same error when I trying to open postgresql on mac

psql: FATAL:  database "user" does not exist

I found this simple command to solve it:

method1

$ createdb --owner=postgres --encoding=utf8 user

and type

 psql

Method 2:

psql -d postgres

How to get the path of running java program

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use

System.getProperty("java.class.path")

Above mentioned System property provides

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

MySQL Workbench: How to keep the connection alive

OK - so this issue has been driving me crazy - v 6.3.6 on Ubuntu Linux. None of the above solutions worked for me. Connecting to localhost mysql server previously always worked fine. Connecting to remote server always timed out - after about 60 seconds, sometimes after less time, sometimes more.

What finally worked for me was upgrading Workbench to 6.3.9 - no more dropped connections.

How to change Visual Studio 2012,2013 or 2015 License Key?

See my UPDATE at the end, before reading the following answer.

I have windows 8 and another pc with windows 8.1

I had License error saying "Prerelease software. License expired".

The only solution that I found which is inspired by the above solutions (Thanks!) was to run process monitor and see the exact registry keys that are accessed when I start the VS2013 which were:

HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C

like what are mentioned in the previous posts. However the process monitor said that this registry is access denied.

So I opened regedit and found that registry key and I could not open it. It says I have no permission to see it.

SO I had to change its permission:

  1. Right click on the "HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C" key
  2. Permissions
  3. Add
  4. In "Enter object names to select" I have added my windows user name. Ok.
  5. check on Full control
  6. Advanced
  7. Owner click on "Change"
  8. In "Enter object names to select" I have added my windows user name. Ok.
  9. Ok. Ok. Ok.

I found that this registry key has several sub keys, however you have to restart regedit to see them.

By seeing which other registry keys are access denied in process monitor , I knew that VS2013 will specifically deal with these subkeys which are ACCESS DENIED also: 06181 0bcad

and these subkeys should be changed their permissions as well like above.

After making these permission changes everything worked well.

The same thing has been done to Microsoft visual studio 2010 because an error in the license as well and the solution worked well.

UPDATE : It turned out that starting visual studio as administrator solved this issue without this registry massage. Seems that this happened to my pc after changing the 'required password to login' removed in the user settings. (I wanted to let the pc start running without any password after restart from a crash or anything else). This made a lot of programs not able to write into some folders like temp folders unless I start the application as admin. Even printing from excel would not work, if excel is not started as admin.

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

Converting a String array into an int Array in java

To help debug, and make your code better, do this:

private void processLine(String[] strings) {
    Integer[] intarray=new Integer[strings.length];
    int i=0;
    for(String str:strings){
        try {
            intarray[i]=Integer.parseInt(str);
            i++;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
        }
    }
}

Also, from a code neatness point, you could reduce the lines by doing this:

for (String str : strings)
    intarray[i++] = Integer.parseInt(str);

How do I view / replay a chrome network debugger har file saved with content?

Edit: Harhar is now open source. I have updated the URL below.

If you use an Avalanche load generator, you can use Harhar to replay a HAR file at very high load: https://acastaner.github.io/harhar/

This tool handles the "content" you use when you "Save as HAR with content."

WebDriver - wait for element using Java

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));     

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  

Check this TUTORIAL for more details.

Importing files from different folder

Your problem is that Python is looking in the Python directory for this file and not finding it. You must specify that you are talking about the directory that you are in and not the Python one.

To do this you change this:

from application.app.folder.file import func_name

to this:

from .application.app.folder.file import func_name

By adding the dot you are saying look in this folder for the application folder instead of looking in the Python directory.

Jenkins Pipeline Wipe Out Workspace

Using the 'WipeWorkspace' extension seems to work as well. It requires the longer form:

checkout([
   $class: 'GitSCM',
   branches: scm.branches,
   extensions: scm.extensions + [[$class: 'WipeWorkspace']],
   userRemoteConfigs: scm.userRemoteConfigs
])

More details here: https://support.cloudbees.com/hc/en-us/articles/226122247-How-to-Customize-Checkout-for-Pipeline-Multibranch-

Available GitSCM extensions here: https://github.com/jenkinsci/git-plugin/tree/master/src/main/java/hudson/plugins/git/extensions/impl

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:

Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");

Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);

// This is not possible: It would throw an 
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");

// This is still possible:
realMap.put("E", "F");

// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F". 

In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.

Update:

As pointed out in a comment, an immutable map can also be created with the standard API using

Map<String, String> immutableMap = 
    Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap)); 

This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap without having to add the dependency to Guava.

How to create a jQuery function (a new jQuery method or plugin)?

You can always do this:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I have added for this:

Server compression

server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

taken from http://bisaga.com/blog/programming/web-compression-on-spring-boot-application/

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

This error in REACT. following steps

  1. Go to Project Root Directory Package.json file

  2. add "type":"module";

  3. Save it and Restart Server

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Change background color of R plot

One Google search later we've learned that you can set the entire plotting device background color as Owen indicates. If you just want the plotting region altered, you have to do something like what is outlined in that R-Help thread:

plot(df)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "gray")
points(df)

The barplot function has an add parameter that you'll likely need to use.

Getting only Month and Year from SQL DATE

convert(varchar(7), <date_field>, 120)
because 120 results in 'yyyy-MM-dd' which is varchar(10)
using varchar(7) will display only year and month

example:
select convert(varchar(7), <date_field>, 120), COUNT(*)
from <some_table>
group by convert(varchar(7), <date_field>, 120)
order by 1

PHP check if date between two dates

You can use the mktime(hour, minute, seconds, month, day, year) function

$paymentDate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$contractDateBegin = mktime(0, 0, 0, 1, 1, 2001); 
$contractDateEnd =  mktime(0, 0, 0, 1, 1, 2012);

if ($paymentDate >= $contractDateBegin && $paymentDate <= $contractDateEnd){
    echo "is between";
}else{
    echo "NO GO!";  
}

How can I bind to the change event of a textarea in jQuery?

This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):

// Storing this jQuery object outside of the event callback 
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")

// input           :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange  :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {

  // This is the correct way to enable/disabled a button in jQuery [4]
  $myButton.prop('disabled', this.value.length === 0)

}

1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function

BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange event. It was developed by the same person who implemented the equivalent onChange event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)

UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell's more recently updated fork of jquery-splendid-textchange.

How to check if a line is blank using regex

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

How can I remove an SSH key?

The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg which apparently contained the cached keys and profiles.

After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.

I didn't have success with the other approaches.

Recommended website resolution (width and height)?

I'd suggest you have a look at media-queries. This is a useful new addition to CSS that really makes so much sense, you'd wonder why this wasn't implemented waaay earlier. Basically it allows you to target browser attributes (such as max and min-widths) directly via CSS and branch your layout code from there. Similar to creating a print stylesheet, you can create your desktop and mobile layouts in parallel in the same file, which kicks ass for development.

How to add a custom right-click menu to a webpage?

Here is a very good tutorial on how to build a custom context menu with a full working code example (without JQuery and other libraries).

You can also find their demo code on GitHub.

They give a detailed step-by-step explanation that you can follow along to build your own right-click context menu (including html, css and javascript code) and summarize it at the end by giving the complete example code.

You can follow along easily and adapt it to your own needs. And there is no need for JQuery or other libraries.

This is how their example menu code looks like:

<nav id="context-menu" class="context-menu">
    <ul class="context-menu__items">
      <li class="context-menu__item">
        <a href="#" class="context-menu__link" data-action="View"><i class="fa fa-eye"></i> View Task</a>
      </li>
      <li class="context-menu__item">
        <a href="#" class="context-menu__link" data-action="Edit"><i class="fa fa-edit"></i> Edit Task</a>
      </li>
      <li class="context-menu__item">
        <a href="#" class="context-menu__link" data-action="Delete"><i class="fa fa-times"></i> Delete Task</a>
      </li>
    </ul>
  </nav>

A working example (task list) can be found on codepen.

How to allow only numbers in textbox in mvc4 razor

Maybe you can use the [Integer] data annotation (If you use the DataAnnotationsExtensions http://dataannotationsextensions.org/) . However, this wil only check if the value is an integer, nót if it is filled in (So you may also need the [Required] attribute).

If you enable Unobtrusive Validation it will validate it clientside, but you should also use Modelstate.Valid in your POST action to decline it in case people have Javascript disabled.

Select tableview row programmatically

From reference documentation:

Calling this method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor does it send UITableViewSelectionDidChangeNotification notifications to observers.

What I would do is:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self doSomethingWithRowAtIndexPath:indexPath];
}

And then, from where you wanted to call selectRowAtIndexPath, you instead call doSomethingWithRowAtIndexPath. On top of that, you can additionally also call selectRowAtIndexPath if you want the UI feedback to happen.

Where does the slf4j log file get saved?

slf4j is only an API. You should have a concrete implementation (for example log4j). This concrete implementation has a config file which tells you where to store the logs.

enter image description here

When slf4j catches a log messages with a logger, it is given to an appender which decides what to do with the message. By default, the ConsoleAppender displays the message in the console.

The default configuration file is :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

  <Appenders>
    <!-- By default => console -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
  </Appenders>

  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

If you put a configuration file available in the classpath, then your concrete implementation (in your case, log4j) will find and use it. See Log4J documentation.

Example of file appender :

<Appenders>
<File name="File" fileName="${filename}">
  <PatternLayout>
    <pattern>%d %p %C{1.} [%t] %m%n</pattern>
  </PatternLayout>
</File>

...
</Appenders>

Complete example with a file appender :

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

  <Appenders>
    <File name="File" fileName="${filename}">
      <PatternLayout>
        <pattern>%d %p %C{1.} [%t] %m%n</pattern>
      </PatternLayout>
    </File>
  </Appenders>

  <Loggers>
    <Root level="error">
      <AppenderRef ref="File"/>
    </Root>
  </Loggers>

</Configuration>

How to get JQuery.trigger('click'); to initiate a mouse click

See my demo: http://jsfiddle.net/8AVau/1/

jQuery(document).ready(function(){
    jQuery('#foo').on('click', function(){
         jQuery('#bar').simulateClick('click');
    });
});

jQuery.fn.simulateClick = function() {
    return this.each(function() {
        if('createEvent' in document) {
            var doc = this.ownerDocument,
                evt = doc.createEvent('MouseEvents');
            evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            this.dispatchEvent(evt);
        } else {
            this.click(); // IE Boss!
        }
    });
}

Curl not recognized as an internal or external command, operable program or batch file

Steps to install curl in windows

Install cURL on Windows

There are 4 steps to follow to get cURL installed on Windows.

Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate

Step One: Install Visual C++ 2008 Redistributables

From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)

Step Two: Install Win(32/64) OpenSSL v1.0.0k Light

From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light

Step Three: Install cURL

Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html

Copy curl.exe to C:\Windows\System32

Step Four: Install Recent Certificates

Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt

If you have already installed curl or after doing the above steps, add the directory where it's installed to the windows path:

1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt

How to change the Jupyter start-up folder

jupyter notebook --notebook-dir=%WORKING_DIR%,

where %WORKING_DIR% (H:\data\ML) - directory where you're going to work

It is the simplest one-line command way, IMHO

How to enable scrolling on website that disabled scrolling?

What worked for me was disabling the position: fixed; CSS.

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation

i.ToString("00")
01

i.ToString("000")
001

i.ToString("0000")
0001

$"Prefix_{i:00}"
Prefix_01

$"Prefix_{i:000}"
Prefix_001

$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix

How to remove old and unused Docker images

@VonC already gave a very nice answer, but for completeness here is a little script I have been using---and which also nukes any errand Docker processes should you have some:

#!/bin/bash

imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
   echo docker rmi ${imgs}
   docker rmi ${imgs}
else
   echo "No images to remove"
fi

procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
   echo docker rm ${procs}
   docker rm ${procs}
else
   echo "No processes to purge"
fi

How to set a header in an HTTP response?

In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:

httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

There are at least three ways to disable the use of unobtrusive JavaScript for client-side validation:

  1. Add the following to the web.config file:
    <configuration>
      <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
      </appSettings>
    </configuration>
  2. Set the value of the System.Web.UI.ValidationSettings.UnobtrusiveValidationMode static property to System.Web.UI.UnobtrusiveValidationMode.None
  3. Set the value of the System.Web.UI.Page.UnobtrusiveValidationMode instance property to System.Web.UI.UnobtrusiveValidationMode.None

To disable the functionality on a per page basis, I prefer to set the Page.UnobtrusiveValidationMode property using the page directive:

<%@ Page Language="C#" UnobtrusiveValidationMode="None" %>

This Handler class should be static or leaks might occur: IncomingHandler

I am not sure but you can try intialising handler to null in onDestroy()

Mixing C# & VB In The Same Project

You need one project per language. I'm quite confident I saw a tool that merged assemblies, if you find that tool you should be good to go. If you need to use both languages in the same class, you should be able to write half of it in say VB.net and then write the rest in C# by inheriting the VB.net class.

Switch role after connecting to database

If someone still needs it (like I do).

The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html

We need to make the current session user a member of the role:

create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;

produces:

Role ROLE created.


Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"

Grant succeeded.


Role SET succeeded.

How to force keyboard with numbers in mobile website in Android

<input type="number" />
<input type="tel" />

Both of these present the numeric keypad when the input gains focus.

<input type="search" /> shows a normal keyboard with an extra search button

Everything else seems to bring up the standard keyboard.

How can I debug a HTTP POST in Chrome?

You can use Canary version of Chrome to see request payload of POST requests.

Request payload

how to read a long multiline string line by line in python

by splitting with newlines.

for line in wallop_of_a_string_with_many_lines.split('\n'):
  #do_something..

if you iterate over a string, you are iterating char by char in that string, not by line.

>>>string = 'abc'
>>>for line in string:
    print line

a
b
c

Get Value From Select Option in Angular 4

    //in html file
    <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">Country</label>
                        <select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
                            <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
                            <div *ngIf="isEdit">
                                <option></option>
                            </div>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
                <div *ngIf="studentForm.get('country').errors.required">*country is required</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">State</label>
                        <select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select State -- </option>
                            <option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
                <div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">City</label>
                        <select class="form-control" formControlName="city">
                            <option disabled selected value [ngValue]="null"> -- Select City -- </option>
                            <option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
                <div *ngIf="studentForm.get('city').errors.required">*city is required</div>
            </div>
    //then in component
    onCountryChange(countryId:number){
   this.studentServive.getSelectedState(countryId).subscribe(resData=>{
    this.states = resData;
   });
  }
  onStateChange(stateId:number){
    this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
     this.cities = resData;
    });
   }`enter code here`

Regex to validate password strength

You should also consider changing some of your rules to:

  1. Add more special characters i.e. %, ^, (, ), -, _, +, and period. I'm adding all the special characters that you missed above the number signs in US keyboards. Escape the ones regex uses.
  2. Make the password 8 or more characters. Not just a static number 8.

With the above improvements, and for more flexibility and readability, I would modify the regex to.

^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-__+.]){1,}).{8,}$

Basic Explanation

(?=(.*RULE){MIN_OCCURANCES,})     

Each rule block is shown by (?=(){}). The rule and number of occurrences can then be easily specified and tested separately, before getting combined

Detailed Explanation

^                               start anchor
(?=(.*[a-z]){3,})               lowercase letters. {3,} indicates that you want 3 of this group
(?=(.*[A-Z]){2,})               uppercase letters. {2,} indicates that you want 2 of this group
(?=(.*[0-9]){2,})               numbers. {2,} indicates that you want 2 of this group
(?=(.*[!@#$%^&*()\-__+.]){1,})  all the special characters in the [] fields. The ones used by regex are escaped by using the \ or the character itself. {1,} is redundant, but good practice, in case you change that to more than 1 in the future. Also keeps all the groups consistent
{8,}                            indicates that you want 8 or more
$                               end anchor

And lastly, for testing purposes here is a robulink with the above regex

Calculate distance between two latitude-longitude points? (Haversine formula)

Dart lang:

import 'dart:math' show cos, sqrt, asin;

double calculateDistance(LatLng l1, LatLng l2) {
  const p = 0.017453292519943295;
  final a = 0.5 -
      cos((l2.latitude - l1.latitude) * p) / 2 +
      cos(l1.latitude * p) *
          cos(l2.latitude * p) *
          (1 - cos((l2.longitude - l1.longitude) * p)) /
          2;
  return 12742 * asin(sqrt(a));
}

How to make a smooth image rotation in Android?

As hanry has mentioned above putting liner iterpolator is fine. But if rotation is inside a set you must put android:shareInterpolator="false" to make it smooth.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
**android:shareInterpolator="false"**
>
<rotate
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="300"
    android:fillAfter="true"
    android:repeatCount="10"
    android:repeatMode="restart"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%" />
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="3000"
    android:fillAfter="true"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:toXScale="0"
    android:toYScale="0" />
</set>

If Sharedinterpolator being not false, the above code gives glitches.

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

What is the difference between Cygwin and MinGW?

From the point of view of porting a C program, a good way to understand this is to take an example:

#include <sys/stat.h>
#include <stdlib.h>

int main(void)
{
   struct stat stbuf;
   stat("c:foo.txt", &stbuf);
   system("command");
   printf("Hello, World\n");
   return 0;
}

If we change stat to _stat, we can compile this program with Microsoft Visual C. We can also compile this program with MinGW, and with Cygwin.

Under Microsoft Visual C, the program will be linked to a MSVC redistributable run-time library: mxvcrtnn.dll, where nn is some version suffix. To ship this program we will have to include that DLL. That DLL provides _stat, system and printf. (We also have the option of statically linking the run-time.)

Under MinGW, the program will be linked to msvcrt.dll, which is an internal, undocumented, unversioned library that is part of Windows, and off-limits to application use. That library is essentially a fork of the redistributable run-time library from MS Visual C for use by Windows itself.

Under both of these, the program will have similar behaviors:

  • the stat function will return very limited information—no useful permissions or inode number, for instance.
  • the path c:file.txt is resolved according to the current working directory associated with drive c:.
  • system uses cmd.exe /c for running the external command.

We can also compile the program under Cygwin. Similarly to the redistributable run-time used by MS Visual C, the Cygwin program will be linked to Cygwin's run-time libraries: cygwin1.dll (Cygwin proper) and cyggcc_s-1.dll (GCC run-time support). Since Cygwin is now under the LGPL, we can package with our program, even if it isn't GPL-compatible free software, and ship the program.

Under Cygwin, the library functions will behave differently:

  • the stat function has rich functionality, returning meaningful values in most of the fields.
  • the path c:file.txt is not understood at all as containing a drive letter reference, since c: isn't followed by a slash. The colon is considered part of the name and somehow mangled into it. There is no concept of a relative path against a volume or drive in Cygwin, no "currently logged drive" concept, and no per-drive current working directory.
  • the system function tries to use the /bin/sh -c interpreter. Cygwin will resolve the / path according to the location of your executable, and expect a sh.exe program to be co-located with your executable.

Both Cygwin and MinGW allow you to use Win32 functions. If you want to call MessageBox or CreateProcess, you can do that. You can also easily build a program which doesn't require a console window, using gcc -mwindows, under MinGW and Cygwin.

Cygwin is not strictly POSIX. In addition to providing access to the Windows API, it also provides its own implementations of some Microsoft C functions (stuff found in msvcrt.dll or the re-distributable msvcrtnn.dll run-times). An example of this are the spawn* family of functions like spawnvp. These are a good idea to use instead of fork and exec on Cygwin since they map better to the Windows process creation model which has no concept of fork.

Thus:

  • Cygwin programs are no less "native" than MS Visual C programs on grounds of requiring the accompaniment of libraries. Programming language implementations on Windows are expected to provide their own run-time, even C language implementations. There is no "libc" on Windows for public use.

  • The fact that MinGW requires no third-party DLL is actually a disadvantage; it is depending on an undocumented, Windows-internal fork of the Visual C run-time. MinGW does this because the GPL system library exception applies to msvcrt.dll, which means that GPL-ed programs can be compiled and redistributed with MinGW.

  • Due to its much broader and deeper support for POSIX compared to msvcrt.dll, Cygwin is by far the superior environment for porting POSIX programs. Since it is now under the LGPL, it allows applications with all sorts of licenses, open or closed source, to be redistributed. Cygwin even contains VT100 emulation and termios, which work with the Microsoft console! A POSIX application that sets up raw mode with tcsetattr and uses VT100 codes to control the cursor will work right in the cmd.exe window. As far as the end-user is concerned, it's a native console app making Win32 calls to control the console.

However:

  • As a native Windows development tool, Cygwin has some quirks, like path handling that is foreign to Windows, dependence on some hard-coded paths like /bin/sh and other issues. These differences are what render Cygwin programs "non-native". If a program takes a path as an argument, or input from a dialog box, Windows users expect that path to work the same way as it does in other Windows programs. If it doesn't work that way, that's a problem.

Plug: Shortly after the LGPL announcement, I started the Cygnal (Cygwin Native Application Library) project to provide a fork of the Cygwin DLL which aims to fix these issues. Programs can be developed under Cygwin, and then deployed with the Cygnal version of cygwin1.dll without recompiling. As this library improves, it will gradually eliminate the need for MinGW.

When Cygnal solves the path handling problem, it will be possible to develop a single executable which works with Windows paths when shipped as a Windows application with Cygnal, and seamlessly works with Cygwin paths when installed in your /usr/bin under Cygwin. Under Cygwin, the executable will transparently work with a path like /cygdrive/c/Users/bob. In the native deployment where it is linking against the Cygnal version of cygwin1.dll, that path will make no sense, whereas it will understand c:foo.txt.

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

Android Button Onclick

Here is some sample code of how to add a button named Add. You should declare the variable as a member variable, and the naming convention for member variables is to start with the letter "m".

Hit Alt+Enter on the classes to add the missing references.

Add this to your activity_main.xml:

 <Button
        android:id="@+id/buttonAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD"
     />

Add this to your MainActivity.java:

public class MainActivity extends AppCompatActivity {

    Button mButtonAdd; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonAdd = findViewById(R.id.buttonAdd);

        mButtonAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // do something here
            }
        });
    }
}

How can I view live MySQL queries?

Gibbs MySQL Spyglass

AgilData launched recently the Gibbs MySQL Scalability Advisor (a free self-service tool) which allows users to capture a live stream of queries to be uploaded to Gibbs. Spyglass (which is Open Source) will watch interactions between your MySQL Servers and client applications. No reconfiguration or restart of the MySQL database server is needed (either client or app).

GitHub: AgilData/gibbs-mysql-spyglass

Learn more: Packet Capturing MySQL with Rust

Install command:

curl -s https://raw.githubusercontent.com/AgilData/gibbs-mysql-spyglass/master/install.sh | bash

Simplest code for array intersection in javascript

I extended tarulen's answer to work with any number of arrays. It also should work with non-integer values.

function intersect() { 
    const last = arguments.length - 1;
    var seen={};
    var result=[];
    for (var i = 0; i < last; i++)   {
        for (var j = 0; j < arguments[i].length; j++)  {
            if (seen[arguments[i][j]])  {
                seen[arguments[i][j]] += 1;
            }
            else if (!i)    {
                seen[arguments[i][j]] = 1;
            }
        }
    }
    for (var i = 0; i < arguments[last].length; i++) {
        if ( seen[arguments[last][i]] === last)
            result.push(arguments[last][i]);
        }
    return result;
}

How to properly overload the << operator for an ostream?

Assuming that we're talking about overloading operator << for all classes derived from std::ostream to handle the Matrix class (and not overloading << for Matrix class), it makes more sense to declare the overload function outside the Math namespace in the header.

Use a friend function only if the functionality cannot be achieved via the public interfaces.

Matrix.h

namespace Math { 
    class Matrix { 
        //...
    };  
}
std::ostream& operator<<(std::ostream&, const Math::Matrix&);

Note that the operator overload is declared outside the namespace.

Matrix.cpp

using namespace Math;
using namespace std;

ostream& operator<< (ostream& os, const Matrix& obj) {
    os << obj.getXYZ() << obj.getABC() << '\n';
    return os;
}

On the other hand, if your overload function does need to be made a friend i.e. needs access to private and protected members.

Math.h

namespace Math {
    class Matrix {
        public:
            friend std::ostream& operator<<(std::ostream&, const Matrix&);
    };
}

You need to enclose the function definition with a namespace block instead of just using namespace Math;.

Matrix.cpp

using namespace Math;
using namespace std;

namespace Math {
    ostream& operator<<(ostream& os, const Matrix& obj) {
        os << obj.XYZ << obj.ABC << '\n';
        return os;
    }                 
}

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Here is another image map plugin I wrote to enhance image maps: https://github.com/gestixi/pictarea

It makes it easy to highlight all the area and let you specify different styles depending on the state of the zone: normal, hover, active, disable.

You can also specify how many zones can be selected at the same time.

Display exact matches only with grep

This may work for you

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

Where does Java's String constant pool live, the heap or the stack?

To the great answers that already included here I want to add something that missing in my perspective - an illustration.

As you already JVM divides the allocated memory to a Java program into two parts. one is stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.

So for example, if you init the following objects:

String s1 = "abc"; 
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);

String literals s1 and s2 will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.

Also, please note that "abc" will appear in heap and in string constant pool. Why is String s1 = "abc" and String obj1 = new String("abc") will be created this way? It's because String obj1 = new String("abc") explicitly creates a new and referentially distinct instance of a String object and String s1 = "abc" may reuse an instance from the string constant pool if one is available. For a more elaborate explanation: https://stackoverflow.com/a/3298542/2811258

enter image description here

Change color of bootstrap navbar on hover link?

If you Navbar code as like as follow:

<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Project name</a>
    </div>
    <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                    <li class="divider"></li>
                    <li class="dropdown-header">Nav header</li>
                    <li><a href="#">Separated link</a></li>
                    <li><a href="#">One more separated link</a></li>
                </ul>
            </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <li><a href="../navbar/">Default</a></li>
            <li><a href="../navbar-static-top/">Static top</a></li>
            <li class="active"><a href="./">Fixed top</a></li>
        </ul>
    </div><!--/.nav-collapse -->
</div>

Then just use the following CSS style to change hover color of your navbar-brand

.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
     color: white;
}

So your navbad-brand hover color will be changed to white. I just tested it and it's working for me correctly.

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

Android Studio: Add jar as library?

Download & Copy Your .jar file in libs folder then adding these line to build.gradle:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.3.1'
}

Do not forget to click "Sync now"

Specifying a custom DateTime format when serializing with Json.Net

public static JsonSerializerSettings JsonSerializer { get; set; } = new JsonSerializerSettings()
        {
            DateFormatString= "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new LowercaseContractResolver()
        };

Hello,

I'm using this property when I need set JsonSerializerSettings

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

basic authorization command for curl

One way, provide --user flag as part of curl, as follows:

curl --user username:password http://example.com

Another way is to get Base64 encoded token of "username:password" from any online website like - https://www.base64encode.org/ and pass it as Authorization header of curl as follows:

curl -i -H 'Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=' http://localhost:8080/

Here, dXNlcm5hbWU6cGFzc3dvcmQ= is Base64 encoded token of username:password.

How can I replace text with CSS?

This implements a checkbox as a button which shows either Yes or No depending on its 'checked' state. So it demonstrates one way of replacing text using CSS without having to write any code.

It will still behave like a checkbox as far as returning (or not returning) a POST value, but from a display point of view it looks like a toggle button.

The colours may not be to your liking, they're only there to illustrate a point.

The HTML is:

<input type="checkbox" class="yesno" id="testcb" /><label for="testcb"><span></span></label>

...and the CSS is:

/* --------------------------------- */
/* Make the checkbox non-displayable */
/* --------------------------------- */
input[type="checkbox"].yesno {
    display:none;
}
/* --------------------------------- */
/* Set the associated label <span>   */
/* the way you want it to look.      */
/* --------------------------------- */
input[type="checkbox"].yesno+label span {
    display:inline-block;
    width:80px;
    height:30px;
    text-align:center;
    vertical-align:middle;
    color:#800000;
    background-color:white;
    border-style:solid;
    border-width:1px;
    border-color:black;
    cursor:pointer;
}
/* --------------------------------- */
/* By default the content after the  */
/* the label <span> is "No"          */
/* --------------------------------- */
input[type="checkbox"].yesno+label span:after {
    content:"No";
}
/* --------------------------------- */
/* When the box is checked the       */
/* content after the label <span>    */
/* is "Yes" (which replaces any      */
/* existing content).                */
/* When the box becomes unchecked the*/
/* content reverts to the way it was.*/
/* --------------------------------- */
input[type="checkbox"].yesno:checked+label span:after {
    content:"Yes";
}
/* --------------------------------- */
/* When the box is checked the       */
/* label <span> looks like this      */
/* (which replaces any existing)     */
/* When the box becomes unchecked the*/
/* layout reverts to the way it was. */
/* --------------------------------- */
input[type="checkbox"].yesno:checked+label span {
    color:green;
    background-color:#C8C8C8;
}

I've only tried it on Firefox, but it's standard CSS so it ought to work elsewhere.

How to pass objects to functions in C++?

There are three methods of passing an object to a function as a parameter:

  1. Pass by reference
  2. pass by value
  3. adding constant in parameter

Go through the following example:

class Sample
{
public:
    int *ptr;
    int mVar;

    Sample(int i)
    {
        mVar = 4;
        ptr = new int(i);
    }

    ~Sample()
    {
        delete ptr;
    }

    void PrintVal()
    {
        cout << "The value of the pointer is " << *ptr << endl
             << "The value of the variable is " << mVar;
   }
};

void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}


int main()
{

  Sample s1= 10;
  SomeFunc(s1);
  s1.PrintVal();
  char ch;
  cin >> ch;
}

Output:

Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4

How to enable curl in xampp?

For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after extension=curl.so

What does '<?=' mean in PHP?

An array in PHP is a map of keys to values:

$array = array();
$array["yellow"] = 3;
$array["green"] = 4;

If you want to do something with each key-value-pair in your array, you can use the foreach control structure:

foreach ($array as $key => $value)

The $array variable is the array you will be using. The $key and $value variables will contain a key-value-pair in every iteration of the foreach loop. In this example, they will first contain "yellow" and 3, then "green" and 4.

You can use an alternative notation if you don't care about the keys:

foreach ($array as $value)

Get the decimal part from a double

Better Way -

        double value = 10.567;
        int result = (int)((value - (int)value) * 100);
        Console.WriteLine(result);

Output -

56

remove attribute display:none; so the item will be visible

For this particular purpose, $("span").show() should be good enough.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

This is fixed by:

a) adding schemas: [ CUSTOM_ELEMENTS_SCHEMA ] to every component or

b) adding

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

and

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

to your module.

How do I format a date with Dart?

There is a package date_format

dependencies:
    date_format:

code

import 'package:date_format/date_format.dart';

final formattedStr = formatDate(
    yourDateTime, [dd, '.', mm, '.', yy, ' ', HH, ':', nn]);

// output example "29.03.19 07:00"

Pay attention: minutes are nn

link to the package

Run a Docker image as a container

You can see your available images using:

docker images

Then you can run in detached mode so your terminal is still usable. You have several options to run it using a repository name (with or without a tag) or image ID:

docker run -d repository
docker run -d repository:tag
docker run -d image_id

Then you can check your container is running using

docker ps

docker ps gives you a container ID. You can use it or just the 2/3 first characters to go into your container using:

docker exec -it container_id /bin/bash

And you can stop it using docker stop container_id and docker rm container_id.

You can also run your container with -rm arguments so if you stop your container it will automatically be removed.

Differences between fork and exec

The main difference between fork() and exec() is that,

The fork() system call creates a clone of the currently running program. The original program continues execution with the next line of code after the fork() function call. The clone also starts execution at the next line of code. Look at the following code that i got from http://timmurphy.org/2014/04/26/using-fork-in-cc-a-minimum-working-example/

#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    printf("--beginning of program\n");
    int counter = 0;
    pid_t pid = fork();
    if (pid == 0)
    {
        // child process
        int i = 0;
        for (; i < 5; ++i)
        {
            printf("child process: counter=%d\n", ++counter);
        }
    }
    else if (pid > 0)
    {
        // parent process
        int j = 0;
        for (; j < 5; ++j)
        {
            printf("parent process: counter=%d\n", ++counter);
        }
    }
    else
    {
        // fork failed
        printf("fork() failed!\n");
        return 1;
    }
    printf("--end of program--\n");
    return 0;
}

This program declares a counter variable, set to zero, before fork()ing. After the fork call, we have two processes running in parallel, both incrementing their own version of counter. Each process will run to completion and exit. Because the processes run in parallel, we have no way of knowing which will finish first. Running this program will print something similar to what is shown below, though results may vary from one run to the next.

--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
--end of program--
child process: counter=4
child process: counter=5
--end of program--

The exec() family of system calls replaces the currently executing code of a process with another piece of code. The process retains its PID but it becomes a new program. For example, consider the following code:

#include <stdio.h> 
#include <unistd.h> 
main() {
 char program[80],*args[3];
 int i; 
printf("Ready to exec()...\n"); 
strcpy(program,"date"); 
args[0]="date"; 
args[1]="-u"; 
args[2]=NULL; 
i=execvp(program,args); 
printf("i=%d ... did it work?\n",i); 
} 

This program calls the execvp() function to replace its code with the date program. If the code is stored in a file named exec1.c, then executing it produces the following output:

Ready to exec()... 
Tue Jul 15 20:17:53 UTC 2008 

The program outputs the line -Ready to exec() . . . ? and after calling the execvp() function, replaces its code with the date program. Note that the line - . . . did it work? is not displayed, because at that point the code has been replaced. Instead, we see the output of executing -date -u.?

Build error: "The process cannot access the file because it is being used by another process"

VS2017 - Solved by closing all instances of MSBuild.exe in the windows task manager

Angularjs: input[text] ngChange fires while the value is changing

For anyone struggling with IE8 (it doesn't like the unbind('input'), I found a way around it.

Inject $sniffer into your directive and use:

if($sniffer.hasEvent('input')){
    elm.unbind('input');
}

IE8 calms down if you do this :)

How to send push notification to web browser?

this is simple way to do push notification for all browser https://pushjs.org

Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
    window.focus();
    this.close();
 }
});

How to suppress warnings globally in an R Script

I have replaced the printf calls with calls to warning in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings() or any of the other above mentioned methods.

suppressWarnings({ your code })

View markdown files offline

There are a few Chrome plug-ins that work well. I've been using Markdown Preview Plus.

After install, enable "Allow access to file URLs" in Extensions (menu > More tools > Extensions or enter URL chrome://extensions/ instead).

enter image description here

Then drag-n-drop a Markdown file onto Chrome and use your favorite editor to edit.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

How can I make SMTP authenticated in C#

Set the Credentials property before sending the message.

Git Bash doesn't see my PATH

I meet this problem when I try to use mingw to compile the xgboost lib in Win10. Finally I found the solution.

Create a file named as .bashrc in your home directory (usually the C:\Users\username). Then add the path to it. Remember to use quotes if your path contains blank, and remember to use /c/ instead of C:/

For example:

PATH=$PATH:"/c/Program Files/mingw-w64/x86_64-7.2.0-posix-seh-rt_v5-rev1/mingw64/bin"

NuGet Packages are missing

I had this exact frustrating message. What finally worked for me was deleting all files and folders inside /packages and letting VS re-fetch everything the next build.

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

Removing an activity from the history stack

You can achieve this by setting the android:noHistory attribute to "true" in the relevant <activity> entries in your AndroidManifest.xml file. For example:

<activity
    android:name=".AnyActivity"
    android:noHistory="true" />

Extract part of a regex match

The provided pieces of code do not cope with Exceptions May I suggest

getattr(re.search(r"<title>(.*)</title>", s, re.IGNORECASE), 'groups', lambda:[u""])()[0]

This returns an empty string by default if the pattern has not been found, or the first match.

Javascript: Extend a Function

Another option could be:

var initial = function() {
    console.log( 'initial function!' );
}

var iWantToExecuteThisOneToo = function () {
    console.log( 'the other function that i wanted to execute!' );
}

function extendFunction( oldOne, newOne ) {
    return (function() {
        oldOne();
        newOne();
    })();
}

var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );

How do I install Maven with Yum?

Not just mvn, for any util, you can find out yourself by giving yum whatprovides {command_name}

Convert Set to List without creating new List

Since it hasn't been mentioned so far, as of Java 10 you can use the new copyOf factory method:

List.copyOf(set);

From the Javadoc:

Returns an unmodifiable List containing the elements of the given Collection, in its iteration order.

Note that this creates a new list (ImmutableCollections$ListN to be precise) under the hood by

  1. calling Collection#toArray() on the given set and then
  2. putting these objects into a new array.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

i donot think onSaveInstanceState is a good solution. it just use for activity which had been destoryed.

From android 3.0 the Fragmen has been manager by FragmentManager, the condition is: one activity mapping manny fragments, when the fragment is added(not replace: it will recreated) in backStack, the view will be destored. when back to the last one, it will display as before.

So i think the fragmentManger and transaction is good enough to handle it.

What to do with "Unexpected indent" in python?

Indentation in Python is important and this is just not for code readability, unlike many other programming languages. If there is any white space or tab in your code between consecutive commands, python will give this error as Python is sensitive to this. We are likely to get this error when we do copy and paste of code to any Python. Make sure to identify and remove these spaces using a text editor like Notepad++ or manually remove the whitespace from the line of code where you are getting an error.

Step1 :Gives error 
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])

Step2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])

Step3: No error after space was removed
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
OUTPUT: [[7, 8, 9, 10]]

Thanks!

Jenkins: Failed to connect to repository

In our case git had to be installed on the Jenkins server.

WCF Service, the type provided as the service attribute values…could not be found

Change the following line in your Eval.svc file from:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.Eval" %> 

to:

<%@ ServiceHost Language="C#" Debug="true" Service="EvalServiceLibary.EvalService" %>

How to get substring in C

If you just want to print the substrings ...

char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);
}

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

How to restart a rails server on Heroku?

Go into your application directory on terminal and run following command:

heroku restart

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How do I reload a page without a POSTDATA warning in Javascript?

using meta refresh in html

<meta http-equiv='refresh' content='1'>

using meta refresh in php

echo "<meta http-equiv='refresh' content='1'>"

What is the difference between String.slice and String.substring?

The one answer is fine but requires a little reading into. Especially with the new terminology "stop".

My Go -- organized by differences to make it useful in addition to the first answer by Daniel above:

1) negative indexes. Substring requires positive indexes and will set a negative index to 0. Slice's negative index means the position from the end of the string.

"1234".substring(-2, -1) == "1234".substring(0,0) == ""
"1234".slice(-2, -1) == "1234".slice(2, 3) == "3"

2) Swapping of indexes. Substring will reorder the indexes to make the first index less than or equal to the second index.

"1234".substring(3,2) == "1234".substring(2,3) == "3"
"1234".slice(3,2) == ""

--------------------------

General comment -- I find it weird that the second index is the position after the last character of the slice or substring. I would expect "1234".slice(2,2) to return "3". This makes Andy's confusion above justified -- I would expect "1234".slice(2, -1) to return "34". Yes, this means I'm new to Javascript. This means also this behavior:

"1234".slice(-2, -2) == "", "1234".slice(-2, -1) == "3", "1234".slice(-2, -0) == "" <-- you have to use length or omit the argument to get the 4.
"1234".slice(3, -2) == "", "1234".slice(3, -1) == "", "1234".slice(3, -0) == "" <-- same issue, but seems weirder.

My 2c.

Call and receive output from Python script in Java?

I met the same problem before, also read the answers here, but doesn't found any satisfy solution can balance the compatibility, performance and well format output, the Jython can't work with extend C packages and slower than CPython. So finally I decided to invent the wheel myself, it took my 5 nights, I hope it can help you too: jpserve(https://github.com/johnhuang-cn/jpserve).

JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss. The following is the sample code.

At first, start jpserve on Python side

>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888

Then call Python from JAVA side:

PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
    + "b = 3\n"
    + "_result_ = a * b";

PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());

---
Result: 6

Passing parameters to a Bash function

A simple example that will clear both during executing script or inside script while calling a function.

#!/bin/bash
echo "parameterized function example"
function print_param_value(){
    value1="${1}" # $1 represent first argument
    value2="${2}" # $2 represent second argument
    echo "param 1 is  ${value1}" # As string
    echo "param 2 is ${value2}"
    sum=$(($value1+$value2)) # Process them as number
    echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" # Space-separated value
# You can also pass parameters during executing the script
print_param_value "$1" "$2" # Parameter $1 and $2 during execution

# Suppose our script name is "param_example".
# Call it like this:
#
# ./param_example 5 5
#
# Now the parameters will be $1=5 and $2=5

Adding Python Path on Windows 7

For people getting the windows store window when writing python in the console, all you have to do is go to configuration -> Manage app execution aliases and disable the toggles that say python.

then, add the following folders to the PATH.

C:\Users\alber\AppData\Local\Programs\Python\Python39\
C:\Users\alber\AppData\Local\Programs\Python\Python39\Scripts\

SQL Server: how to create a stored procedure

Create this way.

Create procedure dept_count(dept_name varchar(20),d_count integer)
   begin
     select count(*) into d_count
     from instructor
     where instructor.dept_name=dept_count.dept_name
   end

Finding the path of the program that will execute from the command line in Windows

Here's a little cmd script you can copy-n-paste into a file named something like where.cmd:

@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem    The main ideas for this script were taken from Raymond Chen's blog:
rem
rem         http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem     help diagnose situations with a conflict of some sort.
rem

setlocal

rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%

if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok

rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

Download Excel file via AJAX MVC

CSL's answer was implemented in a project I'm working on but the problem I incurred was scaling out on Azure broke our file downloads. Instead, I was able to do this with one AJAX call:

SERVER

[HttpPost]
public FileResult DownloadInvoice(int id1, int id2)
{
    //necessary to get the filename in the success of the ajax callback
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    byte[] fileBytes = _service.GetInvoice(id1, id2);
    string fileName = "Invoice.xlsx";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

CLIENT (modified version of Handle file download from ajax post)

$("#downloadInvoice").on("click", function() {
    $("#loaderInvoice").removeClass("d-none");

    var xhr = new XMLHttpRequest();
    var params = [];
    xhr.open('POST', "@Html.Raw(Url.Action("DownloadInvoice", "Controller", new { id1 = Model.Id1, id2 = Model.Id2 }))", true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            var type = xhr.getResponseHeader('Content-Type');

            var blob = typeof File === 'function'
                ? new File([this.response], filename, { type: type })
                : new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location = downloadUrl;

                }

                setTimeout(function() {
                        URL.revokeObjectURL(downloadUrl);
                    $("#loaderInvoice").addClass("d-none");
                }, 100); // cleanup
            }
        }
    };
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send($.param(params));
});

What is "Advanced" SQL?

Check out SQL For Smarties. I thought I was pretty good with SQL too, until I read that book... Goes into tons of depth, talks about things I've not seen elsewhere (I.E. difference between 3'rd and 4'th normal form, Boyce Codd Normal Form, etc)...

WCF error - There was no endpoint listening at

I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.

Right way to split an std::string into a vector<string>

A convenient way would be boost's string algorithms library.

#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
// ...

std::vector<std::string> words;
std::string s;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);

Android Studio cannot resolve R in imported project?

I solve that problem setting JAVA_HOME, CLASSPATH.

People sometimes skip JAVA_HOME and CLASSPATH when setting Java_path.

So try to check Environment Variable.

CLASSPATH -> .;

JAVA_HOME -> C:\Program Files\Java\jdk(version) or where Java installed

and then check the xml file which can have error(Do not naming well-known things such as button,text etc)

sorting a List of Map<String, String>

There are many ways to solve the same. One of the easiest ways to solve using Java 8 is given below :

As per your requirement, To sort in alphabetical order based on the map's key name

1st way :

list = list.stream()
           .sorted((a,b)-> (a.get("name")).compareTo(b.get("name")))
           .collect(Collectors.toList());

Or,

list = list.stream()
           .sorted(Comparator.comparing(map->map.get("name")))
           .collect(Collectors.toList());

2nd way :

Collections.sort(list, Comparator.comparing(map -> map.get("name")));

3rd way :

list.sort(Comparator.comparing(map-> map.get("name")));

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Try this:

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

And your activity namesmust be like this with capital letters:

<activity android:name=".Addfriend"/>
    <activity android:name=".UpdateDetails"/>
    <activity android:name=".Details"/>
    <activity android:name=".Updateimage"/>

How to iterate (keys, values) in JavaScript?

tl;dr

  1. In ECMAScript 5, it is not possible.
  2. In ECMAScript 2015, it is possible with Maps.
  3. In ECMAScript 2017, it would be readily available.

ECMAScript 5:

No, its not possible with objects.

You should either iterate with for..in, or Object.keys, like this

for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {           
        console.log(key, dictionary[key]);
    }
}

Note: The if condition above is necessary, only if you want to iterate the properties which are dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

Or

Object.keys(dictionary).forEach(function(key) {
    console.log(key, dictionary[key]);
});

ECMAScript 2015

In ECMAScript 2015, you can use Map objects and iterate them with Map.prototype.entries. Quoting example from that page,

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

var mapIter = myMap.entries();

console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]

Or iterate with for..of, like this

'use strict';

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const entry of myMap.entries()) {
  console.log(entry);
}

Output

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]

Or

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

Output

0 foo
1 bar
{} baz

ECMAScript 2017

ECMAScript 2017 would introduce a new function Object.entries. You can use this to iterate the object as you wanted.

'use strict';

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

Output

a 1
b 2
c 3

How to find rows in one table that have no corresponding row in another table

You have to check every ID in tableA against every ID in tableB. A fully featured RDBMS (such as Oracle) would be able to optimize that into an INDEX FULL FAST SCAN and not touch the table at all. I don't know whether H2's optimizer is as smart as that.

H2 does support the MINUS syntax so you should try this

select id from tableA
minus
select id from tableB
order by id desc

That may perform faster; it is certainly worth benchmarking.

How to use Tomcat 8 in Eclipse?

The only thing the eclipse plugin is checking is the tomcat version inside:

catalina.jar!/org/apache/catalina/util/ServerInfo.properties

I replaced the properties file with the one in tomcat7 and that fixed the issue for eclipse

In order to be able to deploy the spring-websockets sample app you need to edit the following file in eclipse:

.settings/org.eclipse.wst.common.project.facet.core.xml

And change the web version to 2.5

<installed facet="jst.web" version="2.5"/>

Java 8 - Best way to transform a list: map or foreach?

One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.

Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach method is classed as being terminal (meaning that it can produce side-effects).

The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be

  1. Non-interfering, meaning that the function should not alter the source of the stream if it is non-concurrent (e.g. ArrayList).
  2. Stateless to avoid unexpected results when doing parallel processing (caused by thread scheduling differences).

Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.

Intercept page exit event

I have users who have not been completing all required data.

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
    <cfset unloadCheck=1>
    $("#myInput").change(function(){
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
    });
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    verify();
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>

fatal error: mpi.h: No such file or directory #include <mpi.h>

You can execute:

$ mpicc -showme 

result :

gcc -I/Users/<USER_NAME>/openmpi-2.0.1/include -L/Users/<USER_NAME>/openmpi-2.0.1/lib -lmp

This command shows you the necessary libraries to compile mpicc

Example:

$ mpicc -g  -I/Users/<USER_NAME>/openmpi-2.0.1/include -o [nameExec] [objetcs.o...] [program.c] -lm


$ mpicc -g  -I/Users/<USER_NAME>/openmpi-2.0.1/include -o example file_object.o my_program.c otherlib.o -lm

this command generates executable with your program in example, you can execute :

$ ./example

How do I execute external program within C code in linux with arguments?

How about like this:

char* cmd = "./foo 1 2 3";
system(cmd);

Force "portrait" orientation mode

Don't apply the orientation to the application element, instead you should apply the attribute to the activity element, and you must also set configChanges as noted below.

Example:

<activity
   android:screenOrientation="portrait"
   android:configChanges="orientation|keyboardHidden">
</activity>

This is applied in the manifest file AndroidManifest.xml.

ASP.Net 2012 Unobtrusive Validation with jQuery

Just copy & paste any JQuery file in your project and add a Global.asax file and modify it as below:

I just paste the JQuery file in my project and add a reference in Global.asax file:

protected void Application_Start(object sender, EventArgs e)
    {
        ScriptManager.ScriptResourceMapping.AddDefinition(
        "jquery",
        new ScriptResourceDefinition
        {
            Path = "~/jquery-1.10.2.js",
            DebugPath = "~/jquery-1.10.2.js",
            CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js",
            CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.js",
            CdnSupportsSecureConnection = true,
            LoadSuccessExpression = "jQuery"
        });
    }

Java JTextField with input hint

You could create your own:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;

public class Main {

  public static void main(String[] args) {

    final JFrame frame = new JFrame();

    frame.setLayout(new BorderLayout());

    final JTextField textFieldA = new HintTextField("A hint here");
    final JTextField textFieldB = new HintTextField("Another hint here");

    frame.add(textFieldA, BorderLayout.NORTH);
    frame.add(textFieldB, BorderLayout.CENTER);
    JButton btnGetText = new JButton("Get text");

    btnGetText.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        String message = String.format("textFieldA='%s', textFieldB='%s'",
            textFieldA.getText(), textFieldB.getText());
        JOptionPane.showMessageDialog(frame, message);
      }
    });

    frame.add(btnGetText, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.pack();
  }
}

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

If you're still on Java 1.5, replace the this.getText().isEmpty() with this.getText().length() == 0.

How to determine the installed webpack version

In CLI

$ webpack --version
    
webpack-cli 4.1.0
    
webpack 5.3.2

In Code (node runtime)

process.env.npm_package_devDependencies_webpack // ^5.3.2

or

process.env.npm_package_dependencies_webpack // ^5.3.2

In Plugin

compiler.webpack.version // 5.3.2

how to get all markers on google-maps-v3

Google Maps API v3:

I initialized Google Map and added markers to it. Later, I wanted to retrieve all markers and did it simply by accessing the map property "markers".

var map = new GMaps({
    div: '#map',
    lat: 40.730610,
    lng: -73.935242,
});

var myMarkers = map.markers;

You can loop over it and access all Marker methods listed at Google Maps Reference.

How can I show a message box with two buttons?

It can be done, I found it elsewhere on the web...this is no way my work ! :)

    Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetDlgItemText Lib "user32" _
    Alias "SetDlgItemTextA" _
    (ByVal hDlg As Long, _
     ByVal nIDDlgItem As Long, _
     ByVal lpString As String) As Long

Private Declare Function SetWindowsHookEx Lib "user32" _
    Alias "SetWindowsHookExA" _
    (ByVal idHook As Long, _
     ByVal lpfn As Long, _
     ByVal hmod As Long, _
     ByVal dwThreadId As Long) As Long

Private Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Long) As Long

' Handle to the Hook procedure
Private hHook As Long

' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5

' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7

Public Sub MsgBoxSmile()
    ' Set Hook
    hHook = SetWindowsHookEx(WH_CBT, _
                             AddressOf MsgBoxHookProc, _
                             0, _
                             GetCurrentThreadId)

    ' Run MessageBox
    MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _
                                ByVal wParam As Long, _
                                ByVal lParam As Long) As Long

    If lMsg = HCBT_ACTIVATE Then
        SetDlgItemText wParam, IDYES, "Yes   :-)"
        SetDlgItemText wParam, IDNO, "No   :-("

        ' Release the Hook
        UnhookWindowsHookEx hHook
    End If

    MsgBoxHookProc = False
End Function

Getting DOM element value using pure JavaScript

In the second version, you're passing the String returned from this.id. Not the element itself.

So id.value won't give you what you want.

You would need to pass the element with this.

doSomething(this)

then:

function(el){
    var value = el.value;
    ...
}

Note: In some browsers, the second one would work if you did:

window[id].value 

because element IDs are a global property, but this is not safe.

It makes the most sense to just pass the element with this instead of fetching it again with its ID.

Windows Scipy Install: No Lapack/Blas Resources Found

I was also getting same error while installing scikit-fuzzy. I resolved error as follows:

  1. Install Numpy, a whl file
  2. Install Scipy, again a whl file

choose file according to python version like amd64 for python3 and other win32 file for the python27

  1. then pip install --user skfuzzy

I hope, It will work for you

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

Verify host key with pysftp

If You try to connect by pysftp to "normal" FTP You have to set hostkey to None.

import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None 
with pysftp.Connection(host='****',username='****',password='***',port=22,cnopts=cnopts) as sftp:
    print('DO SOMETHING')

How do I kill all the processes in Mysql "show processlist"?

I'd combine bash and mysql:

for i in $(mysql -Ne "select id from information_schema.processlist where user like 'foo%user' and time > 300;"); do
  mysql -e "kill ${i}"
done

Hash function that produces short hashes?

You can use the hashlib library for Python. The shake_128 and shake_256 algorithms provide variable length hashes. Here's some working code (Python3):

import hashlib
>>> my_string = 'hello shake'
>>> hashlib.shake_256(my_string.encode()).hexdigest(5)
'34177f6a0a'

Notice that with a length parameter x (5 in example) the function returns a hash value of length 2x.

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Count work days between two dates

In Calculating Work Days you can find a good article about this subject, but as you can see it is not that advanced.

--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
    SELECT *
    FROM dbo.SYSOBJECTS
    WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
    AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
 CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
    @StartDate DATETIME,
    @EndDate   DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)

--Define the output data type.
RETURNS INT

AS
--Calculate the RETURN of the function.
BEGIN
    --Declare local variables
    --Temporarily holds @EndDate during date reversal.
    DECLARE @Swap DATETIME

    --If the Start Date is null, return a NULL and exit.
    IF @StartDate IS NULL
        RETURN NULL

    --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
     IF @EndDate IS NULL
        SELECT @EndDate = @StartDate

    --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
    --Usually faster than CONVERT.
    --0 is a date (01/01/1900 00:00:00.000)
     SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
            @EndDate   = DATEADD(dd,DATEDIFF(dd,0,@EndDate)  , 0)

    --If the inputs are in the wrong order, reverse them.
     IF @StartDate > @EndDate
        SELECT @Swap      = @EndDate,
               @EndDate   = @StartDate,
               @StartDate = @Swap

    --Calculate and return the number of workdays using the input parameters.
    --This is the meat of the function.
    --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
     RETURN (
        SELECT
        --Start with total number of days including weekends
        (DATEDIFF(dd,@StartDate, @EndDate)+1)
        --Subtact 2 days for each full weekend
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)
        --If StartDate is a Sunday, Subtract 1
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
            THEN 1
            ELSE 0
        END)
        --If EndDate is a Saturday, Subtract 1
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
            THEN 1
            ELSE 0
        END)
        )
    END
GO

If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.

CakePHP select default value in SELECT input

The best answer to this could be

Don't use selct for this job use input instead

like this

echo  $this->Form->input('field_name', array(
          'type' => 'select',
            'options' => $options_arr, 
            'label' => 'label here',
            'value' => $id,  // default value
            'escape' => false,  // prevent HTML being automatically escaped
            'error' => false,
            'class' => 'form-control' // custom class you want to enter
        ));

Hope it helps.

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

Get GPS location from the web browser

Let's use the latest fat arrow functions:

navigator.geolocation.getCurrentPosition((loc) => {
  console.log('The location in lat lon format is: [', loc.coords.latitude, ',', loc.coords.longitude, ']');
})

Synchronization vs Lock

There are 4 main factors into why you would want to use synchronized or java.util.concurrent.Lock.

Note: Synchronized locking is what I mean when I say intrinsic locking.

  1. When Java 5 came out with ReentrantLocks, they proved to have quite a noticeble throughput difference then intrinsic locking. If youre looking for faster locking mechanism and are running 1.5 consider j.u.c.ReentrantLock. Java 6's intrinsic locking is now comparable.

  2. j.u.c.Lock has different mechanisms for locking. Lock interruptable - attempt to lock until the locking thread is interrupted; timed lock - attempt to lock for a certain amount of time and give up if you do not succeed; tryLock - attempt to lock, if some other thread is holding the lock give up. This all is included aside from the simple lock. Intrinsic locking only offers simple locking

  3. Style. If both 1 and 2 do not fall into categories of what you are concerned with most people, including myself, would find the intrinsic locking semenatics easier to read and less verbose then j.u.c.Lock locking.
  4. Multiple Conditions. An object you lock on can only be notified and waited for a single case. Lock's newCondition method allows for a single Lock to have mutliple reasons to await or signal. I have yet to actually need this functionality in practice, but is a nice feature for those who need it.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Determine number of pages in a PDF file

You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.

iTextSharp Example

You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
  class Program
{
    static void Main(string[] args)
      {
       // Right side of equation is location of YOUR pdf file
        string ppath = "C:\\aworking\\Hawkins.pdf";
        PdfReader pdfReader = new PdfReader(ppath);
        int numberOfPages = pdfReader.NumberOfPages;
        Console.WriteLine(numberOfPages);
        Console.ReadLine();
      }
   }
}

DisplayName attribute from Resources?

How about writing a custom attribute:

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceId) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

which could be used like this:

public class MyModel 
{
    [Required]
    [LocalizedDisplayName("labelForName")]
    public string Name { get; set; }
}

Is it possible to include one CSS file in another?

In some cases it is possible using @import "file.css", and most modern browsers should support this, older browsers such as NN4, will go slightly nuts.

Note: the import statement must precede all other declarations in the file, and test it on all your target browsers before using it in production.

Python: finding lowest integer

Or no float conversion at all by just specifying floats in the list.

l = [-1.2, 0.0, 1]
x = min(l)

or

l = min([-1.2, 0.0, 1])

How to zip a file using cmd line?

tar.exe -acf out.zip in.txt

out.zip is an output folder or filename and in.txt is an input folder or filename. To use this command you should be in the file existing folder.

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

How to delete a remote tag?

Delete local tag '12345'

git tag -d 12345

Delete remote tag '12345' (eg; GitHub version too)

git push origin :refs/tags/12345

alternative approach

git push --delete origin tagName
git tag -d tagName

enter image description here

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

PHP replacing special characters like à->a, è->e

Simple function. Transform strings like 'Ábç Éfg' to 'abc_efg'

/**
 * @param $str
 * @return mixed
 */
function sanitizeString($str) {
    $str = preg_replace('/[áàãâä]/ui', 'a', $str);
    $str = preg_replace('/[éèêë]/ui', 'e', $str);
    $str = preg_replace('/[íìîï]/ui', 'i', $str);
    $str = preg_replace('/[óòõôö]/ui', 'o', $str);
    $str = preg_replace('/[úùûü]/ui', 'u', $str);
    $str = preg_replace('/[ç]/ui', 'c', $str);
    $str = preg_replace('/[^a-z0-9]/i', '_', $str);
    $str = preg_replace('/_+/', '_', $str);

    return $str;
}

How to check whether a file is empty or not?

Since you have not defined what an empty file is. Some might consider a file with just blank lines also an empty file. So if you want to check if your file contains only blank lines (any whitespace character, '\r', '\n', '\t'), you can follow the example below:

Python3

import re

def whitespace_only(file):
    content = open(file, 'r').read()
    if re.search(r'^\s*$', content):
        return True

Explain: the example above uses regular expression (regex) to match the content (content) of the file.
Specifically: for regex of: ^\s*$ as a whole means if the file contains only blank lines and/or blank spaces.
- ^ asserts position at start of a line
- \s matches any whitespace character (equal to [\r\n\t\f\v ])
- * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
- $ asserts position at the end of a line

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

Access parent's parent from javascript object

If I'm reading your question correctly, objects in general are agnostic about where they are contained. They don't know who their parents are. To find that information, you have to parse the parent data structure. The DOM has ways of doing this for us when you're talking about element objects in a document, but it looks like you're talking about vanilla objects.

git: fatal: Could not read from remote repository

In my case it was the postBuffer..

git config --global http.postBuffer 524288000

For reference read: https://gist.github.com/marcusoftnet/1177936

How to change Rails 3 server default port in develoment?

Combining two previous answers, for Rails 4.0.4 (and up, presumably), this suffices at the end of config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    def default_options
      super.merge({Port: 10524})
    end
  end
end

Get Bitmap attached to ImageView

Other way to get a bitmap of an image is doing this:

Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue);
imageView.setImageBitmap(imagenAndroid);

Subversion ignoring "--password" and "--username" options

I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:

Host server.hostname
  User username

I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html

MySQL: Insert datetime into other datetime field

According to MySQL documentation, you should be able to just enclose that datetime string in single quotes, ('YYYY-MM-DD HH:MM:SS') and it should work. Look here: Date and Time Literals

So, in your case, the command should be as follows:

UPDATE products SET former_date='2011-12-18 13:17:17' WHERE id=1

"unadd" a file to svn before commit

svn rm --keep-local folder_name

Note: In svn 1.5.4 svn rm deletes unversioned files even when --keep-local is specified. See http://svn.haxx.se/users/archive-2009-11/0058.shtml for more information.

Setting width to wrap_content for TextView through code

A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.

If you want to update e.g. only the width you can do that with the following line in Kotlin.

tv.updateLayoutParams { width = WRAP_CONTENT }

Git error when trying to push -- pre-receive hook declined

You should ask whoever maintains the repo at git@mycogit/cit_pplus.git.

Your commits were rejected by the pre-receive hook of that repo (that's a user-configurable script that is intended to analyze incoming commits and decide if they are good enough to be accepted into the repo).

It is also a good idea to ask that person to update the hook, so it would print the reasons for the rejection.

If the maintainer is you yourself, then it looks like you've got a problem with your setup on the server-side. Please share more information then.

How to create dispatch queue in Swift 3

it is now simply:

let serialQueue = DispatchQueue(label: "my serial queue")

the default is serial, to get concurrent, you use the optional attributes argument .concurrent

Rename multiple columns by names

This is the function that you need: Then just pass the x in a rename(X) and it will rename all values that appear and if it isn't in there it won't error

rename <-function(x){
  oldNames = c("a","b","c")
  newNames = c("d","e","f")
  existing <- match(oldNames,names(x))
  names(x)[na.omit(existing)] <- newNames[which(!is.na(existing))]
  return(x)
}

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

How to replace url parameter with javascript/jquery?

try this

var updateQueryStringParam = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else { // Otherwise, add it to end of query string
            params = urlQueryString + '&' + newParam;
        }
    }

    // no parameter was set so we don't need the question mark
    params = params == '?' ? '' : params;

    window.history.replaceState({}, "", baseUrl + params);
};

How do I `jsonify` a list in Flask?

josonify works..but if you intend to just pass an array without the 'results' key, you can use json library from python. The following conversion works for me..

 import json

 @app.route('/test/json')
 def test_json():
 list = [
        {'a': 1, 'b': 2},
        {'a': 5, 'b': 10}
       ]
 return json.dumps(list))

JavaScript Editor Plugin for Eclipse

In 2015 I would go with:

  • For small scripts: The js editor + jsHint plugin
  • For large code bases: TypeScript Eclipse plugin, or a similar transpiled language... I only know that TypeScript works well in Eclipse.

Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.

Or just wait for ECMA6, 7, ... :)