Programs & Examples On #Rehosting

HTTP Error 500.30 - ANCM In-Process Start Failure

From ASP.NET Core 3.0+ and visual studio 19 version 16.3+ You will find section in project .csproj file are like below-

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

There is no AspNetCoreHostingModel property there. You will find Hosting model selection in the properties of the project. Right-click the project name in the solution explorer. Click properties.

enter image description here

Click the Debug menu.

enter image description here

enter image description here

Scroll down to find the Hosting Model option.

enter image description here

Select Out of Process.

enter image description here

Save the project and run IIS Express.

UPDATE For Server Deployment:

When you publish your application in the server there is a web config file like below:

enter image description here

change value of 'hostingModel' from 'inprocess' to 'outofprocess' like below:

enter image description here

What is the best method to merge two PHP objects?

To merge any number of raw objects

function merge_obj(){
    foreach(func_get_args() as $a){
        $objects[]=(array)$a;
    }
    return (object)call_user_func_array('array_merge', $objects);
}

What's the UIScrollView contentInset property for?

It's used to add padding in UIScrollView

Without contentInset, a table view is like this:

enter image description here

Then set contentInset:

tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

The effect is as below:

enter image description here

Seems to be better, right?

And I write a blog to study the contentInset, criticism is welcome.

How to sum a variable by group

library(tidyverse)

x <- data.frame(Category= c('First', 'First', 'First', 'Second', 'Third', 'Third', 'Second'), 
           Frequency = c(10, 15, 5, 2, 14, 20, 3))

count(x, Category, wt = Frequency)

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Error in plot.new() : figure margins too large in R

enter image description here

Just zoom this area if you use RStudio.

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

Setting this attribute to ObjectMapper instance works,

objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

How do I edit a file after I shell to a Docker container?

You can open existing file with

cat filename.extension

and copy all the existing text on clipboard.

Then delete old file with

rm filename.extension

or rename old file with

mv old-filename.extension new-filename.extension

Create new file with

cat > new-file.extension

Then paste all text copied on clipboard, press Enter and exit with save by pressing ctrl+z. And voila no need to install any kind of editors.

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

How to check SQL Server version

Here is what i have done to find the version Here is what i have done to find the version: just write SELECT @@version and it will give you the version.

Show message box in case of exception

        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

MySQL "Group By" and "Order By"

Do a GROUP BY after the ORDER BY by wrapping your query with the GROUP BY like this:

SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t GROUP BY t.from

How organize uploaded media in WP?

The plugin Media File Manager advanced is amazing and allow you to create folders and subfolders very easily and move files with a simple drag & drop.

Check it at: http://wordpress.org/plugins/media-file-manager-advanced/

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${project.build.directory} is equivalent to ${project.basedir}/target

as it is defined here: https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to develop Android app completely using python?

Android, Python !

When I saw these two keywords together in your question, Kivy is the one which came to my mind first.

Kivy logo

Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.


Simple to use

With a python basics, you won't have trouble learning it.


Good community

It's well documented and has a great, active community.


Cross platform.

You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.


It is a free software

At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.


Accelerated graphics support

Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.



Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.

How to add external JS scripts to VueJS Components

Simplest solution is to add the script in the index.html file of your vue-project

index.html:

 <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>vue-webpack</title>
      </head>
      <body>
        <div id="app"></div>
        <!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
    0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
    for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
    MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
    mixpanel.init("xyz");</script><!-- end Mixpanel -->
        <script src="/dist/build.js"></script>
      </body>
    </html>

How to make a .NET Windows Service start right after the installation?

You can do this all from within your service executable in response to events fired from the InstallUtil process. Override the OnAfterInstall event to use a ServiceController class to start the service.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx

Does MS SQL Server's "between" include the range boundaries?

Real world example from SQL Server 2008.

Source data:

ID    Start
1     2010-04-30 00:00:01.000
2     2010-04-02 00:00:00.000
3     2010-05-01 00:00:00.000
4     2010-07-31 00:00:00.000

Query:

SELECT
    *
FROM
    tbl
WHERE
    Start BETWEEN '2010-04-01 00:00:00' AND '2010-05-01 00:00:00'

Results:

ID    Start
1     2010-04-30 00:00:01.000
2     2010-04-02 00:00:00.000

alt text

Save attachments to a folder and rename them

See ReceivedTime Property

http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx

You added another \ to the end of C:\Temp\ in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.

dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  
saveFolder = "C:\Temp"

You have not set objAtt so there is no need for "Set objAtt = Nothing". If there was it would be just before End Sub not in the loop.


Public Sub saveAttachtoDisk (itm As Outlook.MailItem) 
    Dim objAtt As Outlook.Attachment 
    Dim saveFolder As String Dim dateFormat
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  saveFolder = "C:\Temp"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Re: It worked the first day I started tinkering but after that it stopped saving files.

This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

In my case, I had to exclude an older hamcrest from junit-vintage:

<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest</artifactId>
  <version>2.1</version>
  <scope>test</scope>
</dependency>

Set width of dropdown element in HTML select dropdown options

Small And Better One

var i = 0;
$("#container > option").each(function(){ 
    if($(this).val().length > i) {
        i = $(this).val().length;

        console.log(i);
        console.log($(this).val());
    }
});

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

In the end after trying many of these complicated solutions as I only needed to save/restore a single value in my Fragment (the content of an EditText), and although it might not be the most elegant solution, creating a SharedPreference and storing my state there worked for me

How to write a switch statement in Ruby

case...when

To add more examples to Chuck's answer:

With parameter:

case a
when 1
  puts "Single value"
when 2, 3
  puts "One of comma-separated values"
when 4..6
  puts "One of 4, 5, 6"
when 7...9
  puts "One of 7, 8, but not 9"
else
  puts "Any other thing"
end

Without parameter:

case
when b < 3
  puts "Little than 3"
when b == 3
  puts "Equal to 3"
when (1..10) === b
  puts "Something in closed range of [1..10]"
end

Please, be aware of "How to write a switch statement in Ruby" that kikito warns about.

Check if Key Exists in NameValueCollection

Yes, you can use Linq to check the AllKeys property:

using System.Linq;
...
collection.AllKeys.Contains(key);

However a Dictionary<string, string[]> would be far more suited to this purpose, perhaps created via an extension method:

public static void Dictionary<string, string[]> ToDictionary(this NameValueCollection collection) 
{
    return collection.Cast<string>().ToDictionary(key => key, key => collection.GetValues(key));
}

var dictionary = collection.ToDictionary();
if (dictionary.ContainsKey(key))
{
   ...
}

Resource leak: 'in' is never closed

You need call in.close(), in a finally block to ensure it occurs.

From the Eclipse documentation, here is why it flags this particular problem (emphasis mine):

Classes implementing the interface java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed.

The Eclipse Java compiler is able to analyze whether code using such types adheres to this policy.

...

The compiler will flag [violations] with "Resource leak: 'stream' is never closed".

Full explanation here.

npm check and update package if needed

One easy step:

$ npm i -g npm-check-updates && ncu -u && npm i

That is all. All of the package versions in package.json will be the latest major versions.

Edit:

What is happening here?

  1. Installing a package that checks updates for you.

  2. Use this package to update all package versions in your package.json (-u is short for --updateAll).

  3. Install all of the new versions of the packages.

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

You can do this in any program other than Explorer, e.g. Notepad, cmd.exe etc.

You just can't do it in Explorer, and Raymond Chen has offered an explanation as to why not.

How often does python flush to a file?

You can also force flush the buffer to a file programmatically with the flush() method.

with open('out.log', 'w+') as f:
    f.write('output is ')
    # some work
    s = 'OK.'
    f.write(s)
    f.write('\n')
    f.flush()
    # some other work
    f.write('done\n')
    f.flush()

I have found this useful when tailing an output file with tail -f.

Wait until all jQuery Ajax requests are done?

On the basis of @BBonifield answer, I wrote a utility function so that semaphore logic is not spread in all the ajax calls.

untilAjax is the utility function which invokes a callback function when all the ajaxCalls are completed.

ajaxObjs is a array of ajax setting objects [http://api.jquery.com/jQuery.ajax/].

fn is callback function

function untilAjax(ajaxObjs, fn) {
  if (!ajaxObjs || !fn) {
    return;
  }
  var ajaxCount = ajaxObjs.length,
    succ = null;

  for (var i = 0; i < ajaxObjs.length; i++) { //append logic to invoke callback function once all the ajax calls are completed, in success handler.
    succ = ajaxObjs[i]['success'];
    ajaxObjs[i]['success'] = function(data) { //modified success handler
      if (succ) {
        succ(data);
      }
      ajaxCount--;
      if (ajaxCount == 0) {
        fn(); //modify statement suitably if you want 'this' keyword to refer to another object
      }
    };
    $.ajax(ajaxObjs[i]); //make ajax call
    succ = null;
  };

Example: doSomething function uses untilAjax.

function doSomething() {
  // variable declarations
  untilAjax([{
    url: 'url2',
    dataType: 'json',
    success: function(data) {
      //do something with success data
    }
  }, {
    url: 'url1',
    dataType: 'json',
    success: function(data) {
      //do something with success data
    }
  }, {
    url: 'url2',
    dataType: 'json',
    success: function(response) {
      //do something with success data
    }
  }], function() {
    // logic after all the calls are completed.
  });
}

How to declare a constant map in Golang?

As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

The Initialization would look like this:

var romanNumeralDict = struct {
    m map[int]string
}{m: map[int]string {
    1000: "M",
    900: "CM",
    //YOUR VALUES HERE
}}

func main() {
    d := 1000
    fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}

How do I check if the mouse is over an element in jQuery?

Here's a technique which doesn't rely on jquery and uses the native DOM matches API. It uses vendor prefixes to support browsers going back to IE9. See matchesselector on caniuse.com for full details.

First create the matchesSelector function, like so:

var matchesSelector = (function(ElementPrototype) {
var fn = ElementPrototype.matches ||
          ElementPrototype.webkitMatchesSelector ||
          ElementPrototype.mozMatchesSelector ||
          ElementPrototype.msMatchesSelector;

return function(element, selector) {
  return fn.call(element, selector);
};

})(Element.prototype);

Then, to detect hover:

var mouseIsOver = matchesSelector(element, ':hover');

How to declare a type as nullable in TypeScript?

Union type is in my mind best option in this case:

interface Employee{
   id: number;
   name: string;
   salary: number | null;
}

// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };

EDIT : For this to work as expected, you should enable the strictNullChecks in tsconfig.

How to Set a Custom Font in the ActionBar Title?

I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:

this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);

LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);

//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());

//assign the view to the actionbar
this.getActionBar().setCustomView(v);

And my layout xml (R.layout.titleview in the code above) looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

<com.your.package.CustomTextView
        android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"
            android:maxLines="1"
            android:ellipsize="end"
            android:text="" />
</RelativeLayout>

What is a good pattern for using a Global Mutex in C#?

Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share.

Use:

using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
    //Only 1 of these runs at a time
    RunSomeStuff();
}

And the helper class:

class SingleGlobalInstance : IDisposable
{
    //edit by user "jitbit" - renamed private fields to "_"
    public bool _hasHandle = false;
    Mutex _mutex;

    private void InitMutex()
    {
        string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
        string mutexId = string.Format("Global\\{{{0}}}", appGuid);
        _mutex = new Mutex(false, mutexId);

        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);
        _mutex.SetAccessControl(securitySettings);
    }

    public SingleGlobalInstance(int timeOut)
    {
        InitMutex();
        try
        {
            if(timeOut < 0)
                _hasHandle = _mutex.WaitOne(Timeout.Infinite, false);
            else
                _hasHandle = _mutex.WaitOne(timeOut, false);

            if (_hasHandle == false)
                throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
        }
        catch (AbandonedMutexException)
        {
            _hasHandle = true;
        }
    }


    public void Dispose()
    {
        if (_mutex != null)
        {
            if (_hasHandle)
                _mutex.ReleaseMutex();
            _mutex.Close();
        }
    }
}

Does 'position: absolute' conflict with Flexbox?

You have to give width:100% to parent to center the text.

_x000D_
_x000D_
 .parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you also need to centre align vertically, give height:100% and align-itens: center

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
   position: absolute;
   width:100%;
   height: 100%;
 }

Delete entire row if cell contains the string X

I'd like to add to @MBK's answer. Although I found @MBK's answer to be very helpful in solving a similar problem, it'd be better if @MBK included a screenshot of how to filter a particular column.enter image description here

Writing to a new file if it doesn't exist, and appending to a file if it does

Notice that if the file's parent folder doesn't exist you'll get the same error:

IOError: [Errno 2] No such file or directory:

Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case

# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
     os.makedirs(folder_path)

print_to_log_file(folder_path, "Some File" ,"Some Content")

Where the internal print_to_log_file just take care of the file level:

# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):

   #1) Save a reference to the original standard output       
    original_stdout = sys.stdout   
    
    #2) Choose the mode
    write_append_mode = 'a' #Append mode
    file_path = folder_path + file_name
    if (if not os.path.exists(file_path) ):
       write_append_mode = 'w' # Write mode
     
    #3) Perform action on file
    with open(file_path, write_append_mode) as f:
        sys.stdout = f  # Change the standard output to the file we created.
        print(file_path, content_to_write)
        sys.stdout = original_stdout  # Reset the standard output to its original value

Consider the following states:

'w'  --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a'  --> Append to file
'a+' --> Append to file, Create it if doesn't exist

In your case I would use a different approach and just use 'a' and 'a+'.

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

Call a VBA Function into a Sub Procedure

Here are some of the different ways you can call things in Microsoft Access:

To call a form sub or function from a module

The sub in the form you are calling MUST be public, as in:

Public Sub DoSomething()
  MsgBox "Foo"
End Sub

Call the sub like this:

Call Forms("form1").DoSomething

The form must be open before you make the call.

To call an event procedure, you should call a public procedure within the form, and call the event procedure within this public procedure.

To call a subroutine in a module from a form

Public Sub DoSomethingElse()
  MsgBox "Bar"
End Sub

...just call it directly from your event procedure:

Call DoSomethingElse

To call a subroutine from a form without using an event procedure

If you want, you can actually bind the function to the form control's event without having to create an event procedure under the control. To do this, you first need a public function in the module instead of a sub, like this:

Public Function DoSomethingElse()
  MsgBox "Bar"
End Function

Then, if you have a button on the form, instead of putting [Event Procedure] in the OnClick event of the property window, put this:

=DoSomethingElse()

When you click the button, it will call the public function in the module.

To call a function instead of a procedure

If calling a sub looks like this:

Call MySub(MyParameter)

Then calling a function looks like this:

Result=MyFunction(MyFarameter)

where Result is a variable of type returned by the function.

NOTE: You don't always need the Call keyword. Most of the time, you can just call the sub like this:

MySub(MyParameter)

Jquery: How to check if the element has certain css class/style

Question is asking for two different things:

  1. An element has certain class
  2. An element has certain style.

Second question has been already answered. For the first one, I would do it this way:

if($("#someElement").is(".test")){
    // Has class test assigned, eventually combined with other classes
}
else{
    // Does not have it
}

Maximum length for MySQL type text

Acording to http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html, the limit is L + 2 bytes, where L < 2^16, or 64k.

You shouldn't need to concern yourself with limiting it, it's automatically broken down into chunks that get added as the string grows, so it won't always blindly use 64k.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

With the latest Firefox, I must use:

<script type="text/javascript">...</script>

Or else the script may not run properly.

Cannot authenticate into mongo, "auth fails"

In MongoDB 3.0, it now supports multiple authentication mechanisms.

  1. MongoDB Challenge and Response (SCRAM-SHA-1) - default in 3.0
  2. MongoDB Challenge and Response (MONGODB-CR) - previous default (< 3.0)

If you started with a new 3.0 database with new users created, they would have been created using SCRAM-SHA-1.

So you will need a driver capable of that authentication:

http://docs.mongodb.org/manual/release-notes/3.0-scram/#considerations-scram-sha-1-drivers

If you had a database upgraded from 2.x with existing user data, they would still be using MONGODB-CR, and the user authentication database would have to be upgraded:

http://docs.mongodb.org/manual/release-notes/3.0-scram/#upgrade-mongodb-cr-to-scram

Now, connecting to MongoDB 3.0 with users created with SCRAM-SHA-1 are required to specify the authentication database (via command line mongo client), and using other mechanisms if using a driver.

$> mongo -u USER -p PASSWORD --authenticationDatabase admin

In this case, the "admin" database, which is also the default will be used to authenticate.

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

VB.NET - Remove a characters from a String

The string class's Replace method can also be used to remove multiple characters from a string:

Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")

How do I run a docker instance from a DockerFile?

Straightforward and easy solution is:

docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67

3000 - can be any port

a3e628814c68 - hash result given by success build command

NOTE: you should be within directory that contains Dockerfile.

How to cast a double to an int in Java by rounding it down?

(int)99.99999

It will be 99. Casting a double to an int does not round, it'll discard the fraction part.

String contains - ignore case

An optimized Imran Tariq's version

Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();

Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.

How do I disable Git Credential Manager for Windows?

It didn't work for me:

C:\Program Files\Git\mingw64\libexec\git-core
git-credential-manager.exe uninstall

Looking for Git installation(s)...
  C:\Program Files\Git

Updated your /etc/gitconfig [git config --system]
Updated your ~/.gitconfig [git config --global]

Removing from 'C:\Program Files\Git'.
  removal failed. U_U

Press any key to continue...

But with the --force flag it worked:

C:\Program Files\Git\mingw64\libexec\git-core
git credential-manager uninstall --force
08:21:42.537616 exec_cmd.c:236          trace: resolved executable dir: C:/Program Files/Git/mingw64/libexec/git-core
e
08:21:42.538616 git.c:576               trace: exec: git-credential-manager uninstall --force
08:21:42.538616 run-command.c:640       trace: run_command: git-credential-manager uninstall --force

Looking for Git installation(s)...
  C:\Program Files\Git

Updated your /etc/gitconfig [git config --system]
Updated your ~/.gitconfig [git config --global]


Success! Git Credential Manager for Windows was removed! ^_^

Press any key to continue...

I could see that trace after I run:

set git_trace=1

Also I added the Git username:

git config --global credential.username myGitUsername

Then:

C:\Program Files\Git\mingw64\libexec\git-core
git config --global credential.helper manager

In the end I put in this command:

git config --global credential.modalPrompt false

I check if the SSH agent is running - open a Bash window to run this command

eval "$(ssh-agent -s)"

Then in the computer users/yourName folder where .ssh is, add a connection (still in Bash):

ssh-add .ssh/id_rsa

or

ssh-add ~/.ssh/id_rsa(if you are not in that folder)

I checked all the settings that I add above:

C:\Program Files\Git\mingw64\libexec\git-core
git config --list
09:41:28.915183 exec_cmd.c:236          trace: resolved executable dir: C:/Program Files/Git/mingw64/libexec/git-cor
e
09:41:28.917182 git.c:344               trace: built-in: git config --list
09:41:28.918181 run-command.c:640       trace: run_command: unset GIT_PAGER_IN_USE; LESS=FRX LV=-c less
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
credential.modalprompt=false
credential.username=myGitUsername

And when I did git push again I had to add username and password only for the first time.

git push
Please enter your GitHub credentials for https://[email protected]/
username: myGithubUsername
password: *************
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 316 bytes | 316.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.

Since then using git push, I don't have the message to enter my Git credentials any more.

D:\projects\react-redux\myProject (master -> origin) ([email protected])
? git push
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 314 bytes | 314.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To https://github.com/myGitUsername/myProject.git
   8d38b18..f442d74  master -> master

After these settings I received an email too with the message:

 A personal access token (git: https://[email protected]/
on LAP0110 at 25-Jun-2018 09:22) with gist and repo scopes was recently added
to your account. Visit https://github.com/settings/tokens for more information.

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

Custom Python list sorting

This does not work in Python 3.

You can use functools cmp_to_key to have old-style comparison functions work though.

from functools import cmp_to_key

def cmp_items(a, b):
    if a.foo > b.foo:
        return 1
    elif a.foo == b.foo:
        return 0
    else:
        return -1

cmp_items_py3 = cmp_to_key(cmp_items)

alist.sort(cmp_items_py3)

What's the best way to share data between activities?

There is a new and better way to share data between activities, and it is LiveData. Notice in particular this quote from the Android developer's page:

The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services. To keep the example simple, you can implement the LiveData class as a singleton

The implication of this is huge - any model data can be shared in a common singleton class inside a LiveData wrapper. It can be injected from the activities into their respective ViewModel for the sake of testability. And you no longer need to worry about weak references to prevent memory leaks.

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

August 2019

In my case I wanted to use a Swift protocol in an Objective-C header file that comes from the same target and for this I needed to use a forward declaration of the Swift protocol to reference it in the Objective-C interface. The same should be valid for using a Swift class in an Objective-C header file. To use forward declaration see the following example from the docs at Include Swift Classes in Objective-C Headers Using Forward Declarations:

// MyObjcClass.h
@class MySwiftClass; // class forward declaration
@protocol MySwiftProtocol; // protocol forward declaration

@interface MyObjcClass : NSObject
- (MySwiftClass *)returnSwiftClassInstance;
- (id <MySwiftProtocol>)returnInstanceAdoptingSwiftProtocol;
// ...
@end

How to advance to the next form input when the current input has a value?

In the first question, you don't need an event listener on every input that would be wasteful.

Instead, listen for the enter key and to find the currently focused element use document.activeElement

window.onkeypress = function(e) {
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
};

One event listener is better than many, especially on low power / mobile browsers.

Multiplying across in a numpy array

I've compared the different options for speed and found that – much to my surprise – all options (except diag) are equally fast. I personally use

A * b[:, None]

(or (A.T * b).T) because it's short.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot


def newaxis(data):
    A, b = data
    return A * b[:, numpy.newaxis]


def none(data):
    A, b = data
    return A * b[:, None]


def double_transpose(data):
    A, b = data
    return (A.T * b).T


def double_transpose_contiguous(data):
    A, b = data
    return numpy.ascontiguousarray((A.T * b).T)


def diag_dot(data):
    A, b = data
    return numpy.dot(numpy.diag(b), A)


def einsum(data):
    A, b = data
    return numpy.einsum("ij,i->ij", A, b)


perfplot.save(
    "p.png",
    setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
    kernels=[
        newaxis,
        none,
        double_transpose,
        double_transpose_contiguous,
        diag_dot,
        einsum,
    ],
    n_range=[2 ** k for k in range(13)],
    xlabel="len(A), len(b)",
)

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

Android ClassNotFoundException: Didn't find class on path

I had this issue recently and I am using Android Studio 0.8.4

The problem was the fact that I decided to rename an XML menu layout file that was called main.xml.

Right click on it and chose Refactor --> Rename. Before renaming it, be sure uncheck "Search in comments and strings" and pressed Refactor.

Because my file was originally named 'main', it renamed critical paths in the app.iml and build.gradle, mainly the java.srcDirs in the build.gradle, since the path is defined as 'src/main/java'.

I hope this helps anyone that may be experiencing this issue.

What is ToString("N0") format?

Here is a good start maybe

Double.ToString()

Have a look in the examples for a number of different formating options Double.ToString(string)

scale fit mobile web content using viewport meta tag

ok, here is my final solution with 100% native javascript:

<meta id="viewport" name="viewport">

<script type="text/javascript">
//mobile viewport hack
(function(){

  function apply_viewport(){
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)   ) {

      var ww = window.screen.width;
      var mw = 800; // min width of site
      var ratio =  ww / mw; //calculate ratio
      var viewport_meta_tag = document.getElementById('viewport');
      if( ww < mw){ //smaller than minimum size
        viewport_meta_tag.setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=no, width=' + mw);
      }
      else { //regular size
        viewport_meta_tag.setAttribute('content', 'initial-scale=1.0, maximum-scale=1, minimum-scale=1.0, user-scalable=yes, width=' + ww);
      }
    }
  }

  //ok, i need to update viewport scale if screen dimentions changed
  window.addEventListener('resize', function(){
    apply_viewport();
  });

  apply_viewport();

}());
</script>

'AND' vs '&&' as operator

Here's a little counter example:

$a = true;
$b = true;
$c = $a & $b;
var_dump(true === $c);

output:

bool(false)

I'd say this kind of typo is far more likely to cause insidious problems (in much the same way as = vs ==) and is far less likely to be noticed than adn/ro typos which will flag as syntax errors. I also find and/or is much easier to read. FWIW, most PHP frameworks that express a preference (most don't) specify and/or. I've also never run into a real, non-contrived case where it would have mattered.

Align printf output in Java

Here's a potential solution that will set the width of the bookType column (i.e. format of the bookTypes value) based on the longest bookTypes value.

public class Test {
    public static void main(String[] args) {
        String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" };
        double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 };

        // Find length of longest bookTypes value.
        int maxLengthItem = 0;
        boolean firstValue = true;
        for (String bookType : bookTypes) {
            maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length());
            firstValue = false;
        }

        // Display rows of data
        for (int i = 0; i < bookTypes.length; i++) {
            // Use %6.2 instead of %.2 so that decimals line up, assuming max
            // book cost of $999.99. Change 6 to a different number if max cost
            // is different
            String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n";
            System.out.printf(format, i + 1, bookTypes[i], costs[i]);
        }
    }
}

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Personally, I prefer changing the method signature to:

public ResponseEntity<?>

This gives the advantage of possibly returning an error message as single item for services which, when ok, return a list of items.

When returning I don't use any type (which is unused in this case anyway):

return new ResponseEntity<>(entities, HttpStatus.OK);

Can I have multiple primary keys in a single table?

Having two primary keys at the same time, is not possible. But (assuming that you have not messed the case up with composite key), may be what you might need is to make one attribute unique.

CREATE t1(
c1 int NOT NULL,
c2 int NOT NULL UNIQUE,
...,
PRIMARY KEY (c1)
);

However note that in relational database a 'super key' is a subset of attributes which uniquely identify a tuple or row in a table. A 'key' is a 'super key' that has an additional property that removing any attribute from the key, makes that key no more a 'super key'(or simply a 'key' is a minimal super key). If there are more keys, all of them are candidate keys. We select one of the candidate keys as a primary key. That's why talking about multiple primary keys for a one relation or table is being a conflict.

What is the proper REST response code for a valid request but an empty data?

Why not use 410? It suggests the requested resource no longer exists and the client is expected to never make a request for that resource, in your case users/9.

You can find more details about 410 here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

What is the facade design pattern?

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Run multiple python scripts concurrently

You try the following ways to run the multiple python scripts:

  import os
  print "Starting script1"
  os.system("python script1.py arg1 arg2 arg3")
  print "script1 ended"
  print "Starting script2"
  os.system("python script2.py arg1 arg2 arg3")
  print "script2 ended"

Note: The execution of multiple scripts depends purely underlined operating system, and it won't be concurrent, I was new comer in Python when I answered it.

Update: I found a package: https://pypi.org/project/schedule/ Above package can be used to run multiple scripts and function, please check this and maybe on weekend will provide some example too.

i.e:

 import schedule
 import time
 import script1, script2

 def job():
     print("I'm working...")

 schedule.every(10).minutes.do(job)
 schedule.every().hour.do(job)
 schedule.every().day.at("10:30").do(job)
 schedule.every(5).to(10).days.do(job)
 schedule.every().monday.do(job)
 schedule.every().wednesday.at("13:15").do(job)

 while True:
     schedule.run_pending()
     time.sleep(1)

Opposite of append in jquery

just had the same problem and ive come across this - which actually does the trick for me:

// $("#the_div").contents().remove();
// or short: 
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");

download file using an ajax request

You actually don't need ajax at all for this. If you just set "download.php" as the href on the button, or, if it's not a link use:

window.location = 'download.php';

The browser should recognise the binary download and not load the actual page but just serve the file as a download.

jQueryUI modal dialog does not show close button (x)

I think the problem is that the browser could not load the jQueryUI image sprite that contains the X icon. Please use Fiddler, Firebug, or some other that can give you access to the HTTP requests the browser makes to the server and verify the image sprite is loaded successfully.

Mysql password expired. Can't connect

All of these answers are using Linux consoles to access MySQL.

If you are on Windows and are using WAMP, you can start by opening the MySQL console (click WAMP icon->MySQL->MySQL console).

Then it will request you to enter your current password, enter it.

And then type SET PASSWORD = PASSWORD('some_pass');

Is there a Java equivalent or methodology for the typedef keyword in C++?

Perhaps this could be another possible replace :

@Data
public class MyMap {
    @Delegate //lombok
    private HashMap<String, String> value;
}

Questions every good .NET developer should be able to answer?

I suggest enquiring about blogs that they read on a regular basis and personal programming projects that they have worked on as this will show a willingness to learn and a passion for programming.

configure Git to accept a particular self-signed server certificate for a particular https remote

Briefly:

  1. Get the self signed certificate
  2. Put it into some (e.g. ~/git-certs/cert.pem) file
  3. Set git to trust this certificate using http.sslCAInfo parameter

In more details:

Get self signed certificate of remote server

Assuming, the server URL is repos.sample.com and you want to access it over port 443.

There are multiple options, how to get it.

Get certificate using openssl

$ openssl s_client -connect repos.sample.com:443

Catch the output into a file cert.pem and delete all but part between (and including) -BEGIN CERTIFICATE- and -END CERTIFICATE-

Content of resulting file ~/git-certs/cert.pem may look like this:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

Get certificate using your web browser

I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.

Using Firefox, I went to Options -> Advanced -> Certificates -> View Certificates -> Servers, found there the selfsigned host, selected it and using Export button I got exactly the same file, as created using openssl.

Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.

Having the trusted certificate in dedicated file

Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used ~/git-certs/cert.pem

Note: If you need more trusted selfsigned certificates, put them into the same file:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

This shall work (but I tested it only with single certificate).

Configure git to trust this certificate

$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem

You may also try to do that system wide, using --system instead of --global.

And test it: You shall now be able communicating with your server without resorting to:

$ git config --global http.sslVerify false #NO NEED TO USE THIS

If you already set your git to ignorance of ssl certificates, unset it:

$ git config --global --unset http.sslVerify

and you may also check, that you did it all correctly, without spelling errors:

$ git config --global --list

what should list all variables, you have set globally. (I mispelled http to htt).

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

jquery dialog save cancel button styling

check out jquery ui 1.8.5 it's available here http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js and it has the new button for dialog ui implementation

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Get just the filename from a path in a Bash script

$ source_file_filename_no_ext=${source_file%.*}
$ echo ${source_file_filename_no_ext##*/}

jQuery: Currency Format Number

Please find in the below code what I developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used ‘en’ while have tested for ‘es’, ‘fr’ and other countries where in the format varies. It not only stops user from keying characters but formats the value on tab out. Have created components for Number as well as for Decimal format. Apart from this have created parseNumber(value, locale) and parseDecimal(value, locale) functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used JQuery validator plugin in the below shared code.

HTML:

<tr>
                            <td>
                                <label class="control-label">
                                    Number Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="numberField" 
                                           name="numberField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="17"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           data-rule-numberExceedsMaxLimit="en"
                                           data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"
                                           onkeydown="return isNumber(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="numberFormatter(this,                                                           
                                                       'en', 
                                                       'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label class="control-label">
                                    Decimal Field:
                                </label>
                                <div class="inner-addon right-addon">                                        
                                    <input type="text" id="decimalField" 
                                           name="decimalField"
                                           class="form-control"
                                           autocomplete="off"
                                           maxlength="20"
                                           data-rule-required="true"
                                           data-msg-required="Cannot be blank."
                                           data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           data-rule-decimalExceedsMaxLimit="en"
                                           data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"
                                           onkeydown="return isDecimal(event, 'en')"
                                           onkeyup="return updateField(this)"
                                           onblur="decimalFormatter(this,
                                               'en', 
                                               'Invalid character(s) found. Please enter valid characters.')">
                                </div>
                            </td>
                        </tr>

JavaScript:

            /* 
     * @author: dinesh.lomte
     */
    /* Holds the maximum limit of digits to be entered in number field. */
    var numericMaxLimit = 13;
    /* Holds the maximum limit of digits to be entered in decimal field. */
    var decimalMaxLimit = 16;

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Boolean}
     */
    parseDecimal = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0.00;
        }
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            value = value.replace(/\./g, '');
        } else {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[0], 'g'), '');
        }
        if (getNumberFormat(locale)[1] === ',') {
            value = value.replace(
                    new RegExp(getNumberFormat(locale)[1], 'g'), '.');
        }
        return value;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    decimalFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();
        value = value.replace(/\s/g, '');
        value = parseDecimal(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} element
     * @param {type} locale
     * @param {type} nanMessage
     * @returns {Boolean}
     */
    numberFormatter = function (element, locale, nanMessage) {

        showErrorMessage(element.id, false, null);
        if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
            return true;
        }
        var value = element.value.trim();    
        var format = getNumberFormat(locale);
        if (hasDecimal(value, format[1])) {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        value = value.replace(/\s/g, '');
        value = parseNumber(value, locale);
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }
        );
        if (numberFormatObj.format(value) === 'NaN') {
            showErrorMessage(element.id, true, nanMessage);
            setFocus(element.id);
            return false;
        }
        element.value =
                numberFormatObj.format(value);
        return true;
    };

    /**
     * 
     * @param {type} id
     * @param {type} flag
     * @param {type} message
     * @returns {undefined}
     */
    showErrorMessage = function(id, flag, message) {

        if (flag) {
            // only add if not added
            if ($('#'+id).parent().next('.app-error-message').length === 0) {
                var errorTag = '<div class=\'app-error-message\'>' + message + '</div>';
                $('#'+id).parent().after(errorTag);
            }
        } else {
            // remove it
            $('#'+id).parent().next(".app-error-message").remove(); 
        }
    };

    /**
     * 
     * @param {type} id             
     * @returns
     */
    setFocus = function(id) {

        id = id.trim();
        if (isNull(id)) {
            return;
        }
        setTimeout(function() {
            document.getElementById(id).focus();
        }, 10);
    };

    /**
     * 
     * @param {type} value
     * @param {type} locale
     * @returns {Array}
     */
    parseNumber = function(value, locale) {

        value = value.trim();
        if (isNull(value)) {
            return 0;
        }    
        if (isNull(locale)) {
            return value;
        }
        if (getNumberFormat(locale)[0] === '.') {
            return value.replace(/\./g, '');
        }
        return value.replace(
                new RegExp(getNumberFormat(locale)[0], 'g'), '');
    };

    /**
     * 
     * @param {type} locale
     * @returns {Array}
     */
    getNumberFormat = function(locale) {

        var format = [];
        var numberFormatObj = new Intl.NumberFormat(locale,
                {   minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
        );
        var value = numberFormatObj.format('132617.07');
        format[0] = value.charAt(3);
        format[1] = value.charAt(7);
        return format;
    };

    /**
     * 
     * @param {type} value
     * @param {type} fractionFormat
     * @returns {Boolean}
     */
    hasDecimal = function(value, fractionFormat) {

        value = value.trim();
        if (isNull(value) || isNull(fractionFormat)) {
            return false;
        }
        if (value.indexOf(fractionFormat) >= 1) {
            return true;
        }
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isNumber = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {        
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && getNumberFormat(locale)[0] === getFormat(keyCode)) {        
            return true;
        }    
        return false;
    };

    /**
     * 
     * @param {type} event
     * @param {type} locale
     * @returns {Boolean}
     */
    isDecimal = function(event, locale) {

        var keyCode = event.which ? event.which : event.keyCode;
        // Validating if user has pressed shift character
        if (keyCode === 16) {
            return false;
        }
        if (isNumberKey(keyCode)) {
            return true;
        }
        var numberFormatter = [32, 110, 188, 190];
        if (keyCode === 32
                && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
            return true;
        }
        if (numberFormatter.indexOf(keyCode) >= 0
                && (getNumberFormat(locale)[0] === getFormat(keyCode)
                    || getNumberFormat(locale)[1] === getFormat(keyCode))) {
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {Boolean}
     */
    isNumberKey = function(keyCode) {

        if ((keyCode >= 48 && keyCode <= 57)
                || (keyCode >= 96 && keyCode <= 105)) {        
            return true;
        }
        var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];
        if (keys.indexOf(keyCode) !== -1) {        
            return true;
        }
        return false;
    };

    /**
     * 
     * @param {type} keyCode
     * @returns {JSON@call;parse.numberFormatter.value|String}
     */
    getFormat = function(keyCode) {

        var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';
        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.numberFormatter) {
            if (jsonObject.numberFormatter.hasOwnProperty(key)
                    && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {
                return jsonObject.numberFormatter[key].value;
            }
        }
        return '';
    };

    /**
     * 
     * @type String
     */
    var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';

    /**
     * 
     * @param {type} value
     * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}
     */
    getShiftCharSpecificNumber = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return jsonObject.shiftCharacterNumberMap[key].number;
            }
        }
        return '';
    };

    /**
     * 
     * @param {type} value
     * @returns {Boolean}
     */
    isShiftSpecificChar = function(value) {

        var jsonObject = JSON.parse(jsonString);
        for (var key in jsonObject.shiftCharacterNumberMap) {
            if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
                    && value === jsonObject.shiftCharacterNumberMap[key].char) {
                return true;
            }
        }
        return false;
    };

    /**
     * 
     * @param {type} element
     * @returns {undefined}
     */
    updateField = function(element) {

        var value = element.value;

        for (var index = 0; index < value.length; index++) {
            if (!isShiftSpecificChar(value.charAt(index))) {
                continue;
            }
            element.value = value.replace(
                    value.charAt(index),
                    getShiftCharSpecificNumber(value.charAt(index)));
        }
    };

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {

        value = parseInt(parseNumber(value, params));
        if (value.toString().length > numericMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');

    /**
     * 
     * @param {type} value
     * @param {type} element
     * @param {type} params
     */
    jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {

        value = parseFloat(parseDecimal(value, params)).toFixed(2);    
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            showErrorMessage(element.id, false, null);
            setFocus(element.id);
            return false;
        }    
        return true;
    }, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isNumberExceedMaxLimit = function(id, locale) {

        var value = parseInt(parseNumber(
                document.getElementById(id).value, locale));
        if (value.toString().length > numericMaxLimit) {
            setFocus(id);
            return true;
        }    
        return false;
    };

    /**
     * @param {type} id
     * @param {type} locale
     * @returns {boolean}
     */
    isDecimalExceedsMaxLimit = function(id, locale) {

        var value = parseFloat(parseDecimal(
                document.getElementById(id).value, locale)).toFixed(2);
        if (value.toString().substring(
                0, value.toString().lastIndexOf('.')).length > numericMaxLimit
                || value.toString().length > decimalMaxLimit) {
            setFocus(id);
            return true;
        }
        return false;
    };

Send email from localhost running XAMMP in PHP using GMAIL mail server

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost

Get the index of the object inside an array, matching a condition

Why do you not want to iterate exactly ? The new Array.prototype.forEach are great for this purpose!

You can use a Binary Search Tree to find via a single method call if you want. This is a neat implementation of BTree and Red black Search tree in JS - https://github.com/vadimg/js_bintrees - but I'm not sure whether you can find the index at the same time.

How to input a regex in string.replace?

This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [DataMember]
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

How do I integrate Ajax with Django applications?

When we use Django:

Server ===> Client(Browser)   
      Send a page

When you click button and send the form,
----------------------------
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      Send a page after doing sth with these data
----------------------------

If you want to keep old data, you can do it without Ajax. (Page will be refreshed)

Server ===> Client(Browser)   
      Send a page
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      1. Send a page after doing sth with data
      2. Insert data into form and make it like before. 
      After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.

Or you can do with Ajax (Page will be not refreshed)

--------------------------
<Initialization> 
Server ===> Client(Browser) [from URL1]    
      Give a page                      
--------------------------  
<Communication>
Server <=== Client(Browser)     
      Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2] 
      Give a data struct(such as JSON)
---------------------------------

If you use Ajax, you must do these:

  1. Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
  2. Use Ajax to communicate with server using URL2. And then server send client a data struct.

Django is different from Ajax. The reason for this is as follows:

  • The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct.
  • Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.

In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.

If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.

(My English is not good)

error: use of deleted function

I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.

Date format Mapping to JSON Jackson

Building on @miklov-kriven's very helpful answer, I hope these two additional points of consideration prove helpful to someone:

(1) I find it a nice idea to include serializer and de-serializer as static inner classes in the same class. NB, using ThreadLocal for thread safety of SimpleDateFormat.

public class DateConverter {

    private static final ThreadLocal<SimpleDateFormat> sdf = 
        ThreadLocal.<SimpleDateFormat>withInitial(
                () -> {return new SimpleDateFormat("yyyy-MM-dd HH:mm a z");});

    public static class Serialize extends JsonSerializer<Date> {
        @Override
        public void serialize(Date value, JsonGenerator jgen SerializerProvider provider) throws Exception {
            if (value == null) {
                jgen.writeNull();
            }
            else {
                jgen.writeString(sdf.get().format(value));
            }
        }
    }

    public static class Deserialize extends JsonDeserializer<Date> {
        @Overrride
        public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws Exception {
            String dateAsString = jp.getText();
            try {
                if (Strings.isNullOrEmpty(dateAsString)) {
                    return null;
                }
                else {
                    return new Date(sdf.get().parse(dateAsString).getTime());
                }
            }
            catch (ParseException pe) {
                throw new RuntimeException(pe);
            }
        }
    }
}

(2) As an alternative to using @JsonSerialize and @JsonDeserialize annotations on each individual class member you could also consider overriding Jackson's default serialization by applying the custom serialization at an application level, that is all class members of type Date will be serialized by Jackson using this custom serialization without explicit annotation on each field. If you are using Spring Boot for example one way to do this would as follows:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public Module customModule() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(Date.class, new DateConverter.Serialize());
        module.addDeserializer(Date.class, new Dateconverter.Deserialize());
        return module;
    }
}

Set size on background image with CSS?

CSS2

If you need to make the image bigger, you must edit the image itself in an image editor.

If you use the img tag, you can change the size, but that would not give you the desired result if you need the image to be background for some other content (and it will not repeat itself like you seems to want)...

CSS3 unleash the powers

This is possible to do in CSS3 with background-size.

All modern browsers support this, so unless you need to support old browsers, this is the way to do it.
Supported browsers:
Mozilla Firefox 4.0+ (Gecko 2.0+), Microsoft Internet Explorer 9.0+, Opera 10.0+, Safari 4.1+ (webkit 532) and Chrome 3.0+.

.stretch{
/* Will stretch to specified width/height */
  background-size: 200px 150px;
}
.stretch-content{
/* Will stretch to width/height of element */
  background-size: 100% 100%;
}

.resize-width{
/* width: 150px, height: auto to retain aspect ratio */
  background-size: 150px Auto;
}
.resize-height{
/* height: 150px, width: auto to retain aspect ratio */
  background-size: Auto 150px;
}
.resize-fill-and-clip{ 
  /* Resize to fill and retain aspect ratio.
     Will cause clipping if aspect ratio of box is different from image. */ 
  background-size: cover;
}
.resize-best-fit{
/* Resize to best fit and retain aspect ratio.
   Will cause gap if aspect ratio of box is different from image. */ 
  background-size: contain;
}

In particular, I like the cover and contain values that gives us new power of control that we didn't have before.

Round

You can also use background-size: round that have a meaning in combination with repeat:

.resize-best-fit-in-repeat{
/* Resize to best fit in a whole number of times in x-direction */ 
  background-size: round auto; /* Height: auto is to keep aspect ratio */
  background-repeat: repeat;
}

This will adjust the image width so it fits a whole number of times in the background positioning area.


Additional note
If the size you need is static pixel size, it is still smart to physically resize the actual image. This is both to improve quality of the resize (given that your image software does a better job than the browsers), and to save bandwidth if the original image is larger than what to display.

How to submit an HTML form on loading the page?

Do this :

$(document).ready(function(){
     $("#frm1").submit();
});

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Select query to remove non-numeric characters

You can create SQL CLR scalar function in order to be able to use regular expressions like replace patterns.

Here you can find example of how to create such function.

Having such function will solve the issue with just the following lines:

SELECT [dbo].[fn_Utils_RegexReplace] ('AB ABCDE # 123', '[^0-9]', '');
SELECT [dbo].[fn_Utils_RegexReplace] ('ABCDE# 123', '[^0-9]', '');
SELECT [dbo].[fn_Utils_RegexReplace] ('AB: ABC# 123', '[^0-9]', '');

More important, you will be able to solve more complex issues as the regular expressions will bring a whole new world of options directly in your T-SQL statements.

ScrollTo function in AngularJS

I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function(event) {
        event.preventDefault();
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
        return false;
      });
    }
  }
});

How to add rows dynamically into table layout

The way you have added a row into the table layout you can add multiple TableRow instances into your tableLayout object

tl.addView(row1);
tl.addView(row2);

etc...

Where can I find the error logs of nginx, using FastCGI and Django?

It is a good practice to set where the access log should be in nginx configuring file . Using acces_log /path/ Like this.

keyval $remote_addr:$http_user_agent $seen zone=clients;

server { listen 443 ssl;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers   HIGH:!aNULL:!MD5;

if ($seen = "") {
    set $seen  1;
    set $logme 1;
}
access_log  /tmp/sslparams.log sslparams if=$logme;
error_log  /pathtolog/error.log;
# ...
}

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

The VMware Authorization Service is not running

Run as admin - vmware workstation will do.

How can I plot data with confidence intervals?

Here is part of my program related to plotting confidence interval.

1. Generate the test data

ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)

Result

enter image description here

2. Fitting the raw data using B-spline smoother method

sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
    tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
    tmp <- 1.96*sqrt(tmp)
    y_e_minus[i] <- y_e[i] - tmp
    y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')

Result

enter image description here

How can I test a PDF document if it is PDF/A compliant?

If you download the latest version of Adobe Acrobat Reader, it will tell you if your pdf is PDF/A compliant. Just open the PDF file and a big blue marking should appear.

OpenOffice supports PDF/A. For some reason "PDF/A-1" is called

"SelectPdfVersion"
internally in OpenOffice. Just add 1 to that value and your output should be PDF/A.

The different values can be

0 = PDFXNONE
1 = PDFX1A2001
2 = PDFX32002
3 = PDFA1A
4 = PDFA1B

You set

FilterData
to be a
HashMap('SelectPdfVersion',1) //1 for PDFX1A2001

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Android Recyclerview GridLayoutManager column spacing

There is a very simple and yet flexible solution for this problem using only XML which works on every LayoutManager.

Assume you want an equal spacing of X (8dp for example).

  1. Wrap your CardView item in another Layout

  2. Give the outer Layout a padding of X/2 (4dp)

  3. Make the outer Layout background transparent

...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@android:color/transparent"
    android:padding="4dip">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.CardView>

</LinearLayout>
  1. Give your RecyclerView a padding of X/2 (4dp)

...

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp" />

and thats it. You have perfect spacing of X (8dp).

Get path of executable

The boost::dll::program_location function is one of the best cross platform methods of getting the path of the running executable that I know of. The DLL library was added to Boost in version 1.61.0.

The following is my solution. I have tested it on Windows, Mac OS X, Solaris, Free BSD, and GNU/Linux.

It requires Boost 1.55.0 or greater. It uses the Boost.Filesystem library directly and the Boost.Locale library and Boost.System library indirectly.

src/executable_path.cpp

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/predef.h>
#include <boost/version.hpp>
#include <boost/tokenizer.hpp>

#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
#  include <boost/process.hpp>
#endif

#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
#  include <Windows.h>
#endif

#include <boost/executable_path.hpp>
#include <boost/detail/executable_path_internals.hpp>

namespace boost {

#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)

std::string executable_path(const char* argv0)
{
  typedef std::vector<char> char_vector;
  typedef std::vector<char>::size_type size_type;
  char_vector buf(1024, 0);
  size_type size = buf.size();
  bool havePath = false;
  bool shouldContinue = true;
  do
  {
    DWORD result = GetModuleFileNameA(nullptr, &buf[0], size);
    DWORD lastError = GetLastError();
    if (result == 0)
    {
      shouldContinue = false;
    }
    else if (result < size)
    {
      havePath = true;
      shouldContinue = false;
    }
    else if (
      result == size
      && (lastError == ERROR_INSUFFICIENT_BUFFER || lastError == ERROR_SUCCESS)
      )
    {
      size *= 2;
      buf.resize(size);
    }
    else
    {
      shouldContinue = false;
    }
  } while (shouldContinue);
  if (!havePath)
  {
    return detail::executable_path_fallback(argv0);
  }
  // On Microsoft Windows, there is no need to call boost::filesystem::canonical or
  // boost::filesystem::path::make_preferred. The path returned by GetModuleFileNameA
  // is the one we want.
  std::string ret = &buf[0];
  return ret;
}

#elif (BOOST_OS_MACOS)

#  include <mach-o/dyld.h>

std::string executable_path(const char* argv0)
{
  typedef std::vector<char> char_vector;
  char_vector buf(1024, 0);
  uint32_t size = static_cast<uint32_t>(buf.size());
  bool havePath = false;
  bool shouldContinue = true;
  do
  {
    int result = _NSGetExecutablePath(&buf[0], &size);
    if (result == -1)
    {
      buf.resize(size + 1);
      std::fill(std::begin(buf), std::end(buf), 0);
    }
    else
    {
      shouldContinue = false;
      if (buf.at(0) != 0)
      {
        havePath = true;
      }
    }
  } while (shouldContinue);
  if (!havePath)
  {
    return detail::executable_path_fallback(argv0);
  }
  std::string path(&buf[0], size);
  boost::system::error_code ec;
  boost::filesystem::path p(
    boost::filesystem::canonical(path, boost::filesystem::current_path(), ec));
  if (ec.value() == boost::system::errc::success)
  {
    return p.make_preferred().string();
  }
  return detail::executable_path_fallback(argv0);
}

#elif (BOOST_OS_SOLARIS)

#  include <stdlib.h>

std::string executable_path(const char* argv0)
{
  std::string ret = getexecname();
  if (ret.empty())
  {
    return detail::executable_path_fallback(argv0);
  }
  boost::filesystem::path p(ret);
  if (!p.has_root_directory())
  {
    boost::system::error_code ec;
    p = boost::filesystem::canonical(
      p, boost::filesystem::current_path(), ec);
    if (ec.value() != boost::system::errc::success)
    {
      return detail::executable_path_fallback(argv0);
    }
    ret = p.make_preferred().string();
  }
  return ret;
}

#elif (BOOST_OS_BSD)

#  include <sys/sysctl.h>

std::string executable_path(const char* argv0)
{
  typedef std::vector<char> char_vector;
  int mib[4]{0};
  size_t size;
  mib[0] = CTL_KERN;
  mib[1] = KERN_PROC;
  mib[2] = KERN_PROC_PATHNAME;
  mib[3] = -1;
  int result = sysctl(mib, 4, nullptr, &size, nullptr, 0);
  if (-1 == result)
  {
    return detail::executable_path_fallback(argv0);
  }
  char_vector buf(size + 1, 0);
  result = sysctl(mib, 4, &buf[0], &size, nullptr, 0);
  if (-1 == result)
  {
    return detail::executable_path_fallback(argv0);
  }
  std::string path(&buf[0], size);
  boost::system::error_code ec;
  boost::filesystem::path p(
    boost::filesystem::canonical(
      path, boost::filesystem::current_path(), ec));
  if (ec.value() == boost::system::errc::success)
  {
    return p.make_preferred().string();
  }
  return detail::executable_path_fallback(argv0);
}

#elif (BOOST_OS_LINUX)

#  include <unistd.h>

std::string executable_path(const char *argv0)
{
  typedef std::vector<char> char_vector;
  typedef std::vector<char>::size_type size_type;
  char_vector buf(1024, 0);
  size_type size = buf.size();
  bool havePath = false;
  bool shouldContinue = true;
  do
  {
    ssize_t result = readlink("/proc/self/exe", &buf[0], size);
    if (result < 0)
    {
      shouldContinue = false;
    }
    else if (static_cast<size_type>(result) < size)
    {
      havePath = true;
      shouldContinue = false;
      size = result;
    }
    else
    {
      size *= 2;
      buf.resize(size);
      std::fill(std::begin(buf), std::end(buf), 0);
    }
  } while (shouldContinue);
  if (!havePath)
  {
    return detail::executable_path_fallback(argv0);
  }
  std::string path(&buf[0], size);
  boost::system::error_code ec;
  boost::filesystem::path p(
    boost::filesystem::canonical(
      path, boost::filesystem::current_path(), ec));
  if (ec.value() == boost::system::errc::success)
  {
    return p.make_preferred().string();
  }
  return detail::executable_path_fallback(argv0);
}

#else

std::string executable_path(const char *argv0)
{
  return detail::executable_path_fallback(argv0);
}

#endif

}

src/detail/executable_path_internals.cpp

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/predef.h>
#include <boost/version.hpp>
#include <boost/tokenizer.hpp>

#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
#  include <boost/process.hpp>
#endif

#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
#  include <Windows.h>
#endif

#include <boost/executable_path.hpp>
#include <boost/detail/executable_path_internals.hpp>

namespace boost {
namespace detail {

std::string GetEnv(const std::string& varName)
{
  if (varName.empty()) return "";
#if (BOOST_OS_BSD || BOOST_OS_CYGWIN || BOOST_OS_LINUX || BOOST_OS_MACOS || BOOST_OS_SOLARIS)
  char* value = std::getenv(varName.c_str());
  if (!value) return "";
  return value;
#elif (BOOST_OS_WINDOWS)
  typedef std::vector<char> char_vector;
  typedef std::vector<char>::size_type size_type;
  char_vector value(8192, 0);
  size_type size = value.size();
  bool haveValue = false;
  bool shouldContinue = true;
  do
  {
    DWORD result = GetEnvironmentVariableA(varName.c_str(), &value[0], size);
    if (result == 0)
    {
      shouldContinue = false;
    }
    else if (result < size)
    {
      haveValue = true;
      shouldContinue = false;
    }
    else
    {
      size *= 2;
      value.resize(size);
    }
  } while (shouldContinue);
  std::string ret;
  if (haveValue)
  {
    ret = &value[0];
  }
  return ret;
#else
  return "";
#endif
}

bool GetDirectoryListFromDelimitedString(
  const std::string& str,
  std::vector<std::string>& dirs)
{
  typedef boost::char_separator<char> char_separator_type;
  typedef boost::tokenizer<
    boost::char_separator<char>, std::string::const_iterator,
    std::string> tokenizer_type;
  dirs.clear();
  if (str.empty())
  {
    return false;
  }
#if (BOOST_OS_WINDOWS)
  const std::string os_pathsep(";");
#else
  const std::string os_pathsep(":");
#endif
  char_separator_type pathSep(os_pathsep.c_str());
  tokenizer_type strTok(str, pathSep);
  typename tokenizer_type::iterator strIt;
  typename tokenizer_type::iterator strEndIt = strTok.end();
  for (strIt = strTok.begin(); strIt != strEndIt; ++strIt)
  {
    dirs.push_back(*strIt);
  }
  if (dirs.empty())
  {
    return false;
  }
  return true;
}

std::string search_path(const std::string& file)
{
  if (file.empty()) return "";
  std::string ret;
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
  {
    namespace bp = boost::process;
    boost::filesystem::path p = bp::search_path(file);
    ret = p.make_preferred().string();
  }
#endif
  if (!ret.empty()) return ret;
  // Drat! I have to do it the hard way.
  std::string pathEnvVar = GetEnv("PATH");
  if (pathEnvVar.empty()) return "";
  std::vector<std::string> pathDirs;
  bool getDirList = GetDirectoryListFromDelimitedString(pathEnvVar, pathDirs);
  if (!getDirList) return "";
  std::vector<std::string>::const_iterator it = pathDirs.cbegin();
  std::vector<std::string>::const_iterator itEnd = pathDirs.cend();
  for ( ; it != itEnd; ++it)
  {
    boost::filesystem::path p(*it);
    p /= file;
    if (boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p))
    {
      return p.make_preferred().string();
    }
  }
  return "";
}

std::string executable_path_fallback(const char *argv0)
{
  if (argv0 == nullptr) return "";
  if (argv0[0] == 0) return "";
#if (BOOST_OS_WINDOWS)
  const std::string os_sep("\\");
#else
  const std::string os_sep("/");
#endif
  if (strstr(argv0, os_sep.c_str()) != nullptr)
  {
    boost::system::error_code ec;
    boost::filesystem::path p(
      boost::filesystem::canonical(
        argv0, boost::filesystem::current_path(), ec));
    if (ec.value() == boost::system::errc::success)
    {
      return p.make_preferred().string();
    }
  }
  std::string ret = search_path(argv0);
  if (!ret.empty())
  {
    return ret;
  }
  boost::system::error_code ec;
  boost::filesystem::path p(
    boost::filesystem::canonical(
      argv0, boost::filesystem::current_path(), ec));
  if (ec.value() == boost::system::errc::success)
  {
    ret = p.make_preferred().string();
  }
  return ret;
}

}
}

include/boost/executable_path.hpp

#ifndef BOOST_EXECUTABLE_PATH_HPP_
#define BOOST_EXECUTABLE_PATH_HPP_

#pragma once

#include <string>

namespace boost {
std::string executable_path(const char * argv0);
}

#endif // BOOST_EXECUTABLE_PATH_HPP_

include/boost/detail/executable_path_internals.hpp

#ifndef BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
#define BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_

#pragma once

#include <string>
#include <vector>

namespace boost {
namespace detail {
std::string GetEnv(const std::string& varName);
bool GetDirectoryListFromDelimitedString(
    const std::string& str,
    std::vector<std::string>& dirs);
std::string search_path(const std::string& file);
std::string executable_path_fallback(const char * argv0);
}
}

#endif // BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_

I have a complete project, including a test application and CMake build files available at SnKOpen - /cpp/executable_path/trunk. This version is more complete than the version I provided here. It is also supports more platforms.

I have tested the application on all supported operating systems in the following four scenarios.

  1. Relative path, executable in current directory: i.e. ./executable_path_test
  2. Relative path, executable in another directory: i.e. ./build/executable_path_test
  3. Full path: i.e. /some/dir/executable_path_test
  4. Executable in path, file name only: i.e. executable_path_test

In all four scenarios, both the executable_path and executable_path_fallback functions work and return the same results.

Notes

This is an updated answer to this question. I updated the answer to take into consideration user comments and suggestions. I also added a link to a project in my SVN Repository.

Capture iOS Simulator video for App Preview

Unfortunately, the iOS Simulator app does not support saving videos. The easiest thing to do is use Quicktime Player to make a screen recording. Of course, you'll see the mouse interacting with it which is not what you want, but I don't have a better option for you at this time.

Why is datetime.strptime not working in this simple example?

You should use strftime static method from datetime class from datetime module. Try:

import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")

Blade if(isset) is not working Laravel

Use 3 curly braces if you want to echo

{{{ $usersType or '' }}}

Email Address Validation in Android on EditText

Use this method to validate the EMAIL :-

 public static boolean isEditTextContainEmail(EditText argEditText) {

            try {
                Pattern pattern = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
                Matcher matcher = pattern.matcher(argEditText.getText());
                return matcher.matches();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

Let me know if you have any queries ?

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

How to enable cURL in PHP / XAMPP

to install php5-curl under opensuse:

sudo yast2

->software ->software management ->search for curl ->check php5-curl case and accept.

after installation you need to restart apache server

service apache2 restart

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

This should fix the error

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.7</version>
     <dependencies>
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-filtering</artifactId>
             <version>1.3</version>
          </dependency>
      </dependencies>
</plugin>

Can anyone explain IEnumerable and IEnumerator to me?

for example, when to use it over foreach?

You don't use IEnumerable "over" foreach. Implementing IEnumerable makes using foreach possible.

When you write code like:

foreach (Foo bar in baz)
{
   ...
}

it's functionally equivalent to writing:

IEnumerator bat = baz.GetEnumerator();
while (bat.MoveNext())
{
   bar = (Foo)bat.Current
   ...
}

By "functionally equivalent," I mean that's actually what the compiler turns the code into. You can't use foreach on baz in this example unless baz implements IEnumerable.

IEnumerable means that baz implements the method

IEnumerator GetEnumerator()

The IEnumerator object that this method returns must implement the methods

bool MoveNext()

and

Object Current()

The first method advances to the next object in the IEnumerable object that created the enumerator, returning false if it's done, and the second returns the current object.

Anything in .Net that you can iterate over implements IEnumerable. If you're building your own class, and it doesn't already inherit from a class that implements IEnumerable, you can make your class usable in foreach statements by implementing IEnumerable (and by creating an enumerator class that its new GetEnumerator method will return).

Generating HTML email body in C#

Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.

Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

Replace text in HTML page with jQuery

The html replace idea is good, but if done to the document.body, the page will blink and ads will disappear.

My solution:
$("*:contains('purrfect')").each(function() { var replaced = $(this).html().replace(/purrfect/g, "purrfect"); $(this).html(replaced); });

How to get current date time in milliseconds in android

try this

  Calendar c = Calendar.getInstance(); 
  int mseconds = c.get(Calendar.MILLISECOND)

an alternative would be

 Calendar rightNow = Calendar.getInstance();

 long offset = rightNow.get(Calendar.ZONE_OFFSET) +
        rightNow.get(Calendar.DST_OFFSET);
 long sinceMid = (rightNow.getTimeInMils() + offset) %
       (24 * 60 * 60 * 1000);

  System.out.println(sinceMid + " milliseconds since midnight");

How to refresh Android listview?

The easiest is to just make a new Adaper and drop the old one:

myListView.setAdapter(new MyListAdapter(...));

How do I increase modal width in Angular UI Bootstrap?

I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.

CSS

@media(min-width: 1400px){
    .my-modal > .modal-lg {
        width: 1308px;
    }
}

JS is the same:

var modal = $modal.open({
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal'
});

How to create file execute mode permissions in Git on Windows?

Indeed, it would be nice if git-add had a --mode flag

git 2.9.x/2.10 (Q3 2016) actually will allow that (thanks to Edward Thomson):

git add --chmod=+x -- afile
git commit -m"Executable!"

That makes the all process quicker, and works even if core.filemode is set to false.

See commit 4e55ed3 (31 May 2016) by Edward Thomson (ethomson).
Helped-by: Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit c8b080a, 06 Jul 2016)

add: add --chmod=+x / --chmod=-x options

The executable bit will not be detected (and therefore will not be set) for paths in a repository with core.filemode set to false, though the users may still wish to add files as executable for compatibility with other users who do have core.filemode functionality.
For example, Windows users adding shell scripts may wish to add them as executable for compatibility with users on non-Windows.

Although this can be done with a plumbing command (git update-index --add --chmod=+x foo), teaching the git-add command allows users to set a file executable with a command that they're already familiar with.

Full-screen iframe with a height of 100%

As per https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe, percentage values are no longer allowed. But the following worked for me

<iframe width="100%" height="this.height=window.innerHeight;" style="border:none" src=""></iframe>

Though width:100% works, height:100% does not work. So window.innerHeight has been used. You can also use css pixels for height.

Working code: Link Working site: Link

Automatic login script for a website on windows machine?

You can use Autohotkey, download it from: http://ahkscript.org/download/

After the installation, if you want to open Gmail website when you press Alt+g, you can do something like this:

!g::
Run www.gmail.com 
return

Further reference: Hotkeys (Mouse, Joystick and Keyboard Shortcuts)

Get content of a DIV using JavaScript

simply you can use jquery plugin to get/set the content of the div.

var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );

for this you need to include jquery library.

Is there an onSelect event or equivalent for HTML <select>?

A long while ago now but in reply to the original question, would this help ? Just put onClick into the SELECT line. Then put what you want each OPTION to do in the OPTION lines. ie:

<SELECT name="your name" onClick>
<option value ="Kilometres" onClick="YourFunction()">Kilometres
-------
-------
</SELECT>

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

IIS Express Windows Authentication

In addition to these great answers, in the context of an IISExpress dev environment, and in order to thwart the infamous "system.web/identity@impersonate" error, you can simply ensure the following setting is in place in your applicationhost.config file.

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
    </system.webServer>
</configuration>

This will allow you more flexibility during development and testing, though be sure you understand the implications of using this setting in a production environment before doing so.

Helpful Posts:

VBA test if cell is in a range

If the two ranges to be tested (your given cell and your given range) are not in the same Worksheet, then Application.Intersect throws an error. Thus, a way to avoid it is with something like

Sub test_inters(rng1 As Range, rng2 As Range)
    If (rng1.Parent.Name = rng2.Parent.Name) Then
        Dim ints As Range
        Set ints = Application.Intersect(rng1, rng2)
        If (Not (ints Is Nothing)) Then
            ' Do your job
        End If
    End If
End Sub

What version of Python is on my Mac?

You could have multiple Python versions on your macOS.

You may check that by command, type or which command, like:

which -a python python2 python2.7 python3 python3.6

Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

compgen -c python

By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

For instance, if you've installed different version via Homebrew, try the following command:

brew list python python3

or:

brew list | grep ^python

it'll show you all Python files installed with the package.

Alternatively you may use apropos or locate python command to locate more Python related files.

To check any environment variables related to Python, run:

env | grep ^PYTHON

To address your issues:

  • Error: No such keg: /usr/local/Cellar/python

    Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

  • The locate database (/var/db/locate.database) does not exist.

    Follow the advice and run:

    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
    

    After the database is rebuild, you can use locate command.

Best way to check for nullable bool in a condition expression (if ...)

How about using GetValueOrDefault, which is pretty self-explaining and allows to use whatever default you want:

if (nullableBool.GetValueOrDefault(false)) {
}

How to solve error message: "Failed to map the path '/'."

You don't have to reset IIS, you can just recycle the app pool.

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Angular ng-repeat add bootstrap row every 3 or 4 cols

I did it only using boostrap, you must be very careful in the location of the row and the column, here is my example.

_x000D_
_x000D_
<section>_x000D_
<div class="container">_x000D_
        <div ng-app="myApp">_x000D_
        _x000D_
                <div ng-controller="SubregionController">_x000D_
                    <div class="row text-center">_x000D_
                        <div class="col-md-4" ng-repeat="post in posts">_x000D_
                            <div >_x000D_
                                <div>{{post.title}}</div>_x000D_
                            </div>_x000D_
                        </div>_x000D_
                    _x000D_
                    </div>_x000D_
                </div>        _x000D_
        </div>_x000D_
    </div>_x000D_
</div> _x000D_
_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to downgrade the installed version of 'pip' on windows?

If downgrading from pip version 10 because of PyCharm manage.py or other python errors:

python -m pip install pip==9.0.1

How to get a certain element in a list, given the position?

std::list doesn't provide any function to get element given an index. You may try to get it by writing some code, which I wouldn't recommend, because that would be inefficient if you frequently need to do so.

What you need is : std::vector. Use it as:

std::vector<Object> objects;
objects.push_back(myObject);

Object const & x = objects[0];    //index isn't checked
Object const & y = objects.at(0); //index is checked 

How to run cron job every 2 hours

0 */2 * * *

The answer is from https://crontab.guru/every-2-hours. It is interesting.

How to remove newlines from beginning and end of a string?

Try this

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}

SQL ROWNUM how to return rows between a specific range

I know this is an old question, however, it is useful to mention the new features in the latest version.

From Oracle 12c onwards, you could use the new Top-n Row limiting feature. No need to write a subquery, no dependency on ROWNUM.

For example, the below query would return the employees between 4th highest till 7th highest salaries in ascending order:

SQL> SELECT empno, sal
  2  FROM   emp
  3  ORDER BY sal
  4  OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;

     EMPNO        SAL
---------- ----------
      7654       1250
      7934       1300
      7844       1500
      7499       1600

SQL>

Make footer stick to bottom of page using Twitter Bootstrap

Use the bootstrap classes to your advantage. navbar-static-bottom leaves it at the bottom.

<div class="navbar-static-bottom" id="footer"></div>

Rename Pandas DataFrame Index

The rename method takes a dictionary for the index which applies to index values.
You want to rename to index level's name:

df.index.names = ['Date']

A good way to think about this is that columns and index are the same type of object (Index or MultiIndex), and you can interchange the two via transpose.

This is a little bit confusing since the index names have a similar meaning to columns, so here are some more examples:

In [1]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))

In [2]: df
Out[2]: 
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df1 = df.set_index('A')

In [4]: df1
Out[4]: 
   B  C
A      
1  2  3
4  5  6

You can see the rename on the index, which can change the value 1:

In [5]: df1.rename(index={1: 'a'})
Out[5]: 
   B  C
A      
a  2  3
4  5  6

In [6]: df1.rename(columns={'B': 'BB'})
Out[6]: 
   BB  C
A       
1   2  3
4   5  6

Whilst renaming the level names:

In [7]: df1.index.names = ['index']
        df1.columns.names = ['column']

Note: this attribute is just a list, and you could do the renaming as a list comprehension/map.

In [8]: df1
Out[8]: 
column  B  C
index       
1       2  3
4       5  6

how to clear JTable

This is the fastest and easiest way that I have found;

while (tableModel.getRowCount()>0)
          {
             tableModel.removeRow(0);
          }

This clears the table lickety split and leaves it ready for new data.

How to compile a 64-bit application using Visual C++ 2010 Express?

Here are step by step instructions:

  1. Download and install the Windows Software Development Kit version 7.1. Visual C++ 2010 Express does not include a 64 bit compiler, but the SDK does. A link to the SDK: http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx
  2. Change your project configuration. Go to Properties of your project. On the top of the dialog box there will be a "Configuration" drop-down menu. Make sure that selects "All Configurations." There will also be a "Platform" drop-down that will read "Win32." Finally on the right there is a "Configuration Manager" button - press it. In the dialog that comes up, find your project, hit the Platform drop-down, select New, then select x64. Now change the "Active solution platform" drop-down menu to "x64." When you return to the Properties dialog box, the "Platform" drop-down should now read "x64."
  3. Finally, change your toolset. In the Properties menu of your project, under Configuration Properties | General, change Platform Toolset from "v100" to "Windows7.1SDK".

These steps have worked for me, anyway. Some more details on step 2 can be found in a reference from Microsoft that a previous poster mentioned: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx.

How do I split a string into an array of characters?

It's as simple as:

s.split("");

The delimiter is an empty string, hence it will break up between each single character.

In AVD emulator how to see sdcard folder? and Install apk to AVD?

//in linux

// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file.

//To install apk in linux

$adb install ./yourfolder/myapkfile.apk

Java logical operator short-circuiting

Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.

Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.

Is it necessary to write HEAD, BODY and HTML tags?

It's valid to omit them in HTML4:

7.3 The HTML element
start tag: optional, End tag: optional

7.4.1 The HEAD element
start tag: optional, End tag: optional

http://www.w3.org/TR/html401/struct/global.html

In HTML5, there are no "required" or "optional" elements exactly, as HTML5 syntax is more loosely defined. For example, title:

The title element is a required child in most situations, but when a higher-level protocol provides title information, e.g. in the Subject line of an e-mail when HTML is used as an e-mail authoring format, the title element can be omitted.

http://www.w3.org/TR/html5/semantics.html#the-title-element-0

It's not valid to omit them in true XHTML5, though that is almost never used (versus XHTML-acting-like-HTML5).

However, from a practical standpoint you often want browsers to run in "standards mode," for predictability in rendering HTML and CSS. Providing a DOCTYPE and a more structured HTML tree will guarantee more predictable cross-browser results.

How to convert a 3D point into 2D perspective projection?

I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:

  1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be isotropic; scaling and shearing makes the normals malformed.
  2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the perspective divide.
  3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. Sutherland-Hodgeman clipping is the most widespread clipping algorithm in use.
  4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.

This stage is the actual projection, because z isn't used as a component in the position any more.

The algorithms:

Calculation of field-of-view

This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.

fov = 1.0 / tan(angle/2.0)

Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.

Calculation of the clip matrix

This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][        1       ]
[        0        ][        0        ][(2*near*far)/(near-far)][        0       ]

Screen Projection

After clipping, this is the final transformation to get our screen coordinates.

new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;

Trivial example implementation in C++

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

struct Vector
{
    Vector() : x(0),y(0),z(0),w(1){}
    Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt(x*x + y*y + z*z);
    }
    
    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if(mag < epsilon){
            std::out_of_range e("");
            throw e;
        }
        return *this / mag;
    }
};

inline float Dot(const Vector& v1, const Vector& v2)
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
    public:
    Matrix() : data(16)
    {
        Identity();
    }
    void Identity()
    {
        std::fill(data.begin(), data.end(), float(0));
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[](size_t index)
    {
        if(index >= 16){
            std::out_of_range e("");
            throw e;
        }
        return data[index];
    }
    Matrix operator*(const Matrix& m) const
    {
        Matrix dst;
        int col;
        for(int y=0; y<4; ++y){
            col = y*4;
            for(int x=0; x<4; ++x){
                for(int i=0; i<4; ++i){
                    dst[x+col] += m[i+col]*data[x+i*4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=(const Matrix& m)
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
    {
        Identity();
        float f = 1.0f / std::tan(fov * 0.5f);
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (far+near) / (far-near);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*near*far) / (near-far);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};

inline Vector operator*(const Vector& v, const Matrix& m)
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping 
        by checking if the x, y and z components are inside the range of [-w, w].
        One checks each vector component seperately against each plane. Per-vertex
        data like colours, normals and texture coordinates need to be linearly
        interpolated for clipped edges to reflect the change. If the edge (v0,v1)
        is tested against the positive x plane, and v1 is outside, the interpolant
        becomes: (v1.x - w) / (v1.x - v0.x)
        I skip this stage all together to be brief.
    */
    for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back(v);
    }

    /* TODO: Clipping here */

    for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}

If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.

How to POST JSON Data With PHP cURL?

$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );

$postdata = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

This code worked for me. You can try...

Convert SVG to image (JPEG, PNG, etc.) in the browser

This seems to work in most browsers:

function copyStylesInline(destinationNode, sourceNode) {
   var containerElements = ["svg","g"];
   for (var cd = 0; cd < destinationNode.childNodes.length; cd++) {
       var child = destinationNode.childNodes[cd];
       if (containerElements.indexOf(child.tagName) != -1) {
            copyStylesInline(child, sourceNode.childNodes[cd]);
            continue;
       }
       var style = sourceNode.childNodes[cd].currentStyle || window.getComputedStyle(sourceNode.childNodes[cd]);
       if (style == "undefined" || style == null) continue;
       for (var st = 0; st < style.length; st++){
            child.style.setProperty(style[st], style.getPropertyValue(style[st]));
       }
   }
}

function triggerDownload (imgURI, fileName) {
  var evt = new MouseEvent("click", {
    view: window,
    bubbles: false,
    cancelable: true
  });
  var a = document.createElement("a");
  a.setAttribute("download", fileName);
  a.setAttribute("href", imgURI);
  a.setAttribute("target", '_blank');
  a.dispatchEvent(evt);
}

function downloadSvg(svg, fileName) {
  var copy = svg.cloneNode(true);
  copyStylesInline(copy, svg);
  var canvas = document.createElement("canvas");
  var bbox = svg.getBBox();
  canvas.width = bbox.width;
  canvas.height = bbox.height;
  var ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, bbox.width, bbox.height);
  var data = (new XMLSerializer()).serializeToString(copy);
  var DOMURL = window.URL || window.webkitURL || window;
  var img = new Image();
  var svgBlob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
  var url = DOMURL.createObjectURL(svgBlob);
  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
    if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob)
    {
        var blob = canvas.msToBlob();         
        navigator.msSaveOrOpenBlob(blob, fileName);
    } 
    else {
        var imgURI = canvas
            .toDataURL("image/png")
            .replace("image/png", "image/octet-stream");
        triggerDownload(imgURI, fileName);
    }
    document.removeChild(canvas);
  };
  img.src = url;
}

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

How to build a query string for a URL in C#?

With the inspiration from Roy Tinker's comment, I ended up using a simple extension method on the Uri class that keeps my code concise and clean:

using System.Web;

public static class HttpExtensions
{
    public static Uri AddQuery(this Uri uri, string name, string value)
    {
        var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);

        httpValueCollection.Remove(name);
        httpValueCollection.Add(name, value);

        var ub = new UriBuilder(uri);
        ub.Query = httpValueCollection.ToString();

        return ub.Uri;
    }
}

Usage:

Uri url = new Uri("http://localhost/rest/something/browse").
          AddQuery("page", "0").
          AddQuery("pageSize", "200");

Edit - Standards compliant variant

As several people pointed out, httpValueCollection.ToString() encodes Unicode characters in a non-standards-compliant way. This is a variant of the same extension method that handles such characters by invoking HttpUtility.UrlEncode method instead of the deprecated HttpUtility.UrlEncodeUnicode method.

using System.Web;

public static Uri AddQuery(this Uri uri, string name, string value)
{
    var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);

    httpValueCollection.Remove(name);
    httpValueCollection.Add(name, value);

    var ub = new UriBuilder(uri);

    // this code block is taken from httpValueCollection.ToString() method
    // and modified so it encodes strings with HttpUtility.UrlEncode
    if (httpValueCollection.Count == 0)
        ub.Query = String.Empty;
    else
    {
        var sb = new StringBuilder();

        for (int i = 0; i < httpValueCollection.Count; i++)
        {
            string text = httpValueCollection.GetKey(i);
            {
                text = HttpUtility.UrlEncode(text);

                string val = (text != null) ? (text + "=") : string.Empty;
                string[] vals = httpValueCollection.GetValues(i);

                if (sb.Length > 0)
                    sb.Append('&');

                if (vals == null || vals.Length == 0)
                    sb.Append(val);
                else
                {
                    if (vals.Length == 1)
                    {
                        sb.Append(val);
                        sb.Append(HttpUtility.UrlEncode(vals[0]));
                    }
                    else
                    {
                        for (int j = 0; j < vals.Length; j++)
                        {
                            if (j > 0)
                                sb.Append('&');

                            sb.Append(val);
                            sb.Append(HttpUtility.UrlEncode(vals[j]));
                        }
                    }
                }
            }
        }

        ub.Query = sb.ToString();
    }

    return ub.Uri;
}

Is it fine to have foreign key as primary key?

Yes, it is legal to have a primary key being a foreign key. This is a rare construct, but it applies for:

  • a 1:1 relation. The two tables cannot be merged in one because of different permissions and privileges only apply at table level (as of 2017, such a database would be odd).

  • a 1:0..1 relation. Profile may or may not exist, depending on the user type.

  • performance is an issue, and the design acts as a partition: the profile table is rarely accessed, hosted on a separate disk or has a different sharding policy as compared to the users table. Would not make sense if the underlining storage is columnar.

Sequence contains no elements?

From "Fixing LINQ Error: Sequence contains no elements":

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

This can also be caused by the following commands:

  • FirstAsync()
  • SingleAsync()
  • Last()
  • LastAsync()
  • Max()
  • Min()
  • Average()
  • Aggregate()

Close Form Button Event

This should handle cases of clicking on [x] or ALT+F4

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   if (e.CloseReason == CloseReason.UserClosing)
   {
      DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
      if (result == DialogResult.Yes)
      {
          Environment.Exit(0);
      }
      else 
      {
         e.Cancel = true;
      }
   }
   else
   {
      e.Cancel = true;
   }
}   

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

C# int to enum conversion

Casting should be enough. If you're using C# 3.0 you can make a handy extension method to parse enum values:

public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
    Type type = typeof(TEnum);

    if (value == default(TInput))
    {
        throw new ArgumentException("Value is null or empty.", "value");
    }

    if (!type.IsEnum)
    {
        throw new ArgumentException("Enum expected.", "TEnum");
    }

    return (TEnum)Enum.Parse(type, value.ToString(), true);
}

Matplotlib - How to plot a high resolution graph?

At the end of your for() loop, you can use the savefig() function instead of plt.show() and set the name, dpi and format of your figure.

E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder ./ with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:

for fname in glob("./*.txt"):
    # Your previous code goes here
    [...]

    plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)

Why doesn't Java allow overriding of static methods?

Overriding in Java simply means that the particular method would be called based on the runtime type of the object and not on the compile-time type of it (which is the case with overridden static methods). As static methods are class methods they are not instance methods so they have nothing to do with the fact which reference is pointing to which Object or instance, because due to the nature of static method it belongs to a specific class. You can redeclare it in the subclass but that subclass won't know anything about the parent class' static methods because, as I said, it is specific to only that class in which it has been declared. Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it more details and example http://faisalbhagat.blogspot.com/2014/09/method-overriding-and-method-hiding.html

Closing Excel Application using VBA

Sub button2_click()
'
' Button2_Click Macro
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
    ActiveSheet.Shapes("Button 2").Select
    Selection.Characters.Text = "Logout"
    ActiveSheet.Shapes("Button 2").Select
    Selection.OnAction = "Button2_Click"
    ActiveWorkbook.Saved = True
    ActiveWorkbook.Save
    Application.Quit
End Sub

Connect with SSH through a proxy

This is how I solved it, hoping to help others later.

My system is debian 10, and minimal installation.

I also have the same problem like this.

git clone [email protected]:nothing/nothing.git
Cloning into 'nothing'...
nc: invalid option -- 'x'
nc -h for help
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Or

git clone [email protected]:nothing/nothing.git
Cloning into 'nothing'...
/usr/bin/nc: invalid option -- 'X'
nc -h for help
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So, I know the nc has different versions like openbsd-netcat and GNU-netcat, you can change the nc in debian to the openbsd version, but I choose to change the software like corkscrew, because the names of the two versions of nc in system are same, and many people don’t understand it well. My approach is as follows.

sudo apt install corkscrew

Then.

vim ~/.ssh/config

Change this file like this.

Host github.com
    User git
    ProxyCommand corkscrew 192.168.1.22 8118 %h %p

192.168.1.22 and 8118 is my proxy server's address and port, you should change it according to your server address.

It's work fine.

Thanks @han.

How to allow only a number (digits and decimal point) to be typed in an input?

You could try this directive to stop any invalid characters from being entered into an input field. (Update: this relies on the directive having explicit knowledge of the model, which is not ideal for reusability, see below for a re-usable example)

app.directive('isNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope) {    
            scope.$watch('wks.number', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.wks.number = oldValue;
                }
            });
        }
    };
});

It also accounts for these scenarios:

  1. Going from a non-empty valid string to an empty string
  2. Negative values
  3. Negative decimal values

I have created a jsFiddle here so you can see how it works.

UPDATE

Following Adam Thomas' feedback regarding not including model references directly inside a directive (which I also believe is the best approach) I have updated my jsFiddle to provide a method which does not rely on this.

The directive makes use of bi-directional binding of local scope to parent scope. The changes made to variables inside the directive will be reflected in the parent scope, and vice versa.

HTML:

<form ng-app="myapp" name="myform" novalidate> 
    <div ng-controller="Ctrl">
        <number-only-input input-value="wks.number" input-name="wks.name"/>
    </div>
</form>

Angular code:

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

app.controller('Ctrl', function($scope) {
    $scope.wks =  {number: 1, name: 'testing'};
});
app.directive('numberOnlyInput', function () {
    return {
        restrict: 'EA',
        template: '<input name="{{inputName}}" ng-model="inputValue" />',
        scope: {
            inputValue: '=',
            inputName: '='
        },
        link: function (scope) {
            scope.$watch('inputValue', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.inputValue = oldValue;
                }
            });
        }
    };
});

How do I override nested NPM dependency versions?

NPM shrinkwrap offers a nice solution to this problem. It allows us to override that version of a particular dependency of a particular sub-module.

Essentially, when you run npm install, npm will first look in your root directory to see whether a npm-shrinkwrap.json file exists. If it does, it will use this first to determine package dependencies, and then falling back to the normal process of working through the package.json files.

To create an npm-shrinkwrap.json, all you need to do is

 npm shrinkwrap --dev

code:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

Converting Integer to Long

If the Integer is not null

Integer i;
Long long = Long.valueOf(i);

i will be automatically typecast to a long.

Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

I solved this issue to update .htaccess file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess in my case).

Just update or add this php_value max_execution_time 300 line before # END WordPress. Then save the file and try to install again.

If the error occurs again, you can maximize the value from 300 to 600.

MongoDB via Mongoose JS - What is findByID?

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

min and max value of data type in C

The header file limits.h defines macros that expand to various limits and parameters of the standard integer types.

How to create the most compact mapping n ? isprime(n) up to a limit N?

Python 3:

def is_prime(a):
    return a > 1 and all(a % i for i in range(2, int(a**0.5) + 1))

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Try change _DEBUG to NDEBUG macro definition in C++ project properties (for Release configuration) Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions

What does "TypeError 'xxx' object is not callable" means?

I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:

class DOH(object):
def __init__(self, property=None):
    self.property=property

def property():
    return property

x = DOH(1)
print(x.property())

Results

$ python3 t.py
Traceback (most recent call last):
  File "t.py", line 9, in <module>
    print(x.property())
TypeError: 'int' object is not callable

The problem here of course is that the function is overwritten with a property.

How do you create a Distinct query in HQL

My main query looked like this in the model:

@NamedQuery(name = "getAllCentralFinancialAgencyAccountCd", 
    query = "select distinct i from CentralFinancialAgencyAccountCd i")

And I was still not getting what I considered "distinct" results. They were just distinct based on a primary key combination on the table.

So in the DaoImpl I added an one line change and ended up getting the "distinct" return I wanted. An example would be instead of seeing 00 four times I now just see it once. Here is the code I added to the DaoImpl:

@SuppressWarnings("unchecked")
public List<CacheModelBase> getAllCodes() {

    Session session = (Session) entityManager.getDelegate();
    org.hibernate.Query q = session.getNamedQuery("getAllCentralFinancialAgencyAccountCd");
    q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // This is the one line I had to add to make it do a more distinct query.
    List<CacheModelBase> codes;
    codes = q.list();
    return codes;       
}

I hope this helped! Once again, this might only work if you are following coding practices that implement the service, dao, and model type of project.

jQuery UI Dialog - missing close icon

I found three fixes:

  1. You can just load bootsrap first. And them load jquery-ui. But it is not good idea. Because you will see errors in console.
  2. This:

    var bootstrapButton = $.fn.button.noConflict();
    $.fn.bootstrapBtn = bootstrapButton;
    

    helps. But other buttons look terrible. And now we don't have bootstrap buttons.

  3. I just want to use bootsrap styles and also I want to have close button with an icon. I've done following:

    How close button looks after fix

    .ui-dialog-titlebar-close {
        padding:0 !important;
    }
    
    .ui-dialog-titlebar-close:after {
        content: '';
        width: 20px;
        height: 20px;
        display: inline-block;
        /* Change path to image*/
        background-image: url(themes/base/images/ui-icons_777777_256x240.png);
        background-position: -96px -128px;
        background-repeat: no-repeat;
    }
    

Flask at first run: Do not use the development server in a production environment

The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.

When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.

Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:

$ pip install waitress

You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.

$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080

Or you can use waitress.serve() in the code instead of using the CLI command.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello!</h1>"

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
$ python hello.py

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

Finding the number of days between two dates

You can try the code below:

$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));

HTML checkbox onclick called in Javascript

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All
</label>

Why is a primary-foreign key relation required when we can join without it?

A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.

To do this you use an outer join:

select tablea.code, tablea.name, tableb.location from tablea left outer join 
tableb on tablea.code = tableb.code

join with out relation

SQL join

Run PHP function on html button click

It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.

jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

What is the difference between a "function" and a "procedure"?

In the context of db: Stored procedure is precompiled execution plan where as functions are not.

Range of values in C Int and Long 32 - 64 bits

Excerpt from K&R:

short is often 16 bits, long 32 bits and int either 16 bits or 32 bits. Each compiler is free to choose appropriate sizes for its own hardware, subject only to the restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer than int, which is no longer than long.


You can make use of limits.h that contains the definition of the limits for the decimal/float types:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>


int main(int argc, char** argv) {

    printf("CHAR_BIT    :   %d\n", CHAR_BIT);
    printf("CHAR_MAX    :   %d\n", CHAR_MAX);
    printf("CHAR_MIN    :   %d\n", CHAR_MIN);
    printf("INT_MAX     :   %d\n", INT_MAX);
    printf("INT_MIN     :   %d\n", INT_MIN);
    printf("LONG_MAX    :   %ld\n", (long) LONG_MAX);
    printf("LONG_MIN    :   %ld\n", (long) LONG_MIN);
    printf("SCHAR_MAX   :   %d\n", SCHAR_MAX);
    printf("SCHAR_MIN   :   %d\n", SCHAR_MIN);
    printf("SHRT_MAX    :   %d\n", SHRT_MAX);
    printf("SHRT_MIN    :   %d\n", SHRT_MIN);
    printf("UCHAR_MAX   :   %d\n", UCHAR_MAX);
    printf("UINT_MAX    :   %u\n", (unsigned int) UINT_MAX);
    printf("ULONG_MAX   :   %lu\n", (unsigned long) ULONG_MAX);
    printf("USHRT_MAX   :   %d\n", (unsigned short) USHRT_MAX);
    printf("FLT_MAX     :   %g\n", (float) FLT_MAX);
    printf("FLT_MIN     :   %g\n", (float) FLT_MIN);
    printf("-FLT_MAX    :   %g\n", (float) -FLT_MAX);
    printf("-FLT_MIN    :   %g\n", (float) -FLT_MIN);
    printf("DBL_MAX     :   %g\n", (double) DBL_MAX);
    printf("DBL_MIN     :   %g\n", (double) DBL_MIN);
    printf("-DBL_MAX     :  %g\n", (double) -DBL_MAX);

    return (EXIT_SUCCESS);
}

Maybe you might have to tweak a little bit on your machine, but it is a good template to start to get an idea of the (implementation-defined) min and max values.

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

SQL Server: converting UniqueIdentifier to string in a case statement

It is possible to use the convert function here, but 36 characters are enough to hold the unique identifier value:

convert(nvarchar(36), requestID) as requestID

How to do an array of hashmaps?

You can't have an array of a generic type. Use List instead.

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

SQL Order By Count

Below gives me opposite of what you have. (Notice Group column)

SELECT
    *
FROM
    myTable
GROUP BY
    Group_value,
    ID
ORDER BY
    count(Group_value)

Let me know if this is fine with you...

I am trying to get what you want too...

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag

Example:

<video controls="controls" width="800" height="600" 
       name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

How do I find the size of a struct?

#include <stdio.h>

typedef struct { char* c; char b; } a;

int main()
{
    printf("sizeof(a) == %d", sizeof(a));
}

I get "sizeof(a) == 8", on a 32-bit machine. The total size of the structure will depend on the packing: In my case, the default packing is 4, so 'c' takes 4 bytes, 'b' takes one byte, leaving 3 padding bytes to bring it to the next multiple of 4: 8. If you want to alter this packing, most compilers have a way to alter it, for example, on MSVC:

#pragma pack(1)
typedef struct { char* c; char b; } a;

gives sizeof(a) == 5. If you do this, be careful to reset the packing before any library headers!

Convert command line argument to string

Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:

std::string dump_name;

(stuff..)

if(argc>2)
{
    dump_name.assign(argv[2]);
    fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
}

Note the use of assign, and also the need for the c_str() function call.

Reading a huge .csv file

Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time.

import pandas as pd
chunksize = 10 ** 8
for chunk in pd.read_csv(filename, chunksize=chunksize):
    process(chunk)

Listing only directories in UNIX

use this to get a list of directory

ls -d */ | sed -e "s/\///g"

How do I pass command-line arguments to a WinForms application?

Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

static class Program
{    
   [STAThread]
   static void Main(string[] args)
   {            
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

public Form1(string s, int i)
{
    if (s != null && i > 0)
       MessageBox.Show(s + " " + i);
}

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

Should I put input elements inside a label element?

One thing you need to consider is the interaction of checkbox and radio inputs with javascript.

Using below structure:

<label>
  <input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
  <span>Label text</span>
</label>

When user clicks on "Label text" controlCheckbox() function will be fired once.

But when input tag is clicked the controlCheckbox() function may be fired twice in some older browsers. That's because both input and label tags trigger onclick event attached to checkbox.

Then you may have some bugs in your checkboxState.

I've run into this issue lately on IE11. I'm not sure if modern browsers have troubles with this structure.

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

How to flush route table in windows?

In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.

How to use Python's pip to download and keep the zipped files for a package?

Use pip download <package1 package2 package n> to download all the packages including dependencies

Use pip install --no-index --find-links . <package1 package2 package n> to install all the packages including dependencies. It gets all the files from CWD. It will not download anything