Programs & Examples On #Meebo

How do I see the extensions loaded by PHP?

If you want to test if a particular extension is loaded you can also use the extension_loaded function, see documentation here

php -r "var_dump(extension_loaded('json'));"

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Java says FileNotFoundException but file exists

Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:

A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".

Hope this helps others save themselves some hair.

How to implement the Android ActionBar back button?

Make sure your the ActionBar Home Button is enabled in the Activity:

Android, API 5+:

@Override
public void onBackPressed() {
     ...
     super.onBackPressed();
}

ActionBarSherlock and App-Compat, API 7+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Android, API 11+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home: 
            // API 5+ solution
            onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

This way all the activities you want can have the backpress.

Android, API 16+:

http://developer.android.com/training/implementing-navigation/ancestral.html

AndroidManifest.xml:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- The meta-data element is needed for versions lower than 4.1 -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

How to search for an element in a golang slice

As other guys commented before you can write your own procedure with anonymous function to solve this issue.

I used two ways to solve it:

func Find(slice interface{}, f func(value interface{}) bool) int {
    s := reflect.ValueOf(slice)
    if s.Kind() == reflect.Slice {
        for index := 0; index < s.Len(); index++ {
            if f(s.Index(index).Interface()) {
                return index
            }
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 12,
    }) 
    
    idx := Find(destinationList, func(value interface{}) bool {
        return value.(UserInfo).UserId == userId
    })
    
    if idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

Second method with less computational cost:

func Search(length int, f func(index int) bool) int {
    for index := 0; index < length; index++ {
        if f(index) {
            return index
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 123,
    }) 
    
    idx := Search(len(destinationList), func(index int) bool {
        return destinationList[index].UserId == userId
    })
    
    if  idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

How to Change color of Button in Android when Clicked?

you can try this code to solve your problem

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android

How to change value of object which is inside an array using JavaScript or jQuery?

The power of javascript destructuring

_x000D_
_x000D_
const projects = [
  {
    value: 'jquery',
    label: 'jQuery',
    desc: 'the write less, do more, JavaScript library',
    icon: 'jquery_32x32.png',
    anotherObj: {
      value: 'jquery',
      label: 'jQuery',
      desc: 'the write less, do more, JavaScript library',
      icon: 'jquery_32x32.png',
    },
  },
  {
    value: 'jquery-ui',
    label: 'jQuery UI',
    desc: 'the official user interface library for jQuery',
    icon: 'jqueryui_32x32.png',
  },
  {
    value: 'sizzlejs',
    label: 'Sizzle JS',
    desc: 'a pure-JavaScript CSS selector engine',
    icon: 'sizzlejs_32x32.png',
  },
];

function createNewDate(date) {
  const newDate = [];
  date.map((obj, index) => {
    if (index === 0) {
      newDate.push({
        ...obj,
        value: 'Jquery??',
        label: 'Jquery is not that good',
        anotherObj: {
          ...obj.anotherObj,
          value: 'Javascript',
          label: 'Javascript',
          desc: 'Write more!!! do more!! with JavaScript',
          icon: 'javascript_4kx4k.4kimage',
        },
      });
    } else {
      newDate.push({
        ...obj,
      });
    }
  });

  return newDate;
}

console.log(createNewDate(projects));
_x000D_
_x000D_
_x000D_

What is the difference between declarations, providers, and import in NgModule?

Angular Concepts

  • imports makes the exported declarations of other modules available in the current module
  • declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
  • providers are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.

A special case for providers are lazy loaded modules that get their own child injector. providers of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html

  • exports makes the components, directives, and pipes available in modules that add this module to imports. exports can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.

  • entryComponents registers components for offline compilation so that they can be used with ViewContainerRef.createComponent(). Components used in router configurations are added implicitly.

TypeScript (ES2015) imports

import ... from 'foo/bar' (which may resolve to an index.ts) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.

Angular's @NgModule() imports and TypeScript import are entirely different concepts.

See also jDriven - TypeScript and ES6 import syntax

Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

Ajax post request in laravel 5 return error 500 (Internal Server Error)

Laravel 7.X In bootstrap.js, in axios related code, add:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');

Solved lot of unexplained 500 ajax errors. Of course it's for those who use axios

Add a pipe separator after items in an unordered list unless that item is the last on a line

Just

li + li::before {
    content: " | ";
}

Of course, this does not actually solve the OP's problem. He wants to elide the vertical bars at the beginning and end of lines depending on where they are broken. I will go out on a limb and assert that this problem is not solvable using CSS, and not even with JS unless one wants to essentially rewrite the browser engine's text-measurement/layout/line breaking logic.

The only pieces of CSS, as far as I can see, that "know" about line breaking are, first, the ::first-line pseudo element, which does not help us here--in any case, it is limited to a few presentational attributes, and does not work together with things like ::before and ::after. The only other aspect of CSS I can think of that to some extent exposes line-breaking is hyphenation. However, hyphenating is all about adding a character (usually a dash) to the end of lines in certain situations, whereas here we are concerned about removing a character (the vertical line), so I just can't see how to apply any kind of hyphenation-related logic, even with the help of properties such as hyphenate-character.

We have the word-spacing property, which is applied intra-line but not at line beginnings and endings, which seems promising, but it defines the width of the space between words, not the character(s) to be used.

One wonders if there's some way to use the text-overflow property, which has the little-known ability to take two values for display of overflow text at both left and right, as in

text-overflow: '' '';

but there still doesn't seem to be any obvious way to get from A to B here.

How to set default value for form field in Symfony2?

If you set 'data' in your creation form, this value will be not modified when edit your entity.

My solution is :

public function buildForm(FormBuilderInterface $builder, array $options) {
    // In my example, data is an associated array
    $data = $builder->getData();

    $builder->add('myfield', 'text', array(
     'label' => 'Field',
     'data' => array_key_exits('myfield', $data) ? $data['myfield'] : 'Default value',
    ));
}

Bye.

T-SQL and the WHERE LIKE %Parameter% clause

The correct answer is, that, because the '%'-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName (be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'

or, in your example:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'

Why use static_cast<int>(x) instead of (int)x?

One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

solve this issue for angular

"styles": [
              "src/styles.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

Android Paint: .measureText() vs .getTextBounds()

The different between getTextBounds and measureText is described with the image below.

In short,

  1. getTextBounds is to get the RECT of the exact text. The measureText is the length of the text, including the extra gap on the left and right.

  2. If there are spaces between the text, it is measured in measureText but not including in the length of the TextBounds, although the coordinate get shifted.

  3. The text could be tilted (Skew) left. In this case, the bounding box left side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText

  4. The text could be tilted (Skew) right. In this case, the bounding box right side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText

enter image description here

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

Android Lint contentDescription warning

Since it is only a warning you can suppress it. Go to your XML's Graphical Layout and do this:

  1. Click on the right top corner red button

    enter image description here

  2. Select "Disable Issue Type" (for example)

    enter image description here

Is there a function in python to split a word into a list?

def count(): list = 'oixfjhibokxnjfklmhjpxesriktglanwekgfvnk'

word_list = []
# dict = {}
for i in range(len(list)):
    word_list.append(list[i])
# word_list1 = sorted(word_list)
for i in range(len(word_list) - 1, 0, -1):
    for j in range(i):
        if word_list[j] > word_list[j + 1]:
            temp = word_list[j]
            word_list[j] = word_list[j + 1]
            word_list[j + 1] = temp
print("final count of arrival of each letter is : \n", dict(map(lambda x: (x, word_list.count(x)), word_list)))

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I was getting this error when I tried to checkout new branch:

error: pathspec 'BRANCH-NAME' did not match any file(s) known to git.

When I tried git checkout origin/<BRANCH-NAME>, I got the detached HEAD:

(detached from origin/)

Finally, I did the following to resolve the issue:

git remote update
git fetch 
git checkout --track origin/<BRANCH-NAME>

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

AngularJS : When to use service instead of factory

Services

Syntax: module.service( 'serviceName', function ); Result: When declaring serviceName as an injectable argument you will be provided the actual function reference passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

Providers

Syntax: module.provider( 'providerName', function );

Result: When declaring providerName as an injectable argument you will be provided the value that is returned by invoking the $get method of the function reference passed to module.provider.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances but that requires some sort of configuration before being injected. Perhaps useful for classes that are reusable across projects? Still kind of hazy on this one.

Python: Is there an equivalent of mid, right, and left from BASIC?

These work great for reading left / right "n" characters from a string, but, at least with BBC BASIC, the LEFT$() and RIGHT$() functions allowed you to change the left / right "n" characters too...

E.g.:

10 a$="00000"
20 RIGHT$(a$,3)="ABC"
30 PRINT a$

Would produce:

00ABC

Edit : Since writing this, I've come up with my own solution...

def left(s, amount = 1, substring = ""):
    if (substring == ""):
        return s[:amount]
    else:
        if (len(substring) > amount):
            substring = substring[:amount]
        return substring + s[:-amount]

def right(s, amount = 1, substring = ""):
    if (substring == ""):
        return s[-amount:]
    else:
        if (len(substring) > amount):
            substring = substring[:amount]
        return s[:-amount] + substring

To return n characters you'd call

substring = left(string,<n>)

Where defaults to 1 if not supplied. The same is true for right()

To change the left or right n characters of a string you'd call

newstring = left(string,<n>,substring)

This would take the first n characters of substring and overwrite the first n characters of string, returning the result in newstring. The same works for right().

Are there such things as variables within an Excel formula?

You could store intermediate values in a cell or column (which you could hide if you choose)

C1: = VLOOKUP(A1, B:B, 1, 0)
D1: = IF(C1 > 10, C1 - 10, C1)

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

I use the AdWords API, and sometimes I have the same problem. My solution is to add ini_set('default_socket_timeout', 900); on the file vendor\googleads\googleads-php-lib\src\Google\AdsApi\AdsSoapClient.php line 65

and in the vendor\googleads-php-lib\src\Google\AdsApi\Adwords\Reporting\v201702\ReportDownloader.php line 126 ini_set('default_socket_timeout', 900); $requestOptions['stream_context']['http']['timeout'] = "900";

Google package overwrite the default php.ini parameter.

Sometimes, the page could connect to 'https://adwords.google.com/ap i/adwords/mcm/v201702/ManagedCustomerService?wsdl and sometimes no. If the page connects once, The WSDL cache will contain the same page, and the program will be ok until the code refreshes the cache...

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

How can I create a progress bar in Excel VBA?

There have been many other great posts, however I'd like to say that theoretically you should be able to create a REAL progress bar control:

  1. Use CreateWindowEx() to create the progress bar

A C++ example:

hwndPB = CreateWindowEx(0, PROGRESS_CLASS, (LPTSTR) NULL, WS_CHILD | WS_VISIBLE, rcClient.left,rcClient.bottom - cyVScroll,rcClient.right, cyVScroll,hwndParent, (HMENU) 0, g_hinst, NULL);

hwndParent Should be set to the parent window. For that one could use the status bar, or a custom form! Here's the window structure of Excel found from Spy++:

enter image description here

This should therefore be relatively simple using FindWindowEx() function.

hwndParent = FindWindowEx(Application.hwnd,,"MsoCommandBar","Status Bar")

After the progress bar has been created you must use SendMessage() to interact with the progress bar:

Function MAKELPARAM(ByVal loWord As Integer, ByVal hiWord As Integer)
    Dim lparam As Long
    MAKELPARAM = loWord Or (&H10000 * hiWord)
End Function

SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, 100))
SendMessage(hwndPB, PBM_SETSTEP, 1, 0)
For i = 1 to 100
    SendMessage(hwndPB, PBM_STEPIT, 0, 0) 
Next
DestroyWindow(hwndPB)

I'm not sure how practical this solution is, but it might look somewhat more 'official' than other methods stated here.

Sort Dictionary by keys

In Swift 5, in order to sort Dictionary by KEYS

let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.0 < $1.0 })

In order to sort Dictionary by VALUES

let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.1 < $1.1 })

Vue.js dynamic images not working

Tried all of the answers here but what worked for me on Vue2 is like this.

<div class="col-lg-2" v-for="pic in pics">
   <img :src="require(`../assets/${pic.imagePath}.png`)" :alt="pic.picName">
</div>

JQuery Parsing JSON array

Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.

How to remove padding around buttons in Android?

It's not a padding but or the shadow of the background drawable or a problem with the minHeight and minWidth.

If you still want the nice ripple affect, you can make your own button style using the ?attr/selectableItemBackground:

<style name="Widget.AppTheme.MyCustomButton" parent="Widget.AppCompat.Button.Borderless">
    <item name="android:minHeight">0dp</item>
    <item name="android:minWidth">0dp</item>
    <item name="android:layout_height">48dp</item>
    <item name="android:background">?attr/selectableItemBackground</item>
</style>

And apply it to the button:

<Button 
    style="@style/Widget.AppTheme.MyCustomButton"
    ... />

Should I use Java's String.format() if performance is important?

The answer to this depends very much on how your specific Java compiler optimizes the bytecode it generates. Strings are immutable and, theoretically, each "+" operation can create a new one. But, your compiler almost certainly optimizes away interim steps in building long strings. It's entirely possible that both lines of code above generate the exact same bytecode.

The only real way to know is to test the code iteratively in your current environment. Write a QD app that concatenates strings both ways iteratively and see how they time out against each other.

AngularJS $resource RESTful example

you can just do $scope.todo = Todo.get({ id: 123 }). .get() and .query() on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

How to properly make a http web GET request

Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

GET async

public async Task<string> GetAsync(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

POST
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        requestBody.Write(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

    

POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

Reading Xml with XmlReader in C#

My experience of XmlReader is that it's very easy to accidentally read too much. I know you've said you want to read it as quickly as possible, but have you tried using a DOM model instead? I've found that LINQ to XML makes XML work much much easier.

If your document is particularly huge, you can combine XmlReader and LINQ to XML by creating an XElement from an XmlReader for each of your "outer" elements in a streaming manner: this lets you do most of the conversion work in LINQ to XML, but still only need a small portion of the document in memory at any one time. Here's some sample code (adapted slightly from this blog post):

static IEnumerable<XElement> SimpleStreamAxis(string inputUrl,
                                              string elementName)
{
  using (XmlReader reader = XmlReader.Create(inputUrl))
  {
    reader.MoveToContent();
    while (reader.Read())
    {
      if (reader.NodeType == XmlNodeType.Element)
      {
        if (reader.Name == elementName)
        {
          XElement el = XNode.ReadFrom(reader) as XElement;
          if (el != null)
          {
            yield return el;
          }
        }
      }
    }
  }
}

I've used this to convert the StackOverflow user data (which is enormous) into another format before - it works very well.

EDIT from radarbob, reformatted by Jon - although it's not quite clear which "read too far" problem is being referred to...

This should simplify the nesting and take care of the "a read too far" problem.

using (XmlReader reader = XmlReader.Create(inputUrl))
{
    reader.ReadStartElement("theRootElement");

    while (reader.Name == "TheNodeIWant")
    {
        XElement el = (XElement) XNode.ReadFrom(reader);
    }

    reader.ReadEndElement();
}

This takes care of "a read too far" problem because it implements the classic while loop pattern:

initial read;
(while "we're not at the end") {
    do stuff;
    read;
}

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Android Marshmallow many methods are deprecated.

For example, to get color use

ContextCompat.getColor(context, R.color.color_name);

Also to get drawable use

ContextCompat.getDrawable(context, R.drawable.drawble_name);

Adding placeholder attribute using Jquery

This line of code might not work in IE 8 because of native support problems.

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.

$('input, textarea').placeholder();

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

anaconda update all possible packages?

To update all possible packages I used conda update --update-all

It works!

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Initialization of all elements of an array to one default value in C++?

In the C++ programming language V4, Stroustrup recommends using vectors or valarrays over builtin arrays. With valarrary's, when you create them, you can init them to a specific value like:

valarray <int>seven7s=(7777777,7);

To initialize an array 7 members long with "7777777".

This is a C++ way of implementing the answer using a C++ data structure instead of a "plain old C" array.

I switched to using the valarray as an attempt in my code to try to use C++'isms v. C'isms....

Toolbar navigation icon never set

Currently you can use it, changing the order: (it seems to be a bug)

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);

toolbar.setNavigationIcon(R.drawable.ic_good);
toolbar.setTitle("Title");
toolbar.setSubtitle("Sub");
toolbar.setLogo(R.drawable.ic_launcher);

How do I list all tables in a schema in Oracle SQL?

If you need to get the size of the table as well, this will be handy:

select SEGMENT_NAME, PARTITION_NAME, BYTES from user_segments where SEGMENT_TYPE='TABLE' order by 1

How can I tell Moq to return a Task?

Your method doesn't have any callbacks so there is no reason to use .CallBack(). You can simply return a Task with the desired values using .Returns() and Task.FromResult, e.g.:

MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.FromResult(someValue));

Update 2014-06-22

Moq 4.2 has two new extension methods to assist with this.

mock.Setup(arg=>arg.DoSomethingAsync())
    .ReturnsAsync(someValue);

mock.Setup(arg=>arg.DoSomethingAsync())        
    .ThrowsAsync(new InvalidOperationException());

Update 2016-05-05

As Seth Flowers mentions in the other answer, ReturnsAsync is only available for methods that return a Task<T>. For methods that return only a Task,

.Returns(Task.FromResult(default(object)))

can be used.

As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);, e.g.:

mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.CompletedTask);

How do you loop through each line in a text file using a windows batch file?

To print all lines in text file from command line (with delayedExpansion):

set input="path/to/file.txt"

for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!)

Works with leading whitespace, blank lines, whitespace lines.

Tested on Win 10 CMD

Test text

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:

$('input[type=file]').change(function () {
    console.log(this.files[0].mozFullPath);
});

http://jsfiddle.net/SCK5A/

So don't waste your time.

edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

As Daniel A. White said in his comment, the OPTIONS request is most likely created by the client as part of a cross domain JavaScript request. This is done automatically by Cross Origin Resource Sharing (CORS) compliant browsers. The request is a preliminary or pre-flight request, made before the actual AJAX request to determine which request verbs and headers are supported for CORS. The server can elect to support it for none, all or some of the HTTP verbs.

To complete the picture, the AJAX request has an additional "Origin" header, which identified where the original page which is hosting the JavaScript was served from. The server can elect to support request from any origin, or just for a set of known, trusted origins. Allowing any origin is a security risk since is can increase the risk of Cross site Request Forgery (CSRF).

So, you need to enable CORS.

Here is a link that explains how to do this in ASP.Net Web API

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

The implementation described there allows you to specify, amongst other things

  • CORS support on a per-action, per-controller or global basis
  • The supported origins
  • When enabling CORS a a controller or global level, the supported HTTP verbs
  • Whether the server supports sending credentials with cross-origin requests

In general, this works fine, but you need to make sure you are aware of the security risks, especially if you allow cross origin requests from any domain. Think very carefully before you allow this.

In terms of which browsers support CORS, Wikipedia says the following engines support it:

  • Gecko 1.9.1 (FireFox 3.5)
  • WebKit (Safari 4, Chrome 3)
  • MSHTML/Trident 6 (IE10) with partial support in IE8 and 9
  • Presto (Opera 12)

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Browser_support

How to make readonly all inputs in some div in Angular2?

Just set css property of container div 'pointer-events' as none i.e. 'pointer-events:none;'

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

Npm install failed with "cannot run in wd"

OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.

I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.

This article provides a very clear step-by-step instruction of how to do so:

https://www.digitalocean.com/community/tutorials/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04

How to properly add cross-site request forgery (CSRF) token using PHP

Security Warning: md5(uniqid(rand(), TRUE)) is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.

Looks like you need an else with your if.

if (!isset($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
}
else
{
    $token = $_SESSION['token'];
}

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

I think this thread actually has the easiest, cleanest solution, that does not sacrifice the JSON martialing tools that Spring provides:

https://stackoverflow.com/a/16986372/1278921

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

How to get a variable type in Typescript?

I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof

if(task.id instanceof UUID) {
  //foo
}

What is the meaning of prepended double colon "::"?

Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:

/path/to/executable

This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...

::std::cout

...is equally explicit in the C++ namespace "tree".

Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...

X11/xterm

...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...

std::cout

...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.

Noteworthy differences:

1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.

2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.

3) C++ always searches the global namespace (like having / implicitly your PATH).

General discussion on namespaces and explicitness of symbols

Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.

As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.

So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

pull access denied repository does not exist or may require docker login

I had the same issue

pull access denied for microsoft/mmsql-server-linux, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

Turns out the DockerHub was moved to a different name So I would suggest you re check-in docker hub

How to set order of repositories in Maven settings.xml

As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.

As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.

Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851

View the change history of a file using Git versioning

For a graphical view I'd use gitk:

gitk [filename]

or to follow filename past renames

gitk --follow [filename]

state machines tutorials

State machines are not something that inherently needs a tutorial to be explained or even used. What I suggest is that you take a look at the data and how it needs to be parsed.

For example, I had to parse the data protocol for a Near Space balloon flight computer, it stored data on the SD card in a specific format (binary) which needed to be parsed out into a comma seperated file. Using a state machine for this makes the most sense because depending on what the next bit of information is we need to change what we are parsing.

The code is written using C++, and is available as ParseFCU. As you can see, it first detects what version we are parsing, and from there it enters two different state machines.

It enters the state machine in a known-good state, at that point we start parsing and depending on what characters we encounter we either move on to the next state, or go back to a previous state. This basically allows the code to self-adapt to the way the data is stored and whether or not certain data exists at all even.

In my example, the GPS string is not a requirement for the flight computer to log, so processing of the GPS string may be skipped over if the ending bytes for that single log write is found.

State machines are simple to write, and in general I follow the rule that it should flow. Input going through the system should flow with certain ease from state to state.

How to initialize var?

A var cannot be set to null since it needs to be statically typed.

var foo = null;
// compiler goes: "Huh, what's that type of foo?"

However, you can use this construct to work around the issue:

var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."

I don't know for sure, but from what I heard you can also use dynamic instead of var. This does not require static typing.

dynamic foo = null;
foo = "hi";

Also, since it was not clear to me from the question if you meant the varkeyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:

string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable

But you cannot do this:

int i = null; // integers cannot contain null

RestClientException: Could not extract response. no suitable HttpMessageConverter found

I was trying to use Feign, while I encounter same issue, As I understood HTTP message converter will help but wanted to understand how to achieve this.

@FeignClient(name = "mobilesearch", url = "${mobile.search.uri}" ,
        fallbackFactory = MobileSearchFallbackFactory.class,
        configuration = MobileSearchFeignConfig.class)
public interface MobileSearchClient {

    @RequestMapping(method = RequestMethod.GET)
    List<MobileSearchResponse> getPhones();
}

You have to use Customer Configuration for the decoder, MobileSearchFeignConfig,

public class MobileSearchFeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
    }

    public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
        return new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return httpMessageConverters;
            }
        };
    }

    public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
        MappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
            setSupportedMediaTypes(mediaTypes);
        }
    }

}

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

I'm a PostgreSQL DBA, as far as I could understand the difference between outer or not outer joins difference is a topic that has considerable discussion all around the internet. Until today I never saw a difference between those two; So I went further and I try to find the difference between those. At the end I read the whole documentation about it and I found the answer for this,

So if you look on documentation (at least in PostgreSQL) you can find this phrase:

"The words INNER and OUTER are optional in all forms. INNER is the default; LEFT, RIGHT, and FULL imply an outer join."

In another words,

LEFT JOIN and LEFT OUTER JOIN ARE THE SAME

RIGHT JOIN and RIGHT OUTER JOIN ARE THE SAME

I hope it can be a contribute for those who are still trying to find the answer.

Can an Android Toast be longer than Toast.LENGTH_LONG?

If you need a long Toast, there's a practical alternative, but it requires your user to click on an OK button to make it go away. You can use an AlertDialog like this:

String message = "This is your message";
new AlertDialog.Builder(YourActivityName.this)
    .setTitle("Optional Title (you can omit this)")
    .setMessage(message)
    .setPositiveButton("ok", null)
    .show();

If you have a long message, chances are, you don't know how long it will take for your user to read the message, so sometimes it is a good idea to require your user to click on an OK button to continue. In my case, I use this technique when a user clicks on a help icon.

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;

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

How to create Python egg file

For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.

python myapp.zip

Where myapp.zip is a zip containing a __main__.py file which is executed as the script file to be executed. Your package dependencies can also be included in the file:

__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py

You can also execute an egg, but the incantation is not as nice:

# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows 
set PYTHONPATH=myapp.egg
python -m myapp

This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:

myapp/__init__.py
myapp/somelibfile.py

And python will run __init__.py (you should check that __file__=='__main__' in your app for command line use).

Egg files are just zip files so you might be able to add __main__.py to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg instead of the above incantation where the PYTHONPATH environment variable is set.

More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.

Connecting to SQL Server using windows authentication

use this code

Data Source=.;Initial Catalog=master;Integrated Security=True

Getting the first and last day of a month, using a given DateTime object

Here you can add one month for the first day of current month than delete 1 day from that day.

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

if ($name )
{
    #since undef and '' both evaluate to false 
    #this should work only when string is defined and non-empty...
    #unless you're expecting someting like $name="0" which is false.
    #notice though that $name="00" is not false
}

Implementing a HashMap in C

The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.

But here is source code example of An Hashmap Implementation in C

How to create a session using JavaScript?

<script type="text/javascript">
function myfunction()
{
    var IDSes= "10200";
    '<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
    '<%Session["IDSes"] = "' + IDSes+ '"; %>';
     alert('<%=Session["IDSes"] %>');
}
</script>

link

Why do you need to put #!/bin/bash at the beginning of a script file?

It's a convention so the *nix shell knows what kind of interpreter to run.

For example, older flavors of ATT defaulted to sh (the Bourne shell), while older versions of BSD defaulted to csh (the C shell).

Even today (where most systems run bash, the "Bourne Again Shell"), scripts can be in bash, python, perl, ruby, PHP, etc, etc. For example, you might see #!/bin/perl or #!/bin/perl5.

PS: The exclamation mark (!) is affectionately called "bang". The shell comment symbol (#) is sometimes called "hash".

PPS: Remember - under *nix, associating a suffix with a file type is merely a convention, not a "rule". An executable can be a binary program, any one of a million script types and other things as well. Hence the need for #!/bin/bash.

Take the content of a list and append it to another list

That seems fairly reasonable for what you're trying to do.

A slightly shorter version which leans on Python to do more of the heavy lifting might be:

for logs in mydir:

    for line in mylog:
        #...if the conditions are met
        list1.append(line)

    if any(True for line in list1 if "string" in line):
        list2.extend(list1)
    del list1

    ....

The (True for line in list1 if "string" in line) iterates over list and emits True whenever a match is found. any() uses short-circuit evaluation to return True as soon as the first True element is found. list2.extend() appends the contents of list1 to the end.

How to Automatically Close Alerts using Twitter Bootstrap

I needed a very simple solution to hide something after sometime and managed to get this to work:

In angular you can do this:

$timeout(self.hideError,2000);

Here is the function that i call when the timeout has been reached

 self.hideError = function(){
   self.HasError = false;
   self.ErrorMessage = '';
};

So now my dialog/ui can use those properties to hide elements.

MySQL string replace

Yes, MySQL has a REPLACE() function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

Note that it's easier if you make that an alias when using SELECT

SELECT REPLACE(string_column, 'search', 'replace') as url....

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

How to know if an object has an attribute in Python

I would like to suggest avoid this:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

The user @jpalecek mentioned it: If an AttributeError occurs inside doStuff(), you are lost.

Maybe this approach is better:

try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)

Notification Icon with the new Firebase Cloud Messaging system

Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.

With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:

<meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/google_blue" />

Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.

Cause of No suitable driver found for

If you look at your original connection string:

<property name="url" value="jdbc:hsqldb:hsql://localhost"/>

The Hypersonic docs suggest that you're missing an alias after localhost:

http://hsqldb.org/doc/guide/ch04.html

How to Apply Gradient to background view of iOS Swift App

One thing I noticed is you can't add a gradient to a UILabel without clearing the text. One simple workaround is to use a UIButton and disable user interaction.

How to add external fonts to android application

You can use the custom TextView for whole app with custom font here is an example for that

public class MyTextView extends TextView {

   Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
   Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(),  Constants.FONT_BOLD);

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

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

   public MyTextView(Context context) {
       super(context);
   }

   public void setTypeface(Typeface tf, int style) {
       if (style == Typeface.BOLD) {
           super.setTypeface(boldTypeface/*, -1*/);
       } else {
           super.setTypeface(normalTypeface/*, -1*/);
       }
   }
}

Throw HttpResponseException or return Request.CreateErrorResponse?

I like Oppositional answer

Anyway, I needed a way to catch the inherited Exception and that solution doesn't satisfy all my needs.

So I ended up changing how he handles OnException and this is my version

public override void OnException(HttpActionExecutedContext actionExecutedContext) {
   if (actionExecutedContext == null || actionExecutedContext.Exception == null) {
      return;
   }

   var type = actionExecutedContext.Exception.GetType();

   Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;

   if (!this.Handlers.TryGetValue(type, out registration)) {
      //tento di vedere se ho registrato qualche eccezione che eredita dal tipo di eccezione sollevata (in ordine di registrazione)
      foreach (var item in this.Handlers.Keys) {
         if (type.IsSubclassOf(item)) {
            registration = this.Handlers[item];
            break;
         }
      }
   }

   //se ho trovato un tipo compatibile, uso la sua gestione
   if (registration != null) {
      var statusCode = registration.Item1;
      var handler = registration.Item2;

      var response = handler(
         actionExecutedContext.Exception.GetBaseException(),
         actionExecutedContext.Request
      );

      // Use registered status code if available
      if (statusCode.HasValue) {
         response.StatusCode = statusCode.Value;
      }

      actionExecutedContext.Response = response;
   }
   else {
      // If no exception handler registered for the exception type, fallback to default handler
      actionExecutedContext.Response = DefaultHandler(actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
      );
   }
}

The core is this loop where I check if the exception type is a subclass of a registered type.

foreach (var item in this.Handlers.Keys) {
    if (type.IsSubclassOf(item)) {
        registration = this.Handlers[item];
        break;
    }
}

my2cents

How to do something to each file in a directory with a batch script

Command line usage:

for /f %f in ('dir /b c:\') do echo %f

Batch file usage:

for /f %%f in ('dir /b c:\') do echo %%f

Update: if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char.

for /f "delims=|" %%f in ('dir /b c:\') do echo %%f

Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq option on the for:

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f

And if you need to use output redirection or command piping, use the escape char (^):

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f

How to set base url for rest in spring boot?

server.servlet.context-path=/api would be the solution I guess. I had the same issue and this got me solved. I used server.context-path. However, that seemed to be deprecated and I found that server.servlet.context-path solves the issue now. Another workaround I found was adding a base tag to my front end (H5) pages. I hope this helps someone out there.

Cheers

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

JavaScript OR (||) variable assignment explanation

According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

He also suggests another use for it (quoted): "lightweight normalization of cross-browser differences"

// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

I had this error, too. I thought everything was setup correctly, but I found out that one thing was missing: The host name I used for my project was not (yet) resolvable.

Since my app determines the current client's name from the host name I used a host name like clientname.mysuperapp.local for development. When I added the development host name to my hosts file, the project was loadable again. Obviously, I had to this anyway, but I haven't thought that VS checks the host name before loading the project.

Convert base-2 binary number string to int

If you are using python3.6 or later you can use f-string to do the conversion:

Binary to decimal:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.

In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.

How to debug a GLSL shader?

I have found Transform Feedback to be a useful tool for debugging vertex shaders. You can use this to capture the values of VS outputs, and read them back on the CPU side, without having to go through the rasterizer.

Here is another link to a tutorial on Transform Feedback.

Component is part of the declaration of 2 modules

IN Angular 4. This error is considered as ng serve run time cache issue.

case:1 this error will occur, once you import the component in one module and again import in sub modules will occur.

case:2 Import one Component in wrong place and removed and replaced in Correct module, That time it consider as ng serve cache issue. Need to Stop the project and start -do again ng serve, It will work as expected.

lambda expression for exists within list

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

SQL query to check if a name begins and ends with a vowel

Try this for beginning with vowel

Oracle:

select distinct *field* from *tablename* where SUBSTR(*sort field*,1,1) IN('A','E','I','O','U') Order by *Sort Field*;

Htaccess: add/remove trailing slash from URL

To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]


For the sake of completeness, here is an alternative emphasizing that REQUEST_URI starts with a slash (at least in .htaccess files):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it

Just don't use %{REQUEST_URI} (.*)/$. Because in the root directory REQUEST_URI equals /, the leading slash, and it would be misinterpreted as a trailing slash.


If you are interested in more reading:

(update: this technique is now implemented in Laravel 5.5)

Difference between static class and singleton pattern?

The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

How to replace list item in best way

You could make it more readable and more efficient:

string oldValue = valueFieldValue.ToString();
string newValue = value.ToString();
int index = listofelements.IndexOf(oldValue);
if(index != -1)
    listofelements[index] = newValue;

This asks only once for the index. Your approach uses Contains first which needs to loop all items(in the worst case), then you're using IndexOf which needs to enumerate the items again .

WPF User Control Parent

Use VisualTreeHelper.GetParent or the recursive function below to find the parent window.

public static Window FindParentWindow(DependencyObject child)
{
    DependencyObject parent= VisualTreeHelper.GetParent(child);

    //CHeck if this is the end of the tree
    if (parent == null) return null;

    Window parentWindow = parent as Window;
    if (parentWindow != null)
    {
        return parentWindow;
    }
    else
    {
        //use recursion until it reaches a Window
        return FindParentWindow(parent);
    }
}

How can I get sin, cos, and tan to use degrees instead of radians?

Multiply the input by Math.PI/180 to convert from degrees to radians before calling the system trig functions.

You could also define your own functions:

function sinDegrees(angleDegrees) {
    return Math.sin(angleDegrees*Math.PI/180);
};

and so on.

Read each line of txt file to new array element

This has been covered here quite well, but if you REALLY need even better performance than anything listed here, you can use this approach that uses strtok.

$Names_Keys = [];
$Name = strtok(file_get_contents($file), "\n");
while ($Name !== false) {
    $Names_Keys[$Name] = 0;
    $Name = strtok("\n");
}

Note, this assumes your file is saved with \n as the newline character (you can update that as need be), and it also stores the words/names/lines as the array keys instead of the values, so that you can use it as a lookup table, allowing the use of isset (much, much faster), instead of in_array.

Installing specific laravel version with composer create-project

To install specific version of laravel try this & simply command on terminal

composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}

How can I keep Bootstrap popovers alive while being hovered?

Here is a solution I devised that seems to work well while also allowing you to use the normal Bootstrap implementation for turning on all popovers.

Original fiddle: https://jsfiddle.net/eXpressive/hfear592/

Ported to this question:

<a href="#" id="example" class="btn btn-danger" rel="popover" >hover for popover</a>

$('#example').popover({
    html : true,
    trigger : 'hover',
    content : function() {
        return '<div class="box"></div>';
    }
}).on('hide.bs.popover', function () {
    if ($(".popover:hover").length) {
      return false;
    }                
}); 

$('body').on('mouseleave', '.popover', function(){
    $('.popover').popover('hide');
});

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

<form action="" method="POST" enctype="multipart/form-data">
  Select image to upload:
  <input type="file"   name="file[]" multiple/>
  <input type="submit" name="submit" value="Upload Image" />
</form>

Using FOR Loop

<?php    
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    for ($x = 0; $x < count($_FILES['file']['name']); $x++) {               

      $file_name   = $_FILES['file']['name'][$x];
      $file_tmp    = $_FILES['file']['tmp_name'][$x];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }    
?>

Using FOREACH Loop

<?php
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    foreach ($_FILES['file']['name'] as $key => $value) {                   

      $file_name   = $_FILES['file']['name'][$key];
      $file_tmp    = $_FILES['file']['tmp_name'][$key];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }
?>

Import Maven dependencies in IntelliJ IDEA

Reimport the project. If you install maven plugin you can use this.

Right click on the project -> Maven -> Reimport

using jquery $.ajax to call a PHP function

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:

$.ajax({ url: '/my/site',
         data: {action: 'test'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
        case 'blah' : blah();break;
        // ...etc...
    }
}

I believe that's a simple incarnation of the Command pattern.

Loop in Jade (currently known as "Pug") template engine

You could also speed things up with a while loop (see here: http://jsperf.com/javascript-while-vs-for-loops). Also much more terse and legible IMHO:

i = 10
while(i--)
    //- iterate here
    div= i

Winforms TableLayoutPanel adding rows programmatically

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        Dim dc As DataColumn
        dc = New DataColumn("Question", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)

        dc = New DataColumn("Ans1", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans2", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans3", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans4", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("AnsType", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)


        Dim Dr As DataRow
        Dr = dt.NewRow
        Dr("Question") = "What is Your Name"
        Dr("Ans1") = "Ravi"
        Dr("Ans2") = "Mohan"
        Dr("Ans3") = "Sohan"
        Dr("Ans4") = "Gopal"
        Dr("AnsType") = "Multi"
        dt.Rows.Add(Dr)

        Dr = dt.NewRow
        Dr("Question") = "What is your father Name"
        Dr("Ans1") = "Ravi22"
        Dr("Ans2") = "Mohan2"
        Dr("Ans3") = "Sohan2"
        Dr("Ans4") = "Gopal2"
        Dr("AnsType") = "Multi"
        dt.Rows.Add(Dr)
        Panel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows
        Panel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
        Panel1.BackColor = Color.Azure
        Panel1.RowStyles.Insert(0, New RowStyle(SizeType.Absolute, 50))
        Dim i As Integer = 0

        For Each dri As DataRow In dt.Rows



            Dim lab As New Label()
            lab.Text = dri("Question")
            lab.AutoSize = True

            Panel1.Controls.Add(lab, 0, i)


            Dim Ans1 As CheckBox
            Ans1 = New CheckBox()
            Ans1.Text = dri("Ans1")
            Panel1.Controls.Add(Ans1, 1, i)

            Dim Ans2 As RadioButton
            Ans2 = New RadioButton()
            Ans2.Text = dri("Ans2")
            Panel1.Controls.Add(Ans2, 2, i)
            i = i + 1

            'Panel1.Controls.Add(Pan)
        Next

How to fix UITableView separator on iOS 7?

UITableView has a property separatorInset. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.

[tableView setSeparatorInset:UIEdgeInsetsZero];

Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

Apache VirtualHost 403 Forbidden

This may be a permissions problem.

every single parent path to the virtual document root must be Readable, Writable, and Executable by the web server httpd user

according to this page about Apache 403 errors.

Since you're using Allow from all, your order shouldn't matter, but you might try switching it to Deny,Allow to set the default behavior to "allowing."

How to split a string into an array in Bash?

if you use macOS and can't use readarray, you can simply do this-

MY_STRING="string1 string2 string3"
array=($MY_STRING)

To iterate over the elements:

for element in "${array[@]}"
do
    echo $element
done

C++ templates that accept only certain types

There is no keyword for such type checks, but you can put some code in that will at least fail in an orderly fashion:

(1) If you want a function template to only accept parameters of a certain base class X, assign it to a X reference in your function. (2) If you want to accept functions but not primitives or vice versa, or you want to filter classes in other ways, call a (empty) template helper function within your function that's only defined for the classes you want to accept.

You can use (1) and (2) also in member functions of a class to force these type checks on the entire class.

You can probably put it into some smart Macro to ease your pain. :)

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How to correctly save instance state of Fragments in back stack?

To correctly save the instance state of Fragment you should do the following:

1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

class MyFragment extends Fragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's state here
        }
    }
    ...
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's state here
    }

}

2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().

class MyActivity extends Activity {

    private MyFragment 

    public void onCreate(Bundle savedInstanceState) {
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's instance
            mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
            ...
        }
        ...
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's instance
        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
    }

}

Hope this helps.

finding first day of the month in python

Can be done on the same line using date.replace:

from datetime import datetime

datetime.today().replace(day=1)

Emulator in Android Studio doesn't start

For me, on MacOS X, the emulator process was already running, but without the interface. I had to open MacOS Activity Monitor and kill the process qemu-system-x86_64. Afterwards, running the app launched the emulator successfully.

Select the process called qemu-system-x86_64 in Activity Monitor and click the X button to kill the process. Then click Run or Debug in Android Studio.

enter image description here

Input type "number" won't resize

Rather than set the length, set the max and min values for the number input.

The input box then resizes to fit the longest valid value.

If you want to allow a 3-digit number then set 999 as the max

 <input type="number" name="quantity" min="0" max="999">

Static Block in Java

Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation. http://www.jusfortechies.com/java/core-java/static-blocks.php

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

How to use mysql JOIN without ON condition?

MySQL documentation covers this topic.

Here is a synopsis. When using join or inner join, the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join. Similarly, you can use an on clause with cross join, which also differs from standard SQL.

A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.

In practice, if you want to do a cross join, then use cross join:

from A cross join B

is much better than:

from A, B

and:

from A join B -- with no on clause

The on clause is required for a right or left outer join, so the discussion is not relevant for them.

If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.

Move SQL data from one table to another

Yes it is. First INSERT + SELECT and then DELETE orginals.

INSERT INTO Table2 (UserName,Password)
SELECT UserName,Password FROM Table1 WHERE UserName='X' AND Password='X'

then delete orginals

DELETE FROM Table1 WHERE UserName='X' AND Password='X'

you may want to preserve UserID or someother primary key, then you can use IDENTITY INSERT to preserve the key.

see more on SET IDENTITY_INSERT on MSDN

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

How to solve "Fatal error: Class 'MySQLi' not found"?

If you are on Ubuntu, run:

 sudo apt-get install php-mysqlnd

Sum the digits of a number

def sumOfDigits():

    n=int(input("enter digit:")) 
    sum=0
    while n!=0 :

        m=n%10
        n=n/10
        sum=int(sum+m)

    print(sum)

sumOfDigits()

How to delete row in gridview using rowdeleting event?

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)");
    GridView1.DataBind();
}

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

Using PUT method in HTML form

for people using laravel

<form method="post" ...>
@csrf
@method('put')
...
</form>

Bootstrap datetimepicker is not a function

I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js

try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}

How to use Apple's new San Francisco font on a webpage

If the user is running El Capitan or higher, it will work in Chrome with

font-family: 'BlinkMacSystemFont';

Is there a way to create multiline comments in Python?

Well, you can try this (when running the quoted, the input to the first question should quoted with '):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

Whatever enclosed between """ will be commented.

If you are looking for single-line comments then it's #.

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

Restoring Nuget References?

Just in case it helps someone - In my scenario, I have some shared libraries (Which have their own TFS projects/solutions) all combined into one solution.

Nuget would restore projects successfully, but the DLL would be missing.

The underlying issue was that, whilst your solution has its own packages folder and has restored them correctly to that folder, the project file (e.g. .csproj) is referencing a different project which may not have the package downloaded. Open the file in a text editor to see where your references are coming from.

This can occur when managing packages on different interlinked shared solutions - since you probably want to make sure all DLLs are on the same level you might set this at the top level. This means it that sometimes it will be looking in a completely different solution for a referenced DLL and so if you don't have all projects/solutions downloaded and up-to-date then you may get the above problem.

What's a good IDE for Python on Mac OS X?

I've searched on Google for an app like this for a while, and I've found only options with heavy and ugly interfaces.

Then I opened Mac App Store and found CodeRunner. Very nice and clean interface. Support many languages like Python, Lua, Perl, Ruby, Javascript, etc. The price is U$10, but it's worth it!

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).

How to install bcmath module?

If you have installed php 7.1 then this line work on your system.

sudo apt install php7.1-bcmath

check your php version in your system on ubuntu 16.04

php -v

and then result show there..

PHP 7.1.x+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Aug 19 2018 07:16:12) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.9-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

In vb.net, how to get the column names from a datatable

Look at

For Each c as DataColumn in dt.Columns
  '... = c.ColumnName
Next

or:

dt.GetDataTableSchema(...)

Detect if HTML5 Video element is playing

I just looked at the link @tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".

I have ust tested it and it works just fine.

How to close a JavaFX application on window close?

Some of the provided answers did not work for me (javaw.exe still running after closing the window) or, eclipse showed an exception after the application was closed.

On the other hand, this works perfectly:

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent t) {
        Platform.exit();
        System.exit(0);
    }
});

How to Add Incremental Numbers to a New Column Using Pandas

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

Convert varchar into datetime in SQL Server

SQL standard dates while inserting or updating Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

So if you are inserting/Updating below 1/1/1753 you will get this error.

Setting device orientation in Swift iOS

From ios 10.0 we need set { self.orientations = newValue } for setting up the orientation, Make sure landscape property is enabled in your project.

private var orientations = UIInterfaceOrientationMask.landscapeLeft
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    get { return self.orientations }
    set { self.orientations = newValue }
}

When is "java.io.IOException:Connection reset by peer" thrown?

It can also mean that the server is completely inaccessible - I was getting this when trying to hit a server that was offline

My client was configured to connect to localhost:3000, but no server was running on that port.

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):

When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.

Note: the answer was edited on Jan 2016 to reflect most recent changes

What is the difference between buffer and cache memory in Linux?

Explained by Red Hat:

Cache Pages:

A cache is the part of the memory which transparently stores data so that future requests for that data can be served faster. This memory is utilized by the kernel to cache disk data and improve i/o performance.

The Linux kernel is built in such a way that it will use as much RAM as it can to cache information from your local and remote filesystems and disks. As the time passes over various reads and writes are performed on the system, kernel tries to keep data stored in the memory for the various processes which are running on the system or the data that of relevant processes which would be used in the near future. The cache is not reclaimed at the time when process get stop/exit, however when the other processes requires more memory then the free available memory, kernel will run heuristics to reclaim the memory by storing the cache data and allocating that memory to new process.

When any kind of file/data is requested then the kernel will look for a copy of the part of the file the user is acting on, and, if no such copy exists, it will allocate one new page of cache memory and fill it with the appropriate contents read out from the disk.

The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere in the disk. When some data is requested, the cache is first checked to see whether it contains that data. The data can be retrieved more quickly from the cache than from its source origin.

SysV shared memory segments are also accounted as a cache, though they do not represent any data on the disks. One can check the size of the shared memory segments using ipcs -m command and checking the bytes column.

Buffers:

Buffers are the disk block representation of the data that is stored under the page caches. Buffers contains the metadata of the files/data which resides under the page cache. Example: When there is a request of any data which is present in the page cache, first the kernel checks the data in the buffers which contain the metadata which points to the actual files/data contained in the page caches. Once from the metadata the actual block address of the file is known, it is picked up by the kernel for processing.

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object and test the $_.CreationTime:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
    Where-Object { $_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }

Nginx: Permission denied for nginx on Ubuntu

Nginx needs to run by command 'sudo /etc/init.d/nginx start'

frequent issues arising in android view, Error parsing XML: unbound prefix

As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="10dip">

will not work.

Change:

xmlns="http://schemas.android.com/apk/res/android"

to

xmlns:android="http://schemas.android.com/apk/res/android"

The error message is referring to everything that starts "android:" as the XML does not know what the "android:" namespace is.

xmlns:android defines it.

Using Camera in the Android emulator

Update of @param's answer.

ICS emulator supports camera.

I found Simple Android Photo Capture, which supports webcam in android emulator.

Why don't self-closing script elements work?

That's because SCRIPT TAG is not a VOID ELEMENT.

In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!

In xhtml, everything is Generic, therefore they all need termination e.g. a "closing tag"; Including br, a simple line-break, as <br></br> or its shorthand <br />.

However, a Script Element is never a void or a parametric Element, because script tag before anything else, is a Browser Instruction, not a Data Description declaration.

Principally, a Semantic Termination Instruction e.g., a "closing tag" is only needed for processing instructions who's semantics cannot be terminated by a succeeding tag. For instance:

<H1> semantics cannot be terminated by a following <P> because it doesn't carry enough of its own semantics to override and therefore terminate the previous H1 instruction set. Although it will be able to break the stream into a new paragraph line, it is not "strong enough" to override the present font size & style line-height pouring down the stream, i.e leaking from H1 (because P doesn't have it).

This is how and why the "/" (termination) signalling has been invented.

A generic no-description termination Tag like < />, would have sufficed for any single fall off the encountered cascade, e.g.: <H1>Title< /> but that's not always the case, because we also want to be capable of "nesting", multiple intermediary tagging of the Stream: split into torrents before wrapping / falling onto another cascade. As a consequence a generic terminator such as < /> would not be able to determine the target of a property to terminate. For example: <b>bold <i>bold-italic < /> italic </>normal. Would undoubtedly fail to get our intention right and would most probably interpret it as bold bold-itallic bold normal.

This is how the notion of a wrapper ie., container was born. (These notions are so similar that it is impossible to discern and sometimes the same element may have both. <H1> is both wrapper and container at the same time. Whereas <B> only a semantic wrapper). We'll need a plain, no semantics container. And of course the invention of a DIV Element came by.

The DIV element is actually a 2BR-Container. Of course the coming of CSS made the whole situation weirder than it would otherwise have been and caused a great confusion with many great consequences - indirectly!

Because with CSS you could easily override the native pre&after BR behavior of a newly invented DIV, it is often referred to, as a "do nothing container". Which is, naturally wrong! DIVs are block elements and will natively break the line of the stream both before and after the end signalling. Soon the WEB started suffering from page DIV-itis. Most of them still are.

The coming of CSS with its capability to fully override and completely redefine the native behavior of any HTML Tag, somehow managed to confuse and blur the whole meaning of HTML existence...

Suddenly all HTML tags appeared as if obsolete, they were defaced, stripped of all their original meaning, identity and purpose. Somehow you'd gain the impression that they're no longer needed. Saying: A single container-wrapper tag would suffice for all the data presentation. Just add the required attributes. Why not have meaningful tags instead; Invent tag names as you go and let the CSS bother with the rest.

This is how xhtml was born and of course the great blunt, paid so dearly by new comers and a distorted vision of what is what, and what's the damn purpose of it all. W3C went from World Wide Web to What Went Wrong, Comrades?!!

The purpose of HTML is to stream meaningful data to the human recipient.

To deliver Information.

The formal part is there to only assist the clarity of information delivery. xhtml doesn't give the slightest consideration to the information. - To it, the information is absolutely irrelevant.

The most important thing in the matter is to know and be able to understand that xhtml is not just a version of some extended HTML, xhtml is a completely different beast; grounds up; and therefore it is wise to keep them separate.

How to kill a process running on particular port in Linux?

You can use the lsof command. Let port number like here is 8090

lsof -i:8090

This command returns a list of open processes on this port.

Something like…

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ssh 75782 eoin 5u IPv6 0x01c1c234 0t0 TCP localhost:8090 (LISTEN)

To free the port, kill the process using it(the process id is 75782)…

kill -9 75782

This one worked for me. here is the link from the original post: link

Set EditText cursor color

are you want specific color you must use AppCompatEditText then backround set null

works for me

<android.support.v7.widget.AppCompatEditText
    android:background="@null"
    android:textCursorDrawable="@color/cursorColor"/>

See this gist

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

How do I create a WPF Rounded Corner container?

I know that this isn't an answer to the initial question ... but you often want to clip the inner content of that rounded corner border you just created.

Chris Cavanagh has come up with an excellent way to do just this.

I have tried a couple different approaches to this ... and I think this one rocks.

Here is the xaml below:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="Black"
>
    <!-- Rounded yellow border -->
    <Border
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        BorderBrush="Yellow"
        BorderThickness="3"
        CornerRadius="10"
        Padding="2"
    >
        <Grid>
            <!-- Rounded mask (stretches to fill Grid) -->
            <Border
                Name="mask"
                Background="White"
                CornerRadius="7"
            />

            <!-- Main content container -->
            <StackPanel>
                <!-- Use a VisualBrush of 'mask' as the opacity mask -->
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>

                <!-- Any content -->
                <Image Source="http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/>
                <Rectangle
                    Height="50"
                    Fill="Red"/>
                <Rectangle
                    Height="50"
                    Fill="White"/>
                <Rectangle
                    Height="50"
                    Fill="Blue"/>
            </StackPanel>
        </Grid>
    </Border>
</Page>

Bootstrap 3 select input form inline

Based on spacebean's answer, this modification also changes the displayed text when the user selects a different item (just as a <select> would do):

http://www.bootply.com/VxVlaebtnL

HTML:

<div class="container">
  <div class="col-sm-7 pull-right well">
    <form class="form-inline" action="#" method="get">
      <div class="input-group col-sm-8">
        <input class="form-control" type="text" value="" placeholder="Search" name="q">
        <div class="input-group-btn">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="mydropdowndisplay">Choice 1</span> <span class="caret"></span></button>
          <ul class="dropdown-menu" id="mydropdownmenu">
            <li><a href="#">Choice 1</a></li>
            <li><a href="#">Choice 2</a></li>
            <li><a href="#">Choice 3</a></li>
          </ul>
          <input type="hidden" id="mydropwodninput" name="category">
        </div><!-- /btn-group -->
      </div>
    <button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
    </form>
  </div>
</div>

Jquery:

$('#mydropdownmenu > li').click(function(e){
  e.preventDefault();
  var selected = $(this).text();
  $('#mydropwodninput').val(selected);
  $('#mydropdowndisplay').text(selected);
});

How to get the return value from a thread in python?

Most answers I've found are long and require being familiar with other modules or advanced python features, and will be rather confusing to someone unless they're already familiar with everything the answer talks about.

Working code for a simplified approach:

import threading, time, random

class ThreadWithResult(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):
        def function():
            self.result = target(*args, **kwargs)
        super().__init__(group=group, target=function, name=name, daemon=daemon)

def function_to_thread(n):
    count = 0
    while count < 3:
            print(f'still running thread {n}')
            count +=1
            time.sleep(3)
    result = random.random()
    print(f'Return value of thread {n} should be: {result}')
    return result


def main():
    thread1 = ThreadWithResult(target=function_to_thread, args=(1,))
    thread2 = ThreadWithResult(target=function_to_thread, args=(2,))
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print(thread1.result)
    print(thread2.result)

main()

Explanation: I wanted to simplify things significantly, so I created a ThreadWithResult class and had it inherit from threading.Thread. The nested function function in __init__ calls the threaded function we want to save the value of, and saves the result of that as the instance attribute self.result after the thread finishes executing.

Creating an instance of this is identical to creating an instance of threading.Thread. Pass in the function you want to run on a new thread to the target argument and any arguments that your function might need to the args argument and any keyword arguments to the kwargs argument.

e.g.

my_thread = ThreadWithResult(target=my_function, args=(arg1, arg2, arg3))

I think this is significantly easier to understand than the vast majority of answers, and this approach requires no extra imports! I included the time and random module to simulate the behavior of a thread, but they're not required to achieve the functionality asked in the original question.

I know I'm answering this looong after the question was asked, but I hope this can help more people in the future!


EDIT: I created the save-thread-result PyPI package to allow you to access the same code above and reuse it across projects (GitHub code is here). The PyPI package fully extends the threading.Thread class, so you can set any attributes you would set on threading.thread on the ThreadWithResult class as well!

The original answer above goes over the main idea behind this subclass, but for more information, see the more detailed explanation (from the module docstring) here.

Quick usage example:

pip3 install -U save-thread-result     # MacOS/Linux
pip  install -U save-thread-result     # Windows

python3     # MacOS/Linux
python      # Windows
from save_thread_result import ThreadWithResult

# As of Release 0.0.3, you can also specify values for
#`group`, `name`, and `daemon` if you want to set those
# values manually.
thread = ThreadWithResult(
    target = my_function,
    args   = (my_function_arg1, my_function_arg2, ...)
    kwargs = (my_function_kwarg1=kwarg1_value, my_function_kwarg2=kwarg2_value, ...)
)

thread.start()
thread.join()
if getattr(thread, 'result', None):
    print(thread.result)
else:
    # thread.result attribute not set - something caused
    # the thread to terminate BEFORE the thread finished
    # executing the function passed in through the
    # `target` argument
    print('ERROR! Something went wrong while executing this thread, and the function you passed in did NOT complete!!')

# seeing help about the class and information about the threading.Thread super class methods and attributes available:
help(ThreadWithResult)

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

How do I exit a foreach loop in C#?

Just use the statement:

break;

Class Diagrams in VS 2017

VS 2017 Professional edition- Go to Quick launch type "Class..." select Class designer and install it.

Once installed go to Add New Items search "Class Diagram" and you are ready to go.

How to Resize a Bitmap in Android?

Scale based on aspect ratio:

float aspectRatio = yourSelectedImage.getWidth() / 
    (float) yourSelectedImage.getHeight();
int width = 480;
int height = Math.round(width / aspectRatio);

yourSelectedImage = Bitmap.createScaledBitmap(
    yourSelectedImage, width, height, false);

To use height as base intead of width change to:

int height = 480;
int width = Math.round(height * aspectRatio);

How to get jQuery dropdown value onchange event

If you have simple dropdown like:

<select name="status" id="status">
    <option value="1">Active</option>
    <option value="0">Inactive</option>
</select>

Then you can use this code for getting value:

$(function(){

 $("#status").change(function(){
     var status = this.value;
     alert(status);
   if(status=="1")
     $("#icon_class, #background_class").hide();// hide multiple sections
  });

});

Get last 5 characters in a string

I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:

Dim sMyString, sLast5 As String

sMyString = "I will be going to school in 2011!"
sLast5 = Right(sMyString, - 5)
MsgBox("sLast5 = " & sLast5)

If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.

Add two textbox values and display the sum in a third textbox automatically

i didn't find who made elegant answer , that's why let me say :

Array.from(
   document.querySelectorAll('#txt1,#txt2')
).map(e => parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)

_x000D_
_x000D_
window.sum= () => _x000D_
 document.getElementById('result').innerHTML=    _x000D_
   Array.from(_x000D_
     document.querySelectorAll('#txt1,#txt2')_x000D_
   ).map(e=>parseInt(e.value)||0)_x000D_
   .reduce((a,b)=>a+b,0)
_x000D_
<input type="text" id="txt1" onkeyup="sum()"/>_x000D_
<input type="text" id="txt2" onkeyup="sum()"  style="margin-right:10px;"/><span id="result"></span>
_x000D_
_x000D_
_x000D_

Is it possible to ping a server from Javascript?

Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:

function ping(host, port, pong) {

  var started = new Date().getTime();

  var http = new XMLHttpRequest();

  http.open("GET", "http://" + host + ":" + port, /*async*/true);
  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      var ended = new Date().getTime();

      var milliseconds = ended - started;

      if (pong != null) {
        pong(milliseconds);
      }
    }
  };
  try {
    http.send(null);
  } catch(exception) {
    // this is expected
  }

}

Is the practice of returning a C++ reference variable evil?

Function as lvalue (aka, returning of non-const references) should be removed from C++. It's terribly unintuitive. Scott Meyers wanted a min() with this behavior.

min(a,b) = 0;  // What???

which isn't really an improvement on

setmin (a, b, 0);

The latter even makes more sense.

I realize that function as lvalue is important for C++ style streams, but it's worth pointing out that C++ style streams are terrible. I'm not the only one that thinks this... as I recall Alexandrescu had a large article on how to do better, and I believe boost has also tried to create a better type safe I/O method.

Min / Max Validator in Angular 2 Final

This question has already been answered. I'd like to extend the answer from @amd. Sometimes you might need a default value.

For example, to validate against a specific value, I'd like to provide it as follows-

<input integerMinValue="20" >

But the minimum value of a 32 bit signed integer is -2147483648. To validate against this value, I don't like to provide it. I'd like to write as follows-

<input integerMinValue >

To achieve this you can write your directive as follows

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, Validators} from '@angular/forms';

@Directive({
    selector: '[integerMinValue]',
    providers: [{provide: NG_VALIDATORS, useExisting: IntegerMinValidatorDirective, multi: true}]
})
export class IntegerMinValidatorDirective implements Validator {

    private minValue = -2147483648;

    @Input('integerMinValue') set min(value: number) {
        if (value) {
            this.minValue = +value;
        }
    }

    validate(control: AbstractControl): ValidationErrors | null {
        return Validators.min(this.minValue)(control);
    }

}

Git resolve conflict using --ours/--theirs for all files

git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.

How do I remove a submodule?

I've created a bash script to ease the removal process. It also checks whether there are changes in the repo left unsaved and asks for confirmation. It has been tested on os x would be interesting to know if it works as is on common linux distros as well:

https://gist.github.com/fabifrank/cdc7e67fd194333760b060835ac0172f

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

Error importing Seaborn module in Python

I had the same problem and I am using iPython. pip or conda by itself did not work for me but when I use !conda it did work.

!conda install seaborn

git: fatal unable to auto-detect email address

Had similar problem, I'm fairly new so take this with a grain of salt but I needed to go up a directory first, set the username, then go back down to git repository.

cd ..    
git config --global user.email "[email protected]"
git config --global user.name "your_name"
cd <your repository folder>

Hope this helps anyone else that gets stuck

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Can't find System.Windows.Media namespace?

You can add PresentationCore.dll more conveniently by editing the project file. Add the following code into your csproj file:

<ItemGroup>
   <FrameworkReference Include="Microsoft.WindowsDesktop.App" />
</ItemGroup>

In your solution explorer, you now should see this framework listed, now. With that, you then can also refer to the classes provided by PresentationCore.dll.

PHP Array to CSV

This is a simple solution that exports an array to csv string:

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));

Running CMD command in PowerShell

One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.

PS C:\> "notepad.exe" | cmd

Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.


Edits

CMD's Startup Message is Shown

As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

IOError: [Errno 32] Broken pipe: Python

A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:

python foo.py | someothercommand

The issue you have is that someothercommand is exiting without reading everything available on its standard input. This causes your write (via print) to fail at some point.

I was able to reproduce the error with the following command on a Linux system:

python -c 'for i in range(1000): print i' | less

If I close the less pager without scrolling through all of its input (1000 lines), Python exits with the same IOError you have reported.

Using NULL in C++?

Assuming that you don't have a library or system header that defines NULL as for example (void*)0 or (char*)0 it's fine. I always tend to use 0 myself as it is by definition the null pointer. In c++0x you'll have nullptr available so the question won't matter as much anymore.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

if you are using httpd/apache, you can add a file something like ws.conf and add this code to it. Also, this solution can proxy something like this "http://localhost:6001/socket.io" to just this "http://localhost/socket.io"

<VirtualHost *:80>
    RewriteEngine on

    #redirect WebSocket
    RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
    RewriteCond %{QUERY_STRING} transport=websocket    [NC]
    RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

    ProxyPass        /socket.io http://localhost:6001/socket.io
    ProxyPassReverse /socket.io http://localhost:6001/socket.io
</VirtualHost>

Decorators with parameters?

Great answers above. This one also illustrates @wraps, which takes the doc string and function name from the original function and applies it to the new wrapped version:

from functools import wraps

def decorator_func_with_args(arg1, arg2):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            print("Before orginal function with decorator args:", arg1, arg2)
            result = f(*args, **kwargs)
            print("Ran after the orginal function")
            return result
        return wrapper
    return decorator

@decorator_func_with_args("foo", "bar")
def hello(name):
    """A function which prints a greeting to the name provided.
    """
    print('hello ', name)
    return 42

print("Starting script..")
x = hello('Bob')
print("The value of x is:", x)
print("The wrapped functions docstring is:", hello.__doc__)
print("The wrapped functions name is:", hello.__name__)

Prints:

Starting script..
Before orginal function with decorator args: foo bar
hello  Bob
Ran after the orginal function
The value of x is: 42
The wrapped functions docstring is: A function which prints a greeting to the name provided.
The wrapped functions name is: hello

Android get current Locale, not default

The default Locale is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale selected on that device when the application was launched. Typically, this is fine, but it does mean that if the user changes their Locale in settings after your application process is running, the value of getDefaultLocale() probably will not be immediately updated.

If you need to trap events like this for some reason in your application, you might instead try obtaining the Locale available from the resource Configuration object, i.e.

Locale current = getResources().getConfiguration().locale;

You may find that this value is updated more quickly after a settings change if that is necessary for your application.

git replace local version with remote version

I would checkout the remote file from the "master" (the remote/origin repository) like this:

git checkout master <FileWithPath>

Example: git checkout master components/indexTest.html

jquery toggle slide from left to right and back

Sliding from the right:

$('#example').animate({width:'toggle'},350);

Sliding to the left:

$('#example').toggle({ direction: "left" }, 1000);

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

I would recommend this to anyone looking for missing functionality:

http://code.google.com/p/ddr-ecma5/

It brings in most of the missing ecma5 functionality to older browers :)

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

Qt: How do I handle the event of the user pressing the 'X' (close) button?

Well, I got it. One way is to override the QWidget::closeEvent(QCloseEvent *event) method in your class definition and add your code into that function. Example:

class foo : public QMainWindow
{
    Q_OBJECT
private:
    void closeEvent(QCloseEvent *bar);
    // ...
};


void foo::closeEvent(QCloseEvent *bar)
{
    // Do something
    bar->accept();
}

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

The Mike R's solution works for me. This is the full set of commands:

Xvfb :99 -ac -screen 0 1280x1024x24 &
export DISPLAY=:99
nice -n 10 x11vnc 2>&1 &

Later you can run google-chrome:

google-chrome --no-sandbox &

Or start google chrome via selenium driver (for example):

ng e2e --serve true --port 4200 --watch true

Protractor.conf file:

capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
        'args': ['no-sandbox']
    }
},

Globally catch exceptions in a WPF application?

In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException (and its similars) with

<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

in the app.config will prevent your secondary threads exception from shutting down the application.

Can I set max_retries for requests.request?

After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:

import backoff

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_tries=5,
    giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
    r = requests.post(url, timeout=10, json=data)
    r.raise_for_status()

I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.

Using an if statement to check if a div is empty

also you can use this :


    if (! $('#leftmenu').children().length > 0 ) {
         // do something : e.x : remove a specific div
    }

I think it'll work for you !

How to watch and reload ts-node when TypeScript files change

i did with

"start": "nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts"

and yarn start.. ts-node not like 'ts-node'

Retrieve column names from java.sql.ResultSet

@Cyntech is right.

Incase your table is empty and you still need to get table column names you can get your column as type Vector,see the following:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

Vector<Vector<String>>tableVector = new Vector<Vector<String>>(); 
boolean isTableEmpty = true;
int col = 0;

 while(rs.next())
    {
      isTableEmpty = false;  //set to false since rs.next has data: this means the table is not empty
       if(col != columnCount)
          {
            for(int x = 1;x <= columnCount;x++){
                 Vector<String> tFields = new Vector<String>(); 
                 tFields.add(rsmd.getColumnName(x).toString());
                 tableVector.add(tFields);
             }
            col = columnCount;
          }
     } 


      //if table is empty then get column names only
  if(isTableEmpty){  
      for(int x=1;x<=colCount;x++){
           Vector<String> tFields = new Vector<String>(); 
           tFields.add(rsmd.getColumnName(x).toString());
           tableVector.add(tFields);
        }
      }

 rs.close();
 stmt.close();

 return tableVector; 

#pragma pack effect

I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.

How to solve privileges issues when restore PostgreSQL Database

You can probably safely ignore the error messages in this case. Failing to add a comment to the public schema and installing plpgsql (which should already be installed) aren't going to cause any real problems.

However, if you want to do a complete re-install you'll need a user with appropriate permissions. That shouldn't be the user your application routinely runs as of course.