Programs & Examples On #Removeall

Remove empty strings from array while keeping record Without Loop?

var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]

filter documentation


// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]

Arrow functions documentation

Format y axis as percent

pandas dataframe plot will return the ax for you, And then you can start to manipulate the axes whatever you want.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100,5))

# you get ax from here
ax = df.plot()
type(ax)  # matplotlib.axes._subplots.AxesSubplot

# manipulate
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])

enter image description here

An App ID with Identifier '' is not available. Please enter a different string

In my case, the problem was, that the identifier had too few dots.

com.example.foo wasn't accepted

com.example.foo.bar works

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

I had the same problem and I solved it as follows:

  1. check the node-sass version used in the current project

  2. go to node-sass release: "https://github.com/sass/node-sass/releases/tag/v@.@.@" (put your node-sass version here)

  3. check the Supported Environment table and see if your Node version exist in it

  4. if it is not, downgrade your node version to the latest version existing in the table

I know it's not the perfect solution but I didn't find anything else in my case.

Count occurrences of a char in a string using Bash

also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2

sed edit file in place

On a system where sed does not have the ability to edit files in place, I think the better solution would be to use perl:

perl -pi -e 's/foo/bar/g' file.txt

Although this does create a temporary file, it replaces the original because an empty in place suffix/extension has been supplied.

ASP.NET Web Site or ASP.NET Web Application?

Compilation Firstly there is a difference in compilation. Web Site is not pre-compiled on server, it is compiled on file. It may be an advantage because when you want to change something in your Web Site you can just download a specific file from server, change it and upload this file back to server and everything would work fine. In Web Application you can't do this because everthing is pre-compiled and you end up with only one dll. When you change something in one file of your project you have to re-compile everything again. So if you would like to have a possibility to change some files on server Web Site is better solution for you. It also allows many developers to work on one Web Site. On the other side, if you don't want your code to be available on server you should rather choose Web Application. This option is also better for Unit Testing because of one DLL file being created after publishing your website.

Project structure There is also a difference in the structure of the project. In Web Application you have a project file just like you had it in normal application. In Web Site there is no traditional project file, all you have is solution file. All references and settings are stored in web.config file. @Page directive There is a different attribute in @Page directive for the file that contains class associated with this page. In Web Application it is standard "CodeBehind", in Web Site you use "CodeFile". You can see this in the examples below:

Web Application:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"  
Inherits="WebApplication._Default" %>  

Web Site:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

Namespaces - In the example above you can see also another difference - how namespaces are created. In Web Application namespace is simply a name of the project. In Website there is default namespace ASP for dynamically compiled pages.

Edit and Continue- In Web Application Edit and Continue option is available (to turn it on you have to go to Tools Menu, click Options then find Edit and Continue in Debugging). This feature is not working in Web Site.ASP.NET MVCIf you want to develop web applications using

ASP.NET MVC (Model View Controller) the best and default option is Web Application. Although it's possible to use MVC in Web Site it's not recommended.

Summary - The most important difference between ASP.NET Web Application and Web Site is compilation. So if you work on a bigger project where a few people can modify it it's better to use Web Site. But if you're doing a smaller project you can use Web Application as well.

Change One Cell's Data in mysql

UPDATE will change only the columns you specifically list.

UPDATE some_table
SET field1='Value 1'
WHERE primary_key = 7;

The WHERE clause limits which rows are updated. Generally you'd use this to identify your table's primary key (or ID) value, so that you're updating only one row.

The SET clause tells MySQL which columns to update. You can list as many or as few columns as you'd like. Any that you do not list will not get updated.

Jquery change background color

try putting a delay on the last color fade.

$("p#44.test").delay(3000).css("background-color","red");

What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

The DLL you're looking for that contains that namespace is

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

Note that unit testing cannot be used in Visual Studio Express.

Test whether string is a valid integer

Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case statement.

case ${variable#[-+]} in
  *[!0-9]* | '') echo Not a number ;;
  * ) echo Valid number ;;
esac

The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

dynamically add and remove view to viewpager

Here's an alternative solution to this question. My adapter:

    private class PagerAdapter extends FragmentPagerAdapter implements 
                    ViewPager.OnPageChangeListener, TabListener {

    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private ViewPager mPager;
    private ActionBar mActionBar;

    private Fragment mPrimaryItem;

    public PagerAdapter(FragmentManager fm, ViewPager vp, ActionBar ab) {
        super(fm);
        mPager = vp;
        mPager.setAdapter(this);
        mPager.setOnPageChangeListener(this);
        mActionBar = ab;
    }

    public void addTab(PartListFragment frag) {
        mFragments.add(frag);
        mActionBar.addTab(mActionBar.newTab().setTabListener(this).
                            setText(frag.getPartCategory()));
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

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

    /** (non-Javadoc)
     * @see android.support.v4.app.FragmentStatePagerAdapter#setPrimaryItem(android.view.ViewGroup, int, java.lang.Object)
     */
    @Override
    public void setPrimaryItem(ViewGroup container, int position,
            Object object) {
        super.setPrimaryItem(container, position, object);
        mPrimaryItem = (Fragment) object;
    }

    /** (non-Javadoc)
     * @see android.support.v4.view.PagerAdapter#getItemPosition(java.lang.Object)
     */
    @Override
    public int getItemPosition(Object object) {
        if (object == mPrimaryItem) {
            return POSITION_UNCHANGED;
        }
        return POSITION_NONE;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        mPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) { }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) { }

    @Override
    public void onPageScrollStateChanged(int arg0) { }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) { }

    @Override
    public void onPageSelected(int position) {
        mActionBar.setSelectedNavigationItem(position);
    }

    /**
     * This method removes the pages from ViewPager
     */
    public void removePages() {
        mActionBar.removeAllTabs();

                    //call to ViewPage to remove the pages
        vp.removeAllViews();
        mFragments.clear();

        //make this to update the pager
        vp.setAdapter(null);
        vp.setAdapter(pagerAdapter);
    }
}

Code to remove and add dynamically

//remove the pages. basically call to method removeAllViews from `ViewPager`
pagerAdapter.removePages();

pagerAdapter.addPage(pass your fragment);

After the advice of Peri Hartman, it started to work after I set null do ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesnt showed its list contents.

Thanks.

How to randomize two ArrayLists in the same fashion?

The simplest approach is to encapsulate the two values together into a type which has both the image and the file. Then build an ArrayList of that and shuffle it.

That improves encapsulation as well, giving you the property that you'll always have the same number of files as images automatically.

An alternative if you really don't like that idea would be to write the shuffle code yourself (there are plenty of examples of a modified Fisher-Yates shuffle in Java, including several on Stack Overflow I suspect) and just operate on both lists at the same time. But I'd strongly recommend going with the "improve encapsulation" approach.

Difference between thread's context class loader and normal classloader

This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader() when you have to call a method that is missing a ClassLoader parameter.

When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.

When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader().

Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader(), sun.misc.VM.latestUserDefinedLoader(), or sun.reflect.Reflection.getCallerClass() it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader() exists only because whoever designed the ObjectInputStream API forgot to accept the ClassLoader as a parameter, and this mistake has haunted the Java community to this day.

That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader (which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.

When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader before the API call (and resetting it afterwards):

ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // call some API that uses reflection without taking ClassLoader param
} finally {
    Thread.currentThread().setContextClassLoader(originalClassLoader);
}

cannot redeclare block scoped variable (typescript)

Use IIFE(Immediately Invoked Function Expression), IIFE

(function () {
    all your code is here...

 })();

Decode HTML entities in Python string?

I had a similar encoding issue. I used the normalize() method. I was getting a Unicode error using the pandas .to_html() method when exporting my data frame to an .html file in another directory. I ended up doing this and it worked...

    import unicodedata 

The dataframe object can be whatever you like, let's call it table...

    table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
    table.index+= 1

encode table data so that we can export it to out .html file in templates folder(this can be whatever location you wish :))

     #this is where the magic happens
     html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')

export normalized string to html file

    file = open("templates/home.html","w") 

    file.write(html_data) 

    file.close() 

Reference: unicodedata documentation

Connect multiple devices to one device via Bluetooth

Yes, that is possible. At its lowest level Bluetooth allows you to connect up to 7 devices to one master device. I have done this and it has worked well for me, but only on other platforms (linux) where I had lots of manual control - I've never tried that on Android and there are some possible complications so you will need to do some testing to be certain.

One of the issues is that you need the tablet to the master and Android doesn't give you any explicit control of this. It is likely that this won't be a problem because * the tablet will automatically become the master when you try to connect a second device to it, or * you will be able to control the master/slave roles by how you setup your socket connection

I will caution though that most apps using Bluetooth on mobile are not attempting many simultaneous connections and Bluetooth can be a bit fragile, e.g. what if two devices already have a Bluetooth connection for some other app - how might that affect the roles?

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

How to remove a web site from google analytics

Updated Answer (July 22, 2015)

The solution to delete an Account/Property/View is still very similar to @Pranav ?'s answer. Google has just moved a few things around, so I thought I would update.

Step #1

Click Admin Tab at the top of the page

Step #1

Step #2

Once you are on the Admin Page, You need to decide if you want to delete the Account, Property, or View. Make sure to select the desired Account, Property, or View from the Drop Down Menu.

In the following pictures, I will show you how to delete the Account, which removes all information including Properties and Views under that particular account.

Click Account Settings to remove Account, Property Settings to remove Property, and View Settings to remove View.

Step #2

Step #3

On Account Settings, you will notice a button 'Move to Trash Can'. You will click this to remove the Account, Property or View. You will have to verify Moving the Account to the Trash Can on the next page/picture.

Step #3

Step #4

When you have verified this is the account you want to delete, go ahead and select 'Trash Account'.

Note: When you Trash an Account it moves all the information to Admin/Account/Trash Can, where it can be recovered within 1 month. Keep in mind that every Account has its own Trash Can. Once that time has lapsed the Account, Property or View will be deleted FOREVER!

Step #4

Hope this helps someone in the future, since I just struggled trying to figure it out even though its pretty simple now.

Password encryption at client side

You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.

You can use following libs:

  • jCryption. Client-Server asymmetric encryption over Javascript

Update after 3 years (2013):

Update after 4 years (2014):

What is a Y-combinator?

A Y-combinator is a "functional" (a function that operates on other functions) that enables recursion, when you can't refer to the function from within itself. In computer-science theory, it generalizes recursion, abstracting its implementation, and thereby separating it from the actual work of the function in question. The benefit of not needing a compile-time name for the recursive function is sort of a bonus. =)

This is applicable in languages that support lambda functions. The expression-based nature of lambdas usually means that they cannot refer to themselves by name. And working around this by way of declaring the variable, refering to it, then assigning the lambda to it, to complete the self-reference loop, is brittle. The lambda variable can be copied, and the original variable re-assigned, which breaks the self-reference.

Y-combinators are cumbersome to implement, and often to use, in static-typed languages (which procedural languages often are), because usually typing restrictions require the number of arguments for the function in question to be known at compile time. This means that a y-combinator must be written for any argument count that one needs to use.

Below is an example of how the usage and working of a Y-Combinator, in C#.

Using a Y-combinator involves an "unusual" way of constructing a recursive function. First you must write your function as a piece of code that calls a pre-existing function, rather than itself:

// Factorial, if func does the same thing as this bit of code...
x == 0 ? 1: x * func(x - 1);

Then you turn that into a function that takes a function to call, and returns a function that does so. This is called a functional, because it takes one function, and performs an operation with it that results in another function.

// A function that creates a factorial, but only if you pass in
// a function that does what the inner function is doing.
Func<Func<Double, Double>, Func<Double, Double>> fact =
  (recurs) =>
    (x) =>
      x == 0 ? 1 : x * recurs(x - 1);

Now you have a function that takes a function, and returns another function that sort of looks like a factorial, but instead of calling itself, it calls the argument passed into the outer function. How do you make this the factorial? Pass the inner function to itself. The Y-Combinator does that, by being a function with a permanent name, which can introduce the recursion.

// One-argument Y-Combinator.
public static Func<T, TResult> Y<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> F)
{
  return
    t =>  // A function that...
      F(  // Calls the factorial creator, passing in...
        Y(F)  // The result of this same Y-combinator function call...
              // (Here is where the recursion is introduced.)
        )
      (t); // And passes the argument into the work function.
}

Rather than the factorial calling itself, what happens is that the factorial calls the factorial generator (returned by the recursive call to Y-Combinator). And depending on the current value of t the function returned from the generator will either call the generator again, with t - 1, or just return 1, terminating the recursion.

It's complicated and cryptic, but it all shakes out at run-time, and the key to its working is "deferred execution", and the breaking up of the recursion to span two functions. The inner F is passed as an argument, to be called in the next iteration, only if necessary.

Logcat not displaying my log calls

There is one more thing to watch for:

On the top right side of the logcat there is a dropdown table for filtering messages by type. Make sure it's on the level you are looking for (if it will be on the assert level, it will likely leave your logcat empty).

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

How do I convert a datetime to date?

import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
    print datetime.datetime.fromtimestamp(dt).date()

jQuery Scroll to Div

Could just use JQuery position function to get coordinates of your div, then use javascript scroll:

var position = $("div").position();
scroll(0,position.top);

m2eclipse not finding maven dependencies, artifacts not found

I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.

SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).

Laravel - Form Input - Multiple select for a one to many relationship

Just single if conditions

<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
 @foreach ($categoryTypes as $categoryType)
  <option value="{{ $categoryType->id }}"
    **@if(in_array($categoryType->id,
     request()->get('category_type')??[]))selected="selected"
    @endif**>
     {{ ucfirst($categoryType->title) }}</option>
     @endforeach
 </select>

Open Sublime Text from Terminal in macOS

I'm on a mac and this worked for me:

open /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl

jQuery UI Dialog individual CSS styling

According to the UI dialog documentation, the dialog plugin generates something like this:

<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
   <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
      <span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
      <a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
   </div>
   <div class="ui-dialog-content ui-widget-content" id="dialog_style1">
      <p>One content</p>
   </div>
</div>

That means what you can add to any class to exactly to first or second dialog using jQuery's closest() method. For example:

$('#dialog_style1').closest('.ui-dialog').addClass('dialog_style1');

$('#dialog_style2').closest('.ui-dialog').addClass('dialog_style2');

and then CSS it.

Explanation of JSONB introduced by PostgreSQL

I was at the pgopen today benchmarks are way faster than mongodb, I believe it was around 500% faster for selects. Pretty much everything was faster at least by at 200% when contrasted with mongodb, than one exception right now is a update which requires completely rewriting the entire json column something mongodb handles better.

The gin indexing on on jsonb sounds amazing.

Also postgres will persist types of jsonb internally and basically match this with types such as numeric, text, boolean etc.

Joins will also be possible using jsonb

Add PLv8 for stored procedures and this will basically be a dream come true for node.js developers.

Being it's stored as binary jsonb will also strip all whitespace, change the ordering of properties and remove duplicate properties using the last occurance of the property.

Besides the index when querying against a jsonb column contrasted to a json column postgres doesn't have to actually run the functionality to convert the text to json on every row which will likely save a vast amount of time alone.

Get current value selected in dropdown using jQuery

This is what you need :)

$('._someDropDown').live('change', function(e) {
    console.log(e.target.options[e.target.selectedIndex].text);
});

For new jQuery use on

$(document).on('change', '._someDropDown', function(e) {
    console.log(this.options[e.target.selectedIndex].text);
});

Summernote image upload

Image Upload for Summernote v0.8.1

for large images

$('#summernote').summernote({
    height: ($(window).height() - 300),
    callbacks: {
        onImageUpload: function(image) {
            uploadImage(image[0]);
        }
    }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("image", image);
    $.ajax({
        url: 'Your url to deal with your image',
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function(url) {
            var image = $('<img>').attr('src', 'http://' + url);
            $('#summernote').summernote("insertNode", image[0]);
        },
        error: function(data) {
            console.log(data);
        }
    });
}

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

jQuery .slideRight effect

Another solution is by using .animate() and appropriate CSS.

e.g.

   $('#mydiv').animate({ marginLeft: "100%"} , 4000);

JS Fiddle

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

Update with Angular 7.x.x, encounter the same issue in one of my modules.

If it lies in your independent module, add these extra modules:

import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [CommonModule, FormsModule], // the order can be random now;
  ...
})

If it lies in your app.module.ts, add these modules:

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports:      [ FormsModule, BrowserModule ], // order can be random now
  ...
})

A simple demo to prove the case.

Is there a way to follow redirects with command line cURL?

As said, to follow redirects you can use the flag -L or --location:

curl -L http://www.example.com

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

How do I count unique values inside a list

For ndarray there is a numpy method called unique:

np.unique(array_name)

Examples:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

For a Series there is a function call value_counts():

Series_name.value_counts()

npm ERR cb() never called

[Works] try

npm config delete https-proxy

it would have conflicted with proxy.

How to include "zero" / "0" results in COUNT aggregate?

You must use LEFT JOIN instead of INNER JOIN

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

Why do we need virtual functions in C++?

i think you are referring to the fact once a method is declared virtual you don't need to use the 'virtual' keyword in overrides.

class Base { virtual void foo(); };

class Derived : Base 
{ 
  void foo(); // this is overriding Base::foo
};

If you don't use 'virtual' in Base's foo declaration then Derived's foo would just be shadowing it.

How to show code but hide output in RMarkdown?

The results = 'hide' option doesn't prevent other messages to be printed. To hide them, the following options are useful:

  • {r, error=FALSE}
  • {r, warning=FALSE}
  • {r, message=FALSE}

In every case, the corresponding warning, error or message will be printed to the console instead.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

i've try a lot of ways, but only this work for me

thanks for workaround

check your .env

MYSQL_VERSION=latest

then type this command

$ docker-compose exec mysql bash
$ mysql -u root -p 

(login as root)

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'secret';

then go to phpmyadmin and login as :

  • host -> mysql
  • user -> root
  • password -> root

hope it help

Pipenv: Command Not Found

You might consider installing pipenv via pipsi.

curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get -pipsi.py | python3
pipsi install pew
pipsi install pipenv

Unfortunately there are some issues with macOS + python3 at the time of writing, see 1, 2. In my case I had to change the bashprompt to #!/Users/einselbst/.local/venvs/pipsi/bin/python

Python, Matplotlib, subplot: How to set the axis range?

Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))

signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)

fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))

plt.show()

Java - Check if JTextField is empty or not

use the following code :

if(name.getText().equals(""))
{
loginbt.disable();
}

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

How to Set Variables in a Laravel Blade Template

I also struggled with this same issue. But I was able to manage this problem by using following code segment. Use this in your blade template.

<input type="hidden" value="{{$old_section = "whatever" }}">

{{$old_section }}

how to implement a pop up dialog box in iOS

For Swift 3 & Swift 4 :

Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3

let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title:     NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
                //Do whatever you want here
        })
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)

Deprecated :

This is the swift version inspired by the checked response :

Display AlertView :

   let alert = UIAlertView(title: "No network connection", 
                           message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
    alert.delegate = self
    alert.show()

Add the delegate to your view controller :

class AgendaViewController: UIViewController, UIAlertViewDelegate

When user click on button, this code will be executed :

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {


}

Best method for reading newline delimited files and discarding the newlines?

I use this

def cleaned( aFile ):
    for line in aFile:
        yield line.strip()

Then I can do things like this.

lines = list( cleaned( open("file","r") ) )

Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.

How to do jquery code AFTER page loading?

Edit: This code will wait until all content (images and scripts) are fully loaded and rendered in the browser.

I've had this problem where $(window).on('load',function(){ ... }) would fire too quick for my code since the Javascript I used was for formatting purposes and hiding elements. The elements where hidden too soon and where left with a height of 0.

I now use $(window).on('pageshow',function(){ //code here }); and it fires at the time I need.

Flutter - The method was called on null

You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.

EDIT:

I see diegoveloper beat me to answering this, and that the OP asked a follow up.

@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

CryptoListPresenter _presenter;

@override
void initState() {
  _presenter = new CryptoListPresenter(...);
}

Changing the child element's CSS when the parent is hovered

.parent:hover > .child {
    /*do anything with this child*/
}

AttributeError: 'tuple' object has no attribute

I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion

Is there a way to check which CSS styles are being used or not used on a web page?

Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.

Static linking vs dynamic linking

Dynamic linking requires extra time for the OS to find the dynamic library and load it. With static linking, everything is together and it is a one-shot load into memory.

Also, see DLL Hell. This is the scenario where the DLL that the OS loads is not the one that came with your application, or the version that your application expects.

Print series of prime numbers in python

min=int(input("min:"))
max=int(input("max:"))
for num in range(min,max):
    for x in range(2,num):
        if(num%x==0 and num!=1):
            break
        else:
            print(num,"is prime")
            break

how to change text in Android TextView

I just posted this answer in the android-discuss google group

If you are just trying to add text to the view so that it displays "Step One: blast egg Step Two: fry egg" Then consider using t.appendText("Step Two: fry egg"); instead of t.setText("Step Two: fry egg");

If you want to completely change what is in the TextView so that it says "Step One: blast egg" on startup and then it says "Step Two: fry egg" at a time later you can always use a

Runnable example sadboy gave

Good luck

Converting Decimal to Binary Java

public static void main(String h[])
{
    Scanner sc=new Scanner(System.in);
    int decimal=sc.nextInt();

    String binary="";

    if(decimal<=0)
    {
        System.out.println("Please Enter more than 0");

    }
    else
    {
        while(decimal>0)
        {

            binary=(decimal%2)+binary;
            decimal=decimal/2;

        }
        System.out.println("binary is:"+binary);

    }

}

SCRIPT5: Access is denied in IE9 on xmlhttprequest

This error message (SCRIPT5: Access is denied.) can also be encountered if the target page of a .replace method is not found (I had entered the page name incorrectly). I know because it just happened to me, which is why I went searching for some more information about the meaning of the error message.

How do I convert NSInteger to NSString datatype?

%zd works for NSIntegers (%tu for NSUInteger) with no casts and no warnings on both 32-bit and 64-bit architectures. I have no idea why this is not the "recommended way".

NSString *string = [NSString stringWithFormat:@"%zd", month];

If you're interested in why this works see this question.

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

Similar to POsha's answer but this is what worked for me on ubuntu 19

sudo npm i -g ngrok --unsafe-perm=true --allow-root

From this link

https://github.com/inconshreveable/ngrok/issues/429

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Remove all special characters, punctuation and spaces from string

Assuming you want to use a regex and you want/need Unicode-cognisant 2.x code that is 2to3-ready:

>>> import re
>>> rx = re.compile(u'[\W_]+', re.UNICODE)
>>> data = u''.join(unichr(i) for i in range(256))
>>> rx.sub(u'', data)
u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xaa\xb2 [snip] \xfe\xff'
>>>

T-SQL Subquery Max(Date) and Joins

In SQL Server 2005 and later use ROW_NUMBER():

SELECT * FROM 
    ( SELECT p.*,
        ROW_NUMBER() OVER(PARTITION BY Partid ORDER BY PriceDate DESC) AS rn
    FROM MyPrice AS p ) AS t
WHERE rn=1

Redirecting output to $null in PowerShell, but ensuring the variable remains set

If it's errors you want to hide you can do it like this

$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on

Does MS Access support "CASE WHEN" clause if connect with ODBC?

You could use IIF statement like in the next example:

SELECT
   IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
   TABLE_NAME

How to fix Invalid AES key length?

You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.

This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;

public class Encrypt {

    static byte [] arr = {1,2,3,4,5,6,7,8,9};

    // static byte [] arr = new byte[16];

      public static void main(String...args) {
        try {
         //   System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
            Base64.Decoder decoder = Base64.getDecoder();
            // static byte [] arr = new byte[16];
            Security.setProperty("crypto.policy", "unlimited");
            String key = "Your key";
       //     System.out.println("-------" + key);

            String value = "Hey, i am adnan";
            String IV = "0123456789abcdef";
       //     System.out.println(value);
            // log.info(value);
          IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            //    IvParameterSpec iv = new IvParameterSpec(arr);

        //    System.out.println(key);
            SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
         //   System.out.println(skeySpec);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //    System.out.println("ddddddddd"+IV);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
       //     System.out.println(cipher.getIV());

            byte[] encrypted = cipher.doFinal(value.getBytes());
            String encryptedString = Base64.getEncoder().encodeToString(encrypted);

            System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
            // vars.put("input-1",encryptedString);
            //  log.info("beanshell");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}

Forbidden: You don't have permission to access / on this server, WAMP Error

By default wamp sets the following as the default for any directory not explicitly declared:

<Directory />
    AllowOverride none
    Require all denied
</Directory>

For me, if I comment out the line that says Require all denied I started having access to the directory in question. I don't recommend this.

Instead in the directory directive I included Require local as below:

<Directory "C:/GitHub/head_count/">
    AllowOverride All
    Allow from all
    Require local
</Directory>

NOTE: I was still getting permission denied when I only had Allow from all. Adding Require local helped for me.

Bootstrap Accordion button toggle "data-parent" not working

As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:

$('#your-parent .collapse').on('show.bs.collapse', function (e) {
    var actives = $('#your-parent').find('.in, .collapsing');
    actives.each( function (index, element) {
        $(element).collapse('hide');
    })
})

Does a "Find in project..." feature exist in Eclipse IDE?

Open Search Dialog Search-> Search... or use Shortcut Ctrl + H.

  1. Containing text: Type the expression for which you wish to do the text search.
  2. Choose if you want Case sensitive, Regular expression or Whole word
  3. File name patterns: In this field, enter all the file name patterns for the files to find or search through for the specified expression.
  4. Scope: Choose the scope of your search. You can either search the whole workspace, pre-defined working sets, previously selected resources or projects enclosing the selected resources.
  5. Press Search

enter image description here

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had this error and the other fixes didn't help me, but changing the CPU type the emulator used did get it working.

Create a new emulator and try using mips or arm for the cpu selection

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

How do I profile memory usage in Python?

Python 3.4 includes a new module: tracemalloc. It provides detailed statistics about which code is allocating the most memory. Here's an example that displays the top three lines allocating memory.

from collections import Counter
import linecache
import os
import tracemalloc

def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


tracemalloc.start()

counts = Counter()
fname = '/usr/share/dict/american-english'
with open(fname) as words:
    words = list(words)
    for word in words:
        prefix = word[:3]
        counts[prefix] += 1
print('Top prefixes:', counts.most_common(3))

snapshot = tracemalloc.take_snapshot()
display_top(snapshot)

And here are the results:

Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: scratches/memory_test.py:37: 6527.1 KiB
    words = list(words)
#2: scratches/memory_test.py:39: 247.7 KiB
    prefix = word[:3]
#3: scratches/memory_test.py:40: 193.0 KiB
    counts[prefix] += 1
4 other: 4.3 KiB
Total allocated size: 6972.1 KiB

When is a memory leak not a leak?

That example is great when the memory is still being held at the end of the calculation, but sometimes you have code that allocates a lot of memory and then releases it all. It's not technically a memory leak, but it's using more memory than you think it should. How can you track memory usage when it all gets released? If it's your code, you can probably add some debugging code to take snapshots while it's running. If not, you can start a background thread to monitor memory usage while the main thread runs.

Here's the previous example where the code has all been moved into the count_prefixes() function. When that function returns, all the memory is released. I also added some sleep() calls to simulate a long-running calculation.

from collections import Counter
import linecache
import os
import tracemalloc
from time import sleep


def count_prefixes():
    sleep(2)  # Start up time.
    counts = Counter()
    fname = '/usr/share/dict/american-english'
    with open(fname) as words:
        words = list(words)
        for word in words:
            prefix = word[:3]
            counts[prefix] += 1
            sleep(0.0001)
    most_common = counts.most_common(3)
    sleep(3)  # Shut down time.
    return most_common


def main():
    tracemalloc.start()

    most_common = count_prefixes()
    print('Top prefixes:', most_common)

    snapshot = tracemalloc.take_snapshot()
    display_top(snapshot)


def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


main()

When I run that version, the memory usage has gone from 6MB down to 4KB, because the function released all its memory when it finished.

Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: collections/__init__.py:537: 0.7 KiB
    self.update(*args, **kwds)
#2: collections/__init__.py:555: 0.6 KiB
    return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
#3: python3.6/heapq.py:569: 0.5 KiB
    result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
10 other: 2.2 KiB
Total allocated size: 4.0 KiB

Now here's a version inspired by another answer that starts a second thread to monitor memory usage.

from collections import Counter
import linecache
import os
import tracemalloc
from datetime import datetime
from queue import Queue, Empty
from resource import getrusage, RUSAGE_SELF
from threading import Thread
from time import sleep

def memory_monitor(command_queue: Queue, poll_interval=1):
    tracemalloc.start()
    old_max = 0
    snapshot = None
    while True:
        try:
            command_queue.get(timeout=poll_interval)
            if snapshot is not None:
                print(datetime.now())
                display_top(snapshot)

            return
        except Empty:
            max_rss = getrusage(RUSAGE_SELF).ru_maxrss
            if max_rss > old_max:
                old_max = max_rss
                snapshot = tracemalloc.take_snapshot()
                print(datetime.now(), 'max RSS', max_rss)


def count_prefixes():
    sleep(2)  # Start up time.
    counts = Counter()
    fname = '/usr/share/dict/american-english'
    with open(fname) as words:
        words = list(words)
        for word in words:
            prefix = word[:3]
            counts[prefix] += 1
            sleep(0.0001)
    most_common = counts.most_common(3)
    sleep(3)  # Shut down time.
    return most_common


def main():
    queue = Queue()
    poll_interval = 0.1
    monitor_thread = Thread(target=memory_monitor, args=(queue, poll_interval))
    monitor_thread.start()
    try:
        most_common = count_prefixes()
        print('Top prefixes:', most_common)
    finally:
        queue.put('stop')
        monitor_thread.join()


def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


main()

The resource module lets you check the current memory usage, and save the snapshot from the peak memory usage. The queue lets the main thread tell the memory monitor thread when to print its report and shut down. When it runs, it shows the memory being used by the list() call:

2018-05-29 10:34:34.441334 max RSS 10188
2018-05-29 10:34:36.475707 max RSS 23588
2018-05-29 10:34:36.616524 max RSS 38104
2018-05-29 10:34:36.772978 max RSS 45924
2018-05-29 10:34:36.929688 max RSS 46824
2018-05-29 10:34:37.087554 max RSS 46852
Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
2018-05-29 10:34:56.281262
Top 3 lines
#1: scratches/scratch.py:36: 6527.0 KiB
    words = list(words)
#2: scratches/scratch.py:38: 16.4 KiB
    prefix = word[:3]
#3: scratches/scratch.py:39: 10.1 KiB
    counts[prefix] += 1
19 other: 10.8 KiB
Total allocated size: 6564.3 KiB

If you're on Linux, you may find /proc/self/statm more useful than the resource module.

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django view.py

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(request.data['data'])
    ...
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

How to Configure SSL for Amazon S3 bucket

You can access your files via SSL like this:

https://s3.amazonaws.com/bucket_name/images/logo.gif

If you use a custom domain for your bucket, you can use S3 and CloudFront together with your own SSL certificate (or generate a free one via Amazon Certificate Manager): http://aws.amazon.com/cloudfront/custom-ssl-domains/

How To: Best way to draw table in console app (C#)

Edit: thanks to @superlogical, you can now find and improve the following code in github!


I wrote this class based on some ideas here. The columns width is optimal, an it can handle object arrays with this simple API:

static void Main(string[] args)
{
  IEnumerable<Tuple<int, string, string>> authors =
    new[]
    {
      Tuple.Create(1, "Isaac", "Asimov"),
      Tuple.Create(2, "Robert", "Heinlein"),
      Tuple.Create(3, "Frank", "Herbert"),
      Tuple.Create(4, "Aldous", "Huxley"),
    };

  Console.WriteLine(authors.ToStringTable(
    new[] {"Id", "First Name", "Surname"},
    a => a.Item1, a => a.Item2, a => a.Item3));

  /* Result:        
  | Id | First Name | Surname  |
  |----------------------------|
  | 1  | Isaac      | Asimov   |
  | 2  | Robert     | Heinlein |
  | 3  | Frank      | Herbert  |
  | 4  | Aldous     | Huxley   |
  */
}

Here is the class:

public static class TableParser
{
  public static string ToStringTable<T>(
    this IEnumerable<T> values,
    string[] columnHeaders,
    params Func<T, object>[] valueSelectors)
  {
    return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
  }

  public static string ToStringTable<T>(
    this T[] values,
    string[] columnHeaders,
    params Func<T, object>[] valueSelectors)
  {
    Debug.Assert(columnHeaders.Length == valueSelectors.Length);

    var arrValues = new string[values.Length + 1, valueSelectors.Length];

    // Fill headers
    for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
    {
      arrValues[0, colIndex] = columnHeaders[colIndex];
    }

    // Fill table rows
    for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
    {
      for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
      {
        arrValues[rowIndex, colIndex] = valueSelectors[colIndex]
          .Invoke(values[rowIndex - 1]).ToString();
      }
    }

    return ToStringTable(arrValues);
  }

  public static string ToStringTable(this string[,] arrValues)
  {
    int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
    var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);

    var sb = new StringBuilder();
    for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
    {
      for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
      {
        // Print cell
        string cell = arrValues[rowIndex, colIndex];
        cell = cell.PadRight(maxColumnsWidth[colIndex]);
        sb.Append(" | ");
        sb.Append(cell);
      }

      // Print end of line
      sb.Append(" | ");
      sb.AppendLine();

      // Print splitter
      if (rowIndex == 0)
      {
        sb.AppendFormat(" |{0}| ", headerSpliter);
        sb.AppendLine();
      }
    }

    return sb.ToString();
  }

  private static int[] GetMaxColumnsWidth(string[,] arrValues)
  {
    var maxColumnsWidth = new int[arrValues.GetLength(1)];
    for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
    {
      for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
      {
        int newLength = arrValues[rowIndex, colIndex].Length;
        int oldLength = maxColumnsWidth[colIndex];

        if (newLength > oldLength)
        {
          maxColumnsWidth[colIndex] = newLength;
        }
      }
    }

    return maxColumnsWidth;
  }
}

Edit: I added a minor improvement - if you want the column headers to be the property name, add the following method to TableParser (note that it will be a bit slower due to reflection):

public static string ToStringTable<T>(
    this IEnumerable<T> values,
    params Expression<Func<T, object>>[] valueSelectors)
{
  var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
  var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
  return ToStringTable(values, headers, selectors);
}

private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expresstion)
{
  if (expresstion.Body is UnaryExpression)
  {
    if ((expresstion.Body as UnaryExpression).Operand is MemberExpression)
    {
      return ((expresstion.Body as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo;
    }
  }

  if ((expresstion.Body is MemberExpression))
  {
    return (expresstion.Body as MemberExpression).Member as PropertyInfo;
  }
  return null;
}

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Python unittest - opposite of assertRaises?

I am the original poster and I accepted the above answer by DGH without having first used it in the code.

Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).

I thought it was worth posting the tweak here for the benefit of others:

    try:
        a = Application("abcdef", "")
    except pySourceAidExceptions.PathIsNotAValidOne:
        pass
    except:
        self.assertTrue(False)

What I was attempting to do here was to ensure that if an attempt was made to instantiate an Application object with a second argument of spaces the pySourceAidExceptions.PathIsNotAValidOne would be raised.

I believe that using the above code (based heavily on DGH's answer) will do that.

How does Access-Control-Allow-Origin header work?

Using React and Axios, join proxy link to the URL and add header as shown below

https://cors-anywhere.herokuapp.com/ + Your API URL

Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.

axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
      .then(response => console.log(response:data);
  }

WARNING: Not to be used in Production

This is just a quick fix, if you're struggling with why you're not able to get a response, you CAN use this. But again it's not the best answer for production.

Got several downvotes and it completely makes sense, I should have added the warning a long time ago.

Is there a difference between /\s/g and /\s+/g?

In a match situation the first would return one match per whitespace, when the second would return a match for each group of whitespaces.

The result is the same because you're replacing it with an empty string. If you replace it with 'x' for instance, the results would differ.

str.replace(/\s/g, '') will return 'xxAxBxxCxxxDxEF '

while str.replace(/\s+/g, '') will return 'xAxBxCxDxEF '

because \s matches each whitespace, replacing each one with 'x', and \s+ matches groups of whitespaces, replacing multiple sequential whitespaces with a single 'x'.

How do I update a Linq to SQL dbml file?

We use a custom written T4 template that dynamically queries the information_schema model for each table in all of our .DBML files, and then overwrites parts of the .DBML file with fresh schema info from the database. I highly recommend implementing a solution like this - it has saved me oodles of time, and unlike deleting and re-adding your tables to your model you get to keep your associations. With this solution, you'll get compile-time errors when your schema changes. You want to make sure that you're using a version control system though, because diffing is really handy. This is a great solution that works well if you're developing with a DB schema first approach. Of course, I can't share my company's code so you're on your own for writing this yourself. But if you know some Linq-to-XML and can go to school on this project, you can get to where you want to be.

How to change progress bar's progress color in Android

As per muhammad-adil suggested for SDK ver 21 and above

android:indeterminateTint="@color/orange"

in XML Works for me, is easy enough.

remove table row with specific id

$('#3').remove();

Might not work with numeric id's though.

What is the 'override' keyword in C++ used for?

Wikipedia says:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

In detail, when you have an object foo that has a void hello() function:

class foo {
    virtual void hello(); // Code : printf("Hello!");
}

A child of foo, will also have a hello() function:

class bar : foo {
    // no functions in here but yet, you can call
    // bar.hello()
}

However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override

class bar : foo {
    virtual void hello() override; // Code : printf("Hello Bar!");
}

Get textarea text with javascript or Jquery

Try This:

var info = document.getElementById("area1").value; // Javascript
var info = $("#area1").val(); // jQuery

Check list of words in another string

Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTM's answer, depending on the context.

1) use a regular expression:

import re
words_re = re.compile("|".join(list_of_words))

if words_re.search('some one long two phrase three'):
   # do logic you want to perform

2) You could use sets if you want to match whole words, e.g. you do not want to find the word "the" in the phrase "them theorems are theoretical":

word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
    # do stuff

Of course you can also do whole word matches with regex using the "\b" token.

The performance of these and Kenny's solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change. If performance is not an issue then go for the simplest, which is probably Kenny's.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

All I did is go to my project directory from the cmd (command prompt) I typed java -version.it told me what version it was looking for. so I Installed that version and I changed the path to were the jdk of that version was located .

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

How can I check for Python version in a program that uses new language features?

Put the following at the very top of your file:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

Then continue on with the normal Python code:

import ...
import ...
other code...

Regular Expression Match to test for a valid year

you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...

Onclick javascript to make browser go back to previous page?

<input name="action" type="submit" value="Cancel" onclick="window.history.back();"/> 

Convert Python program to C/C++ code?

Shed Skin is "a (restricted) Python-to-C++ compiler".

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

try like this. hope it works

drawable-sw720dp-xxhdpi and values-sw720dp-xxhdpi

drawable-sw720dp-xxxhdpi and values-sw720dp-xxxhdpi

link might destroy so pasted ans

reference Android xxx-hdpi real devices

xxxhdpi was only introduced because of the way that launcher icons are scaled on the nexus 5's launcher Because the nexus 5's default launcher uses bigger icons, xxxhdpi was introduced so that icons would still look good on the nexus 5's launcher.

also check these links

Different resolution support android

Application Skeleton to support multiple screen

Is there a list of screen resolutions for all Android based phones and tablets?

How to align iframe always in the center

Try this:

#wrapper {
    text-align: center;
}

#wrapper iframe {
    display: inline-block;
}

What does mvn install in maven exactly do

It will run all goals of all configured plugins associated with any phase of the default lifecycle up to the "install" phase:

https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

Generate a sequence of numbers in Python

>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'

That was a quick and quite dirty solution.

Now, for a solution that is suitable for different kinds of progression problems:

def deltas():
    while True:
        yield 1
        yield 3
def numbers(start, deltas, max):
    i = start
    while i <= max:
        yield i
        i += next(deltas)
print(','.join(str(i) for i in numbers(1, deltas(), 100)))

And here are similar ideas implemented using itertools:

from itertools import cycle, takewhile, accumulate, chain

def numbers(start, deltas, max):
    deltas = cycle(deltas)
    numbers = accumulate(chain([start], deltas))
    return takewhile(lambda x: x <= max, numbers)

print(','.join(str(x) for x in numbers(1, [1, 3], 100)))

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Tested on 4.2.7 release

package com.national.software.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.national.software.dto.UserDetails;

public class HibernateTest {

    static SessionFactory sessionFactory;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("user1");

        Configuration config = new Configuration();
        config.configure();

        ServiceRegistry  serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        sessionFactory = config.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();

    }

}

Difference between no-cache and must-revalidate

I think there is a difference between max-age=0, must-revalidate and no-cache:

In the must-revalidate case the client is allowed to send a If-Modified-Since request and serve the response from cache if 304 Not Modified is returned.

In the no-cache case, the client must not cache the response, so should not use If-Modified-Since.

How do I register a .NET DLL file in the GAC?

I tried just about everything in the comments and it didn't work. So I did gacutil /i "path to my dll" from Powershell and it worked.

Also remember the trick of pressing Shift when you right-click on a file in Windows Explorer to get the option of Copy path.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

Maybe your dept_name columns have different charsets.

You could try to alter one or both of them:

ALTER TABLE department MODIFY dept_name VARCHAR(20) CHARACTER SET utf8;
ALTER TABLE course MODIFY dept_name VARCHAR(20) CHARACTER SET utf8;

Simplest way to set image as JPanel background

As I know the way you can do it is to override paintComponent method that demands to inherit JPanel

 @Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); // paint the background image and scale it to fill the entire space
    g.drawImage(/*....*/);
}

The other way (a bit complicated) to create second custom JPanel and put is as background for your main

ImagePanel

public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;

public ImagePanel(Image image)
{
    this.image = image;
    this.iWidth2 = image.getWidth(this)/2;
    this.iHeight2 = image.getHeight(this)/2;
}


public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    if (image != null)
    {
        int x = this.getParent().getWidth()/2 - iWidth2;
        int y = this.getParent().getHeight()/2 - iHeight2;
        g.drawImage(image,x,y,this);
    }
}
}

EmptyPanel

public class EmptyPanel extends JPanel{

private static final long serialVersionUID = 1L;

public EmptyPanel() {
    super();
    init();
}

@Override
public boolean isOptimizedDrawingEnabled() {
    return false;
}


public void init(){

    LayoutManager overlay = new OverlayLayout(this);
    this.setLayout(overlay);

    ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
    iPanel.setLayout(new BorderLayout());   
    this.add(iPanel);
    iPanel.setOpaque(false);                
}
}

IconToImage

public class IconToImage {

Icon icon;
Image image;


public IconToImage(Icon icon) {
    this.icon = icon;
    image = iconToImage();
}

public Image iconToImage() { 
    if (icon instanceof ImageIcon) { 
        return ((ImageIcon)icon).getImage(); 
    } else { 
        int w = icon.getIconWidth(); 
        int h = icon.getIconHeight(); 
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
        GraphicsDevice gd = ge.getDefaultScreenDevice(); 
        GraphicsConfiguration gc = gd.getDefaultConfiguration(); 
        BufferedImage image = gc.createCompatibleImage(w, h); 
        Graphics2D g = image.createGraphics(); 
        icon.paintIcon(null, g, 0, 0); 
        g.dispose(); 
        return image; 
    } 
}


/**
 * @return the image
 */
public Image getImage() {
    return image;
}
}

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

Django Multiple Choice Field / Checkbox Select Multiple

The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)

This trick works very well

#model.py
class ClassName(models.Model):
    field_name = models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.field_name:
            self.field_name= eval(self.field_name)



#form.py
CHOICES = [('pi', 'PI'), ('ci', 'CI')]

class ClassNameForm(forms.ModelForm):
    field_name = forms.MultipleChoiceField(choices=CHOICES)

    class Meta:
        model = ClassName
        fields = ['field_name',]

How to Select a substring in Oracle SQL up to a specific character?

SELECT REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1)  from dual

is the right answer, as posted by user1717270

If you use INSTR, it will give you the position for a string that assumes it contains "_" in it. What if it doesn't? Well the answer will be 0. Therefore, when you want to print the string, it will print a NULL. Example: If you want to remove the domain from a "host.domain". In some cases you will only have the short name, i.e. "host". Most likely you would like to print "host". Well, with INSTR it will give you a NULL because it did not find any ".", i.e. it will print from 0 to 0. With REGEXP_SUBSTR you will get the right answer in all cases:

SELECT REGEXP_SUBSTR('HOST.DOMAIN','[^.]+',1,1)  from dual;

HOST

and

SELECT REGEXP_SUBSTR('HOST','[^.]+',1,1)  from dual;

HOST

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

How to disable registration new users in Laravel

I guess this would rather be a better solution.

Override the following methods as below mentioned in

App\Http\Controller\Auth\RegisterController.php

use Illuminate\Http\Response;

.
.
.

public function showRegistrationForm()
{
    abort(Response::HTTP_NOT_FOUND);
}

public function register(Request $request)
{
    abort(Response::HTTP_NOT_FOUND);
}

Confirm Password with jQuery Validate

Remove the required: true rule.

Demo: Fiddle

jQuery('.validatedForm').validate({
            rules : {
                password : {
                    minlength : 5
                },
                password_confirm : {
                    minlength : 5,
                    equalTo : "#password"
                }
            }

Exception in thread "main" java.util.NoSuchElementException

Reimeus is right, you see this because of in.close in your chooseCave(). Also, this is wrong.

if (playAgain == "yes") {
      play = true;
}

You should use equals instead of "==".

if (playAgain.equals("yes")) {
      play = true;
}

Detect Route Change with react-router

React Router V5

If you want the pathName as a string ('/' or 'users'), you can use the following:

  // React Hooks: React Router DOM
  let history = useHistory();
  const location = useLocation();
  const pathName = location.pathname;

How can I read SMS messages from the device programmatically in Android?

From API 19 onwards you can make use of the Telephony Class for that; Since hardcored values won't retrieve messages in every devices because the content provider Uri changes from devices and manufacturers.

public void getAllSms(Context context) {

    ContentResolver cr = context.getContentResolver();
    Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
    int totalSMS = 0;
    if (c != null) {
        totalSMS = c.getCount();
        if (c.moveToFirst()) {
            for (int j = 0; j < totalSMS; j++) {
                String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
                String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
                String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
                Date dateFormat= new Date(Long.valueOf(smsDate));
                String type;
                switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)))) {
                    case Telephony.Sms.MESSAGE_TYPE_INBOX:
                        type = "inbox";
                        break;
                    case Telephony.Sms.MESSAGE_TYPE_SENT:
                        type = "sent";
                        break;
                    case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
                        type = "outbox";
                        break;
                    default:
                        break;
                }


                c.moveToNext();
            }
        }

        c.close();

    } else {
        Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show();
    }
}

jQuery - add additional parameters on submit (NOT ajax)

In your case it should suffice to just add another hidden field to your form dynamically.

var input = $("<input>").attr("type", "hidden").val("Bla");
$('#form').append($(input));

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

AngularJS: Basic example to use authentication in Single Page Application

I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.

And what happen if the user catch de JSON and change the bool to True?

I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.

Inheriting from a template class in c++

Rectangle will have to be a template, otherwise it is just one type. It cannot be a non-template whilst its base magically is. (Its base may be a template instantiation, though you seem to want to maintain the base's functionality as a template.)

PHP Notice: Undefined offset: 1 with array when reading data

Change

$data[$parts[0]] = $parts[1];

to

if ( ! isset($parts[1])) {
   $parts[1] = null;
}

$data[$parts[0]] = $parts[1];

or simply:

$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;

Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.

According to php.net possible return values from explode:

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

"google is not defined" when using Google Maps V3 in Firefox remotely

instead of this

var defaultLocation = new google.maps.LatLng(lat, lng);

use this

var defaultLocation = new window.google.maps.LatLng(lat, lng);

and this worked for me.

SQL Query NOT Between Two Dates

If the 'NOT' is put before the start_date it should work. For some reason (I don't know why) when 'NOT' is put before 'BETWEEN' it seems to return everything.

NOT (start_date BETWEEN CAST('2009-12-15' AS DATE) AND CAST('2010-01-02' AS DATE))

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

Convert a string to a double - is this possible?

Just use floatval().

E.g.:

$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343

And in case you wonder doubleval() is just an alias for floatval().

And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001 and this error could propagate.

React navigation goBack() and update parent state

For those who don't want to manage via props, try this. It will call everytime when this page appear.

Note* (this is not only for goBack but it will call every-time you enter this page.)

import { NavigationEvents } from 'react-navigation';

render() {
    return (
        <View style={{ flex: 1 }}>
            <NavigationEvents
              onWillFocus={() => {
                // Do your things here
              }}
            />
        </View>
    );
}

How do I make a WinForms app go Full Screen

A tested and simple solution

I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.

Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

Download a file from NodeJS Server using Express

'use strict';

var express = require('express');
var fs = require('fs');
var compress = require('compression');
var bodyParser = require('body-parser');

var app = express();
app.set('port', 9999);
app.use(bodyParser.json({ limit: '1mb' }));
app.use(compress());

app.use(function (req, res, next) {
    req.setTimeout(3600000)
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join());

    if (req.method === 'OPTIONS') {
        res.write(':)');
        res.end();
    } else next();
});

function readApp(req,res) {
  var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa",
      filePath = "/home/sony/Documents/docs/";
  fs.exists(filePath, function(exists){
      if (exists) {     
        res.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition" : "attachment; filename=" + file});
        fs.createReadStream(filePath + file).pipe(res);
      } else {
        res.writeHead(400, {"Content-Type": "text/plain"});
        res.end("ERROR File does NOT Exists.ipa");
      }
    });  
}

app.get('/read-android', function(req, res) {
    var u = {"originalUrl":req.originalUrl};
    readApp(u,res) 
});

app.get('/read-ios', function(req, res) {
    var u = {"originalUrl":req.originalUrl};
    readApp(u,res) 
});

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + server.address().port);
});

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

Passing arguments to JavaScript function from code-behind

Some other things I found out:

You can't directly pass in an array like:

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",   
"<script>test("+x+","+y+");</script>");

because that calls the ToString() methods of x and y, which returns "System.Int32[]", and obviously Javascript can't use that. I had to pass in the arrays as strings, like "[1,2,3,4,5]", so I wrote a helper method to do the conversion.

Also, there is a difference between this.Page.ClientScript.RegisterStartupScript() and this.Page.ClientScript.RegisterClientScriptBlock() - the former places the script at the bottom of the page, which I need in order to be able to access the controls (like with document.getElementByID). RegisterClientScriptBlock() is executed before the tags are rendered, so I actually get a Javascript error if I use that method.

http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.html covers the difference between the two pretty well.

Here's the complete example I came up with:

// code behind
protected void Button1_Click(object sender, EventArgs e)
{
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
    string yStr = getArrayString(y);

    string script = String.Format("test({0},{1})", xStr, yStr);
    this.Page.ClientScript.RegisterStartupScript(this.GetType(),
    "testFunction", script, true);
    //this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
    //"testFunction", script, true); // different result
}
private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}

//aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function test(x, y)
    {
        var text1 = document.getElementById("text1")
        for(var i = 0; i<x.length; i++)
        {
            text1.innerText += x[i]; // prints 12345
        }
        text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5

    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"
         onclick="Button1_Click" />
    </div>
    <div id ="text1"> 
    </div>
    </form>
</body>
</html>

How to create a data file for gnuplot?

Create your Datafile like this:

# X      Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45

And plot it with

$ gnuplot -p -e "plot 'filename.dat'"

There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/

What is the default maximum heap size for Sun's JVM from Java SE 6?

one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details

When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.

How to configure PostgreSQL to accept all incoming connections

Configuration all files with postgres 12 on centos:

step 1: search and edit file

sudo vi /var/lib/pgsql/12/data/pg_hba.conf

press "i" and at line IPv4 change

host    all             all             0.0.0.0/0            md5

step 2: search and edit file postgresql.conf

sudo vi /var/lib/pgsql/12/data/postgresql.conf

add last line: listen_addresses = '*' :wq! (save file) - step 3: restart

systemctl restart postgresql-12.service

When should I use a table variable vs temporary table in sql server?

Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.

I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).

Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp table will do (table-valued parameters allow readonly access).

Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).

  1. If you need an index that cannot be created on a table variable then you will of course need a #temporary table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE or PRIMARY KEY constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX. This has been extended since to allow filtered index conditions. Indexes with INCLUDE-d columns or columnstore indexes are still not possible to create on table variables however.

  2. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE as illustrated here.

  3. If you will be deleting or updating a large number of rows then the temp table may well perform much better than a table variable - if it is able to use rowset sharing (see "Effects of rowset sharing" below for an example).
  4. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  5. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  6. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  7. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  8. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  9. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. Bob Ward points out in his tempdb presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.

Effects of rowset sharing

DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);

CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);

INSERT INTO @T 
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2

SET STATISTICS TIME ON

/*CPU time = 7016 ms,  elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;

/*CPU time = 6234 ms,  elapsed time = 7236 ms.*/
DELETE FROM @T

/* CPU time = 828 ms,  elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;

/*CPU time = 672 ms,  elapsed time = 980 ms.*/
DELETE FROM #T

DROP TABLE #T

Split string into individual words Java

Use split() method

Eg:

String s = "I want to walk my dog";
String[] arr = s.split(" ");    

for ( String ss : arr) {
    System.out.println(ss);
}

Instagram API: How to get all user media?

See http://instagram.com/developer/endpoints/ for information on pagination. You need to subsequentially step through the result pages, each time requesting the next part with the next_url that the result specifies in the pagination object.

Change status bar color with AppCompat ActionBarActivity

I'm not sure I understand the problem.

I you want to change the status bar color programmatically (and provided the device has Android 5.0) then you can use Window.setStatusBarColor(). It shouldn't make a difference whether the activity is derived from Activity or ActionBarActivity.

Just try doing:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(Color.BLUE);
}

Just tested this with ActionBarActivity and it works alright.


Note: Setting the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag programmatically is not necessary if your values-v21 styles file has it set already, via:

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>

ZIP file content type for HTTP request

If you want the MIME type for a file, you can use the following code:

- (NSString *)mimeTypeForPath:(NSString *)path
{
    // get a mime type for an extension using MobileCoreServices.framework

    CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
    assert(UTI != NULL);

    NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
    assert(mimetype != NULL);

    CFRelease(UTI);

    return mimetype;
}

In the case of a ZIP file, this will return application/zip.

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}

How to merge two json string in Python?

To append key-value pairs to a json string, you can use dict.update: dictA.update(dictB).

For your case, this will look like this:

dictA = json.loads(jsonStringA)
dictB = json.loads('{"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}')

dictA.update(dictB)
jsonStringA = json.dumps(dictA)

Note that key collisions will cause values in dictB overriding dictA.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).

How to log cron jobs?

If you'd still like to check your cron jobs you should provide a valid email account when setting the Cron jobs in cPanel.

When you specify a valid email you will receive the output of the cron job that is executed. Thus you will be able to check it and make sure everything has been executed correctly. Note that you will not receive an email if there is no output from the cron job command.

Please bear in mind that you will receive an email for each of the executed cron jobs. This may flood your inbox in case your crons run too often

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

Datepicker: How to popup datepicker when click on edittext

Try this

btn=(Button)findViewById(R.id.chs);
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setCanceledOnTouchOutside(true);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.setContentView(R.layout.datepickerdialog);
            dp=(DatePicker) dialog.findViewById(R.id.btp);
            dialog.show();
            ok=(Button)dialog.findViewById(R.id.btn1);
            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }

    });

Sum values in foreach loop php

In your case IF you want to go with foreach loop than

$sum = 0;
foreach($group as $key => $value) {
   $sum += $value; 
}
echo $sum;

But if you want to go with direct sum of array than look on below for your solution :

$total = array_sum($group);

for only sum of array looping is time wasting.

http://php.net/manual/en/function.array-sum.php

array_sum — Calculate the sum of values in an array

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9

get current date with 'yyyy-MM-dd' format in Angular 4

You can use date:'yyyy-MM-dd' pipe

curDate=new Date();

<p>{{curDate | date:'yyyy-MM-dd'}}</p>

Converting a view to Bitmap without displaying it in Android?

there is a way to do this. you have to create a Bitmap and a Canvas and call view.draw(canvas);

here is the code:

public static Bitmap loadBitmapFromView(View v) {
    Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
    Canvas c = new Canvas(b);
    v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    v.draw(c);
    return b;
}

if the view wasn't displayed before the size of it will be zero. Its possible to measure it like this:

if (v.getMeasuredHeight() <= 0) {
    v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    v.draw(c);
    return b;
}

EDIT: according to this post, Passing WRAP_CONTENT as value to makeMeasureSpec() doesn't to do any good (although for some view classes it does work), and the recommended method is:

// Either this
int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
// Or this
int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();

Replace given value in vector

Perhaps replace is what you are looking for:

> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1

Or, if you don't have x (any specific reason why not?):

replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)

Many people are familiar with gsub, so you can also try either of the following:

as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))

Update

After reading the comments, perhaps with is an option:

with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

How to create JSON object using jQuery

I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:

script.js

var yourObject = {
  test:'test 1',
  testData: [ 
    {testName: 'do',testId:''}
   ],
   testRcd:'value'   
};
var myString = 'newData='+JSON.stringify(yourObject);  //converts json to string and prepends the POST variable name
$.ajax({
   type: "POST",
   url: "buildJson.php", //the name and location of your php file
   data: myString,      //add the converted json string to a document.
   success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false;  //prevents the page from reloading. this helps if you want to bind this whole process to a click event.

buildJson.php

<?php
    $file = "data.json";  //name and location of json file. if the file doesn't exist, it   will be created with this name

    $fh = fopen($file, 'a');  //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.

    $new_data = $_POST["newData"]; //put POST data from ajax request in a variable

    fwrite($fh, $new_data);  //write the data with fwrite

    fclose($fh);  //close the dile
?>

Sound effects in JavaScript / HTML5

howler.js

For game authoring, one of the best solutions is to use a library which solves the many problems we face when writing code for the web, such as howler.js. howler.js abstracts the great (but low-level) Web Audio API into an easy to use framework. It will attempt to fall back to HTML5 Audio Element if Web Audio API is unavailable.

var sound = new Howl({
  urls: ['sound.mp3', 'sound.ogg']
}).play();
// it also provides calls for spatial/3d audio effects (most browsers)
sound.pos3d(0.1,0.3,0.5);

wad.js

Another great library is wad.js, which is especially useful for producing synth audio, such as music and effects. For example:

var saw = new Wad({source : 'sawtooth'})
saw.play({
    volume  : 0.8,
    wait    : 0,     // Time in seconds between calling play() and actually triggering the note.
    loop    : false, // This overrides the value for loop on the constructor, if it was set. 
    pitch   : 'A4',  // A4 is 440 hertz.
    label   : 'A',   // A label that identifies this note.
    env     : {hold : 9001},
    panning : [1, -1, 10],
    filter  : {frequency : 900},
    delay   : {delayTime : .8}
})

Sound for Games

Another library similar to Wad.js is "Sound for Games", it has more focus on effects production, while providing a similar set of functionality through a relatively distinct (and perhaps more concise feeling) API:

function shootSound() {
  soundEffect(
    1046.5,           //frequency
    0,                //attack
    0.3,              //decay
    "sawtooth",       //waveform
    1,                //Volume
    -0.8,             //pan
    0,                //wait before playing
    1200,             //pitch bend amount
    false,            //reverse bend
    0,                //random pitch range
    25,               //dissonance
    [0.2, 0.2, 2000], //echo array: [delay, feedback, filter]
    undefined         //reverb array: [duration, decay, reverse?]
  );
}

Summary

Each of these libraries are worth a look, whether you need to play back a single sound file, or perhaps create your own html-based music editor, effects generator, or video game.

Where is the .NET Framework 4.5 directory?

.NET 4.5 is an in place replacement for 4.0 - you will find the assemblies in the 4.0 directory.

See the blogs by Rick Strahl and Scott Hanselman on this topic.

You can also find the specific versions in:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework

Sorting A ListView By Column

i would recommend you to you datagridview, for heavy stuff.. it's include a lot of auto feature listviwe does not

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

Add string in a certain position in Python

Python 3.6+ using f-string:

mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

gives

'1362511338_314'

Session 'app' error while installing APK

In my case my device didn't have enough memory. After trying out a number of the suggestions here, I finally noticed the notification on my phone about low memory. The notification had been there for hours apparently.

How to check if a string starts with "_" in PHP?

function starts_with($s, $prefix){
    // returns a bool
    return strpos($s, $prefix) === 0;
}

starts_with($variable, "_");

Replace and overwrite instead of appending

Using python3 pathlib library:

import re
from pathlib import Path
import shutil

shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

Similar method using different approach to backups:

from pathlib import Path

filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

What is the easiest way to clear a database from the CLI with manage.py in Django?

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

How to get child process from parent process

To get the child process and thread, pstree -p PID. It also show the hierarchical tree

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.

How to calculate distance between two locations using their longitude and latitude value

Use the below method for calculating the distance of two different locations.

public double getKilometers(double lat1, double long1, double lat2, double long2) {
 double PI_RAD = Math.PI / 180.0;
 double phi1 = lat1 * PI_RAD;
 double phi2 = lat2 * PI_RAD;
 double lam1 = long1 * PI_RAD;
 double lam2 = long2 * PI_RAD;

return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));}

plain count up timer in javascript

Check this:

_x000D_
_x000D_
var minutesLabel = document.getElementById("minutes");_x000D_
var secondsLabel = document.getElementById("seconds");_x000D_
var totalSeconds = 0;_x000D_
setInterval(setTime, 1000);_x000D_
_x000D_
function setTime() {_x000D_
  ++totalSeconds;_x000D_
  secondsLabel.innerHTML = pad(totalSeconds % 60);_x000D_
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));_x000D_
}_x000D_
_x000D_
function pad(val) {_x000D_
  var valString = val + "";_x000D_
  if (valString.length < 2) {_x000D_
    return "0" + valString;_x000D_
  } else {_x000D_
    return valString;_x000D_
  }_x000D_
}
_x000D_
<label id="minutes">00</label>:<label id="seconds">00</label>
_x000D_
_x000D_
_x000D_

How do I get the list of keys in a Dictionary?

You should be able to just look at .Keys:

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    foreach (string key in data.Keys)
    {
        Console.WriteLine(key);
    }

How to make rectangular image appear circular with CSS

This one works well if you know height and width:

img {
  object-fit: cover;
  border-radius: '50%';
  width: 100px;
  height: 100px;
}

via https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87

Good Linux (Ubuntu) SVN client

See my question:

What is the best subversion client for Linux?

I also agree, GUI clients in linux suck.

I use subeclipse in Eclipse and RapidSVN in gnome.

How to write a JSON file in C#?

The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.

The following adds basic JSON indentation:

 string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

How do I update a Mongo document after inserting it?

I will use collection.save(the_changed_dict) this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.:

save(to_save[, manipulate=True[, safe=False[, **kwargs]]])

Save a document in this collection.

If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.

Install specific branch from github using Npm

I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:

"dependencies": {
  "<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}

How can I make the browser wait to display the page until it's fully loaded?

Immediately following your <body> tag add something like this...

 <style> body  {opacity:0;}</style>

And for the very first thing in your <head> add something like...

 <script>
  window.onload = function() {setTimeout(function(){document.body.style.opacity="100";},500);};
 </script>

As far as this being good practice or bad depends on your visitors, and the time the wait takes.

The question that is stil left open and I am not seeing any answers here is how to be sure the page has stabilized. For example if you are loading fonts the page may reflow a bit until all the fonts are loaded and displayed. I would like to know if there is an event that tells me the page is done rendering.

How do I clone a Django model instance object and save it to the database?

There's a clone snippet here, which you can add to your model which does this:

def clone(self):
  new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != old._meta.pk]);
  return self.__class__.objects.create(**new_kwargs)

Trying to SSH into an Amazon Ec2 instance - permission error

In windows,

  • Right click on the pem file. Then select properties.
  • Select security tab --> Click on Edit --> Remove all other user except current user
  • Go back to security tab again --> Click on Advanced --> Disable inheritance

Safely casting long to int in Java

I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception x and y, but not when they mean row and column (sometimes respectively)).

public static int intValue(long value) {
    int valueInt = (int)value;
    if (valueInt != value) {
        throw new IllegalArgumentException(
            "The long value "+value+" is not within range of the int type"
        );
    }
    return valueInt;
}

However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases IllegalArgumentException is almost certainly the wrong exception to be throwing as far as client code is concerned.

JavaScript to get rows count of a HTML table

This is another option, using jQuery and getting only tbody rows (with the data) and desconsidering thead/tfoot.

$("#tableId > tbody > tr").length

_x000D_
_x000D_
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
   width:100%;
   height:100%;
   border:1px solid #C0C0C0;
   border-collapse:collapse;
   border-spacing:2px;
   padding:5px;
}

.demo caption {
   caption-side:top;
   text-align:center;
}

.demo th {
   border:1px solid #C0C0C0;
   padding:5px;
   background:#F0F0F0;
}

.demo td {
   border:1px solid #C0C0C0;
   text-align:left;
   padding:5px;
   background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
   <caption>Table 1</caption>
   <thead>
      <tr>
         <th>Header 1</th>
         <th>Header 2</th>
         <th>Header 3</th>
         <th>Header 4</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
   </tbody>
   <tfoot>
      <tr>
         <td colspan=4 style="background:#F0F0F0">&nbsp; </td>
      </tr>
   </tfoot>
</table>
_x000D_
_x000D_
_x000D_

How to run eclipse in clean mode? what happens if we do so?

You can start Eclipse in clean mode from the command line:

eclipse -clean

How do I add a new sourceset to Gradle?

Update for 2021:

A lot has changed in 8ish years. Gradle continues to be a great tool. Now there's a whole section in the docs dedicated to configuring Integration Tests. I recommend you read the docs now.

Original Answer:

This took me a while to figure out and the online resources weren't great. So I wanted to document my solution.

This is a simple gradle build script that has an intTest source set in addition to the main and test source sets:

apply plugin: "java"

sourceSets {
    // Note that just declaring this sourceset creates two configurations.
    intTest {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
        }
    }
}

configurations {
    intTestCompile.extendsFrom testCompile
    intTestRuntime.extendsFrom testRuntime
}

task intTest(type:Test){
    description = "Run integration tests (located in src/intTest/...)."
    testClassesDir = project.sourceSets.intTest.output.classesDir
    classpath = project.sourceSets.intTest.runtimeClasspath
}

How to check if a file exists from a url

Hi according to our test between 2 different servers the results are as follows:

using curl for checking 10 .png files (each about 5 mb) was on average 5.7 secs. using header check for the same thing took average of 7.8 seconds!

So in our test curl was much faster if you have to check larger files!

our curl function is:

function remote_file_exists($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if( $httpCode == 200 ){return true;}
    return false;
}

here is our header check sample:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

What is the difference between Builder Design pattern and Factory Design pattern?

Builder and Abstract Factory have meant for different purposes. Depending on right use case, you have to select suitable design pattern.

Builder salient features:

  1. Builder pattern builds a complex object using simple objects and using a step by step approach
  2. A Builder class builds the final object step by step. This builder is independent of other objects
  3. Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
  4. Some of the parameters might be optional unlike in Factory which forces to send all parameters

Factory (simple Factory) salient features:

  1. Creational pattern
  2. Based on inheritance
  3. Factory returns a Factory Method (interface) which in turn returns Concrete Object
  4. You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
  5. Client always access interface only and you can hide object creation details in Factory method.

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex)

Have a look at related posts:

Keeping builder in separate class (fluent interface)

Design Patterns: Factory vs Factory method vs Abstract Factory

You can refer to below articles for more details:

sourcemaking

journaldev

How much memory can a 32 bit process access on a 64 bit operating system?

Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.

How to clear the cache in NetBeans

The cache is C:\Users\userName\AppData\Local\NetBeans\Cache\, and then the version name of the folder will specify the correct cache.

You can also do this: Close the IDE. Instead, of deleting files and risking everything, rename this cache folder. Now start the IDE. Once it starts, a new cache folder will be created since the folder is not found. Now you can delete the renamed folder safely.

How to clone object in C++ ? Or Is there another solution?

In C++ copying the object means cloning. There is no any special cloning in the language.

As the standard suggests, after copying you should have 2 identical copies of the same object.

There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.

Convert String To date in PHP

$d="05/Feb/2010:14:00:01";
$dr= date_create_from_format('d/M/Y:H:i:s', $d);
echo $dr->format('Y-m-d H:i:s');

here you get date string, give format specifier in ->format() according to format needed

accessing a docker container from another container

Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.

The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.

https://deis.com/blog/2016/connecting-docker-containers-1/

The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.

Example:

you named the db container db1 and the webserver container web0. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.

So if you have a web config file for your app, then for DB host you will use the name db1.

if you are using an older version of docker, then you should use --link.

Example:

Step 1: docker run --name db1 oracle/database:12.1.0.2-ee

then when you start the web app. use:

Step 2: docker run --name web0 --link db1 webapp/webapp:3.0

and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.

I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites

an example setup is like this:

file name is base.yml

version: "2"
services:
  webserver:
    image: "moodlehq/moodle-php-apache:7.1
    depends_on:
      - db
    volumes:
      - "/var/www/html:/var/www/html"
      - "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"
  db:
    image: postgres:9
    environment:
      POSTGRES_USER: moodle
      POSTGRES_PASSWORD: "m@0dl3ing"
      POSTGRES_DB: moodle
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"

this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.

IE docker-compose --name setup1 up base.yml

NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.

Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command

best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.

Example:

db.yml

version: "2"
services:
  webserver:
    environment:
      MOODLE_DOCKER_DBTYPE: oci
      MOODLE_DOCKER_DBNAME: XE
  db:
    image: moodlehq/moodle-db-oracle

Then call docker-compose --name setup1 up base.yml db.yml

This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.

I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.

NOTE: I did not use the --port command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.

UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.

Example:

docker network create test_network

The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network switch operator.

Example:

docker run \
    --detach \
    --name db1 \
    --network test_network \
    -e MYSQL_ROOT_PASSWORD="${DBPASS}" \
    -e MYSQL_DATABASE="${DBNAME}" \
    -e MYSQL_USER="${DBUSER}" \
    -e MYSQL_PASSWORD="${DBPASS}" \
    --tmpfs /var/lib/mysql:rw \
    mysql:5

Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1. You just have to make sure all containers are connected to the same network, and you are good to go.

For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh

Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

CSS3 selector :first-of-type with class name?

This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.

p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }

The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.

More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

TSQL Pivot without aggregate function

SELECT
main.CustomerID,
f.Data AS FirstName,
m.Data AS MiddleName,
l.Data AS LastName,
d.Data AS Date
FROM table main
INNER JOIN table f on f.CustomerID = main.CustomerID
INNER JOIN table m on m.CustomerID = main.CustomerID
INNER JOIN table l on l.CustomerID = main.CustomerID
INNER JOIN table d on d.CustomerID = main.CustomerID
WHERE f.DBColumnName = 'FirstName' 
AND m.DBColumnName = 'MiddleName' 
AND l.DBColumnName = 'LastName' 
AND d.DBColumnName = 'Date' 

Edit: I have written this without an editor & have not run the SQL. I hope, you get the idea.

How to escape JSON string?

Building on the answer by Dejan, what you can do is import System.Web.Helpers .NET Framework assembly, then use the following function:

static string EscapeForJson(string s) {
  string quoted = System.Web.Helpers.Json.Encode(s);
  return quoted.Substring(1, quoted.Length - 2);
}

The Substring call is required, since Encode automatically surrounds strings with double quotes.

How to clamp an integer to some range?

Whatever happened to my beloved readable Python language? :-)

Seriously, just make it a function:

def addInRange(val, add, minval, maxval):
    newval = val + add
    if newval < minval: return minval
    if newval > maxval: return maxval
    return newval

then just call it with something like:

val = addInRange(val, 7, 0, 42)

Or a simpler, more flexible, solution where you do the calculation yourself:

def restrict(val, minval, maxval):
    if val < minval: return minval
    if val > maxval: return maxval
    return val

x = restrict(x+10, 0, 42)

If you wanted to, you could even make the min/max a list so it looks more "mathematically pure":

x = restrict(val+7, [0, 42])

Call angularjs function using jquery/javascript

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});

removing html element styles via javascript

Completly removing style, not only set to NULL

document.getElementById("id").removeAttribute("style")

Pause in Python

On Windows 10 insert at beggining this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Strange, but it works for me! (Together with input() at the end, of course)

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

  1. override hashCode() and equals(..) using those 4 fields
  2. use new HashSet<Blog>(blogList) - this will give you a Set which has no duplicates by definition

Update: Since you can't change the class, here's an O(n^2) solution:

  • create a new list
  • iterate the first list
  • in an inner loop iterate the second list and verify if it has an element with the same fields

You can make this more efficient if you provide a HashSet data structure with externalized hashCode() and equals(..) methods.

Clear image on picturebox

You need the following:

pictbox.Image = null;
pictbox.update();

How do you change the width and height of Twitter Bootstrap's tooltips?

Just override bootstrap.css

The default value in BS2 is max-width:200px; So you can increase it with whatever fits your needs.

.tooltip-inner {
    max-width: 350px;
    /* If max-width does not work, try using width instead */
    width: 350px; 
}

How to check whether a int is not null or empty?

public class Demo {
    private static int i;
    private static Integer j;
    private static int k = -1;

    public static void main(String[] args) {
        System.out.println(i+" "+j+" "+k);
    }
}

OutPut: 0 null -1

Python: URLError: <urlopen error [Errno 10060]

The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.

You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.

For proxy issue, there are some material here:

Using an HTTP PROXY - Python

Why can't I get Python's urlopen() method to work on Windows?

Hope it helps!