Programs & Examples On #Twig

Twig is a modern, fast, flexible, and secure templating engine for PHP. Created for Symfony and adopted by Drupal 8.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to get config parameters in Symfony2 Twig Templates

In confing.yml

# app/config/config.yml
twig:
  globals:
    version: '%app.version%'

In Twig view

# twig view
{{ version }}

How to use absolute path in twig functions

Daniel's answer seems to work fine for now, but please note that generating absolute urls using twig's asset function is now deprecated:

DEPRECATED - Generating absolute URLs with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0. Please use absolute_url() instead.

Here's the official announcement: http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes

You have to use the absolute_url twig function:

{# Symfony 2.6 #}
{{ asset('logo.png', absolute = true) }}

{# Symfony 2.7 #}
{{ absolute_url(asset('logo.png')) }}

It is interesting to note that it also works with path function:

{{ absolute_url(path('index')) }}

Twig for loop for arrays with keys

I guess you want to do the "Iterating over Keys and Values"

As the doc here says, just add "|keys" in the variable you want and it will magically happen.

{% for key, user in users %}
    <li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}

It never hurts to search before asking :)

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

How to include CSS file in Symfony 2 and Twig?

You are doing everything right, except passing your bundle path to asset() function.

According to documentation - in your example this should look like below:

{{ asset('bundles/webshome/css/main.css') }}

Tip: you also can call assets:install with --symlink key, so it will create symlinks in web folder. This is extremely useful when you often apply js or css changes (in this way your changes, applied to src/YouBundle/Resources/public will be immediately reflected in web folder without need to call assets:install again):

app/console assets:install web --symlink

Also, if you wish to add some assets in your child template, you could call parent() method for the Twig block. In your case it would be like this:

{% block stylesheets %}
    {{ parent() }}

    <link href="{{ asset('bundles/webshome/css/main.css') }}" rel="stylesheet">
{% endblock %}

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

How to render a DateTime object in a Twig template

There is a symfony2 tool to display date in the current locale:

{{ user.createdAt|localeDate }} to have a medium date and no time, in the current locale

{{ user.createdAt|localeDate('long','medium') }} to have a long date and medium time, in the current locale

https://github.com/michelsalib/BCCExtraToolsBundle

The CSRF token is invalid. Please try to resubmit the form

Before your </form> tag put:

{{ form_rest(form) }}

It will automatically insert other important (hidden) inputs.

How to concatenate strings in twig

To mix strings, variables and translations I simply do the following:

    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

Despite everything being mixed up, it works like a charm.

Accessing session from TWIG template

The way to access a session variable in Twig is:

{{ app.session.get('name_variable') }}

symfony 2 twig limit the length of the text and put three dots

Another one is:

{{ myentity.text[:50] ~ '...' }}

How to var_dump variables in twig templates?

If you are using Twig in your application as a component you can do this:

$twig = new Twig_Environment($loader, array(
    'autoescape' => false
));

$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));

Then in your templates:

{{ my_variable | var_dump }}

How can I use break or continue within for loop in Twig template?

From docs TWIG docs:

Unlike in PHP, it's not possible to break or continue in a loop.

But still:

You can however filter the sequence during iteration which allows you to skip items.

Example 1 (for huge lists you can filter posts using slice, slice(start, length)):

{% for post in posts|slice(0,10) %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

Example 2:

{% for post in posts if post.id < 10 %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

You can even use own TWIG filters for more complexed conditions, like:

{% for post in posts|onlySuperPosts %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

How to display string that contains HTML in twig template?

if you don't need variable, you can define text in
translations/messages.en.yaml :
CiteExampleHtmlCode: "<b> my static text </b>"

then use it with twig:
templates/about/index.html.twig
… {{ 'CiteExampleHtmlCode' }}
or if you need multilangages like me:
… {{ 'CiteExampleHtmlCode' | trans }}

Let's have a look of https://symfony.com/doc/current/translation.html for more information about translations use.

Call PHP function from Twig template

If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:

function evilEvalPhp($eval, $args = null)
{
    $result = null;
    eval($eval);
    return $result;
}

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

Check if inputs form are empty jQuery

You could do it like this :

bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;

//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
   //If the field's empty
   if($(this).val() != '')
   {
      //Mark it
      areFieldEmpty = NO;
      //Then leave all the loops
      break outer_loop;
   }
});

//Then test your bool 

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

Java: Reading integers from a file into an array

You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.

PHP cURL GET request and request's body

you have done it the correct way using

curl_setopt($ch, CURLOPT_POSTFIELDS,$body);

but i notice your missing

curl_setopt($ch, CURLOPT_POST,1);

Using C# to read/write Excel files (.xls/.xlsx)

You can use Excel Automation (it is basically a COM Base stuff) e.g:

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;


xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

Link to the full tutorial

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

How to create file object from URL object (image)

You can convert the URL to a String and use it to create a new File. e.g.

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

Add click event on div tag using javascript

Separate function to make adding event handlers much easier.

function addListener(event, obj, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(event, fn, false);   // modern browsers
    } else {
        obj.attachEvent("on"+event, fn);          // older versions of IE
    }
}

element = document.getElementsByClassName('drill_cursor')[0];

addListener('click', element, function () {
    // Do stuff
});

CMake does not find Visual C++ compiler

i found this sollution at stackoverflow and i work for me although not working other sollutions if you have a windows 10 OS, doing the following steps will fix the problem:

1) go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin

2) then copy RC.exe and RcDll from this file

3) go to C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin and paste the two files you have copied into it.

thats all i hope it is helpful...

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

Just add data-backdrop="static" and data-keyboard="false" attributes to that modal.

Eg.

<a data-controls-modal="your_div_id" data-backdrop="static" data-keyboard="false" href="#">

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

How to convert hex to rgb using Java?

To elaborate on the answer @xhh provided, you can append the red, green, and blue to format your string as "rgb(0,0,0)" before returning it.

/**
* 
* @param colorStr e.g. "#FFFFFF"
* @return String - formatted "rgb(0,0,0)"
*/
public static String hex2Rgb(String colorStr) {
    Color c = new Color(
        Integer.valueOf(hexString.substring(1, 3), 16), 
        Integer.valueOf(hexString.substring(3, 5), 16), 
        Integer.valueOf(hexString.substring(5, 7), 16));

    StringBuffer sb = new StringBuffer();
    sb.append("rgb(");
    sb.append(c.getRed());
    sb.append(",");
    sb.append(c.getGreen());
    sb.append(",");
    sb.append(c.getBlue());
    sb.append(")");
    return sb.toString();
}

Slide up/down effect with ng-show and ng-animate

You should use Javascript animations for this - it is not possible in pure CSS, because you can't know the height of any element. Follow the instructions it has for you about javascript animation implementation, and copy slideUp and slideDown from jQuery's source.

Creating default object from empty value in PHP?

Try using:

$user = (object) null;

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

To post JSON, you will need to stringify it. JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Bulk insert with SQLAlchemy ORM

As far as I know, there is no way to get the ORM to issue bulk inserts. I believe the underlying reason is that SQLAlchemy needs to keep track of each object's identity (i.e., new primary keys), and bulk inserts interfere with that. For example, assuming your foo table contains an id column and is mapped to a Foo class:

x = Foo(bar=1)
print x.id
# None
session.add(x)
session.flush()
# BEGIN
# INSERT INTO foo (bar) VALUES(1)
# COMMIT
print x.id
# 1

Since SQLAlchemy picked up the value for x.id without issuing another query, we can infer that it got the value directly from the INSERT statement. If you don't need subsequent access to the created objects via the same instances, you can skip the ORM layer for your insert:

Foo.__table__.insert().execute([{'bar': 1}, {'bar': 2}, {'bar': 3}])
# INSERT INTO foo (bar) VALUES ((1,), (2,), (3,))

SQLAlchemy can't match these new rows with any existing objects, so you'll have to query them anew for any subsequent operations.

As far as stale data is concerned, it's helpful to remember that the session has no built-in way to know when the database is changed outside of the session. In order to access externally modified data through existing instances, the instances must be marked as expired. This happens by default on session.commit(), but can be done manually by calling session.expire_all() or session.expire(instance). An example (SQL omitted):

x = Foo(bar=1)
session.add(x)
session.commit()
print x.bar
# 1
foo.update().execute(bar=42)
print x.bar
# 1
session.expire(x)
print x.bar
# 42

session.commit() expires x, so the first print statement implicitly opens a new transaction and re-queries x's attributes. If you comment out the first print statement, you'll notice that the second one now picks up the correct value, because the new query isn't emitted until after the update.

This makes sense from the point of view of transactional isolation - you should only pick up external modifications between transactions. If this is causing you trouble, I'd suggest clarifying or re-thinking your application's transaction boundaries instead of immediately reaching for session.expire_all().

Count specific character occurrences in a string

    ' Trying to find the amount of "." in the text
    ' if txtName looks like "hi...hi" then intdots will = 3
    Dim test As String = txtName.Text
    Dim intdots As Integer = 0
    For i = 1 To test.Length
        Dim inta As Integer = 0 + 1
        Dim stra As String = test.Substring(inta)
        If stra = "." Then
            intdots = intdots + 1
        End If
    Next
    txttest.text = intdots

django MultiValueDictKeyError error, how do I deal with it

Another thing to remember is that request.POST['keyword'] refers to the element identified by the specified html name attribute keyword.

So, if your form is:

<form action="/login/" method="POST">
  <input type="text" name="keyword" placeholder="Search query">
  <input type="number" name="results" placeholder="Number of results">
</form>

then, request.POST['keyword'] and request.POST['results'] will contain the value of the input elements keyword and results, respectively.

Cannot find name 'require' after upgrading to Angular4

I added

"types": [ 
   "node"
]

in my tsconfig file and its worked for me tsconfig.json file look like

  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": [ 
      "node",
      "underscore"
    ]
  },  

Length of a JavaScript object

Use Object.keys(myObject).length to get the length of object/array

_x000D_
_x000D_
var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

console.log(Object.keys(myObject).length); //3
_x000D_
_x000D_
_x000D_

Benefits of inline functions in C++?

Advantages

  • By inlining your code where it is needed, your program will spend less time in the function call and return parts. It is supposed to make your code go faster, even as it goes larger (see below). Inlining trivial accessors could be an example of effective inlining.
  • By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)

Disadvantages

  • It can make your code larger (i.e. if you use inline for non-trivial functions). As such, it could provoke paging and defeat optimizations from the compiler.
  • It slightly breaks your encapsulation because it exposes the internal of your object processing (but then, every "private" member would, too). This means you must not use inlining in a PImpl pattern.
  • It slightly breaks your encapsulation 2: C++ inlining is resolved at compile time. Which means that should you change the code of the inlined function, you would need to recompile all the code using it to be sure it will be updated (for the same reason, I avoid default values for function parameters)
  • When used in a header, it makes your header file larger, and thus, will dilute interesting informations (like the list of a class methods) with code the user don't care about (this is the reason that I declare inlined functions inside a class, but will define it in an header after the class body, and never inside the class body).

Inlining Magic

  • The compiler may or may not inline the functions you marked as inline; it may also decide to inline functions not marked as inline at compilation or linking time.
  • Inline works like a copy/paste controlled by the compiler, which is quite different from a pre-processor macro: The macro will be forcibly inlined, will pollute all the namespaces and code, won't be easily debuggable, and will be done even if the compiler would have ruled it as inefficient.
  • Every method of a class defined inside the body of the class itself is considered as "inlined" (even if the compiler can still decide to not inline it
  • Virtual methods are not supposed to be inlinable. Still, sometimes, when the compiler can know for sure the type of the object (i.e. the object was declared and constructed inside the same function body), even a virtual function will be inlined because the compiler knows exactly the type of the object.
  • Template methods/functions are not always inlined (their presence in an header will not make them automatically inline).
  • The next step after "inline" is template metaprograming . I.e. By "inlining" your code at compile time, sometimes, the compiler can deduce the final result of a function... So a complex algorithm can sometimes be reduced to a kind of return 42 ; statement. This is for me extreme inlining. It happens rarely in real life, it makes compilation time longer, will not bloat your code, and will make your code faster. But like the grail, don't try to apply it everywhere because most processing cannot be resolved this way... Still, this is cool anyway...
    :-p

Return Result from Select Query in stored procedure to a List

May be this will help:

Getting rows from DB:

public static DataRowCollection getAllUsers(string tableName) 
{
     DataSet set = new DataSet();
     SqlCommand comm = new SqlCommand();
     comm.Connection = DAL.DAL.conn;
     comm.CommandType = CommandType.StoredProcedure;
     comm.CommandText = "getAllUsers";
     SqlDataAdapter da = new SqlDataAdapter();
     da.SelectCommand = comm;
     da.Fill(set,tableName);

     DataRowCollection usersCollection = set.Tables[tableName].Rows;
     return usersCollection;
}

Populating DataGridView from DataRowCollection :

public static void ShowAllUsers(DataGridView grdView,string table, params string[] fields) 
{
    DataRowCollection userSet = getAllUsers(table);
    foreach (DataRow user in userSet)
    {
         grdView.Rows.Add(user[fields[0]],
         user[fields[1]],
         user[fields[2]],
         user[fields[3]]);
    }
}

Implementation :

BLL.BLL.ShowAllUsers(grdUsers,"eusers","eid","euname","eupassword","eposition");

How to access the php.ini file in godaddy shared hosting linux

I had this exact problem with my GoDaddy account.

I am running the Linux hosting with cPanel

follow these steps and you should be fine if you are running the same hosting as me:

first, go to you Manage Your Hosting -> Manage

then you will see a section called Files, click on File Manager

you can select the Document Root for: yourwebsite.com then click GO

this should bring you right away in the public_html folder

in that folder, you can add a file (by clicking the +File in top left corner), call it phpinfo.php

right click that new file, and select edit :

right this in it and save changes:

<?php phpinfo(); ?>

it the same public_html folder, add another file called php.ini

edit this one too, right those lines:

max_execution_time 600
memory_limit 128M
post_max_size 32M
upload_max_filesize 32M

now, go back to your Manage Your Hosting -> Manage, look for PHP Process

click Kill Process, this will allows a refresh with your new settings. you are good to go

side note: you can see your new settings by navigating to yourwebiste.com/phpinfo.php

How to unnest a nested list

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.

import java.sql.Timestamp;

public class DateTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new Timestamp(System.currentTimeMillis()));
    }
}

How to compare two dates to find time difference in SQL Server 2005, date manipulation

You can use the DATEDIFF function to get the difference in minutes, seconds, days etc.

SELECT DATEDIFF(MINUTE,job_start,job_end)

MINUTE obviously returns the difference in minutes, you can also use DAY, HOUR, SECOND, YEAR (see the books online link for the full list).

If you want to get fancy you can show this differently for example 75 minutes could be displayed like this: 01:15:00:0

Here is the code to do that for both SQL Server 2005 and 2008

-- SQL Server 2005
SELECT CONVERT(VARCHAR(10),DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000'),114)

-- SQL Server 2008
SELECT CAST(DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000') AS TIME)

How do I search an SQL Server database for a string?

You could;

  1. Script the database to a single file and search the file for tblEmployees using a text editor. In SQL Server Management Studio (SSMS), right click over the database and choose Generate Scripts.
  2. Use SSMS 'View Dependencies' by right clicking over tblEmployees to see which other objects are dependent on it
  3. Use a free third-party tool such as Redgate Software's SQL Search to search all database objects by name and content by keyword.

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

How to check if a particular service is running on Ubuntu

I don't have an Ubuntu box, but on Red Hat Linux you can see all running services by running the following command:

service --status-all

On the list the + indicates the service is running, - indicates service is not running, ? indicates the service state cannot be determined.

How to Apply Gradient to background view of iOS Swift App

Cleaner code that lets you pass any UIColor to an instance of the GradientLayer class:

class GradientLayer {

    let gradientLayer: CAGradientLayer
    let colorTop: CGColor
    let colorBottom: CGColor

    init(colorTop: UIColor, colorBottom: UIColor) {
        self.colorTop = colorTop.CGColor
        self.colorBottom = colorBottom.CGColor
        gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
    }
}

update to python 3.7 using anaconda

To see just the Python releases, do conda search --full-name python.

How to extract text from a PDF file?

Camelot seems a fairly powerful solution to extract tables from PDFs in Python.

At first sight it seems to achieve almost as accurate extraction as the tabula-py package suggested by CreekGeek, which is already waaaaay above any other posted solution as of today in terms of reliability, but it is supposedly much more configurable. Furthermore it has its own accuracy indicator (results.parsing_report), and great debugging features.

Both Camelot and Tabula provide the results as Pandas’ DataFrames, so it is easy to adjust tables afterwards.

pip install camelot-py

(Not to be confused with the camelot package.)

import camelot

df_list = []
results = camelot.read_pdf("file.pdf", ...)
for table in results:
    print(table.parsing_report)
    df_list.append(results[0].df)

It can also output results as CSV, JSON, HTML or Excel.

Camelot comes at the expense of a number of dependencies.

NB : Since my input is pretty complex with many different tables I ended up using both Camelot and Tabula, depending on the table, to achieve the best results.

Can I limit the length of an array in JavaScript?

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.

You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).

You should convert the shortened array back to a string with .join(",") and then use it for the new cookie instead of using old_cookie which is not shortened.

You may also not be using .splice() correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice() here.

Non greedy (reluctant) regex matching in sed?

sed 's|\(http:\/\/www\.[a-z.0-9]*\/\).*|\1| works too

What is the meaning of polyfills in HTML5?

A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers, e.g., to support canvas (an HTML5 feature) in older browsers.

It's sort of an HTML5 technique, since it is used in conjunction with HTML5, but it's not part of HTML5, and you can have polyfills without having HTML5 (for example, to support CSS3 techniques you want).

Here's a good post:

http://remysharp.com/2010/10/08/what-is-a-polyfill/

Here's a comprehensive list of Polyfills and Shims:

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

Functions are not valid as a React child. This may happen if you return a Component instead of from render

You are using it as a regular component, but it's actually a function that returns a component.

Try doing something like this:

const NewComponent = NewHOC(Movie)

And you will use it like this:

<NewComponent someProp="someValue" />

Here is a running example:

_x000D_
_x000D_
const NewHOC = (PassedComponent) => {
  return class extends React.Component {
    render() {
      return (
        <div>
          <PassedComponent {...this.props} />
        </div>
      )
    }
  }
}

const Movie = ({name}) => <div>{name}</div>

const NewComponent = NewHOC(Movie);

function App() {
  return (
    <div>
      <NewComponent name="Kill Bill" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>
_x000D_
_x000D_
_x000D_

So basically NewHOC is just a function that accepts a component and returns a new component that renders the component passed in. We usually use this pattern to enhance components and share logic or data.

You can read about HOCS in the docs and I also recommend reading about the difference between react elements and components

I wrote an article about the different ways and patterns of sharing logic in react.

How to display custom view in ActionBar?

There is a trick for this. All you have to do is to use RelativeLayout instead of LinearLayout as the main container. It's important to have android:layout_gravity="fill_horizontal" set for it. That should do it.

How to git-cherry-pick only changes to certain files?

Use git merge --squash branch_name this will get all changes from the other branch and will prepare a commit for you. Now remove all unneeded changes and leave the one you want. And git will not know that there was a merge.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

There might be cases when some dependencies doest not have types and ts forces you to include types for that. There is a workaround to resolve the issue, which is to use javascript instead.

e.g.

import {Charts} from "react-charts"; //error: Could not find a declaration file for module 'react-charts'.

Workaround: const ReactChart = require("react-charts"); //no-error

How to create a database from shell command?

The ist and 2nd answer are good but if anybody is looking for having a script or If you want dynamic i.e (db/username/password in variable) then here:

#!/bin/bash



DB="mydb"
USER="user1"
PASS="pass_bla"

mysql -uroot -prootpassword -e "CREATE DATABASE $DB CHARACTER SET utf8 COLLATE utf8_general_ci";
mysql -uroot -prootpassword -e "CREATE USER $USER@'127.0.0.1' IDENTIFIED BY '$PASS'";
mysql -uroot -prootpassword -e "GRANT SELECT, INSERT, UPDATE ON $DB.* TO '$USER'@'127.0.0.1'";

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

pip not working in Python Installation in Windows 10

You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator. It's worked for me.

How to copy files between two nodes using ansible

If you need to sync files between two remote nodes via ansible you can use this:

- name: synchronize between nodes
  environment:
    RSYNC_PASSWORD: "{{ input_user_password_if_needed }}"
  synchronize:
    src: rsync://user@remote_server:/module/
    dest: /destination/directory/
    // if needed
    rsync_opts:
       - "--include=what_needed"
       - "--exclude=**/**"
    mode: pull
    delegate_to: "{{ inventory_hostname }}"

when on remote_server you need to startup rsync with daemon mode. Simple example:

pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsync.log
port = port

[module]
path = /path/to/needed/directory/
uid = nobody
gid = nobody
read only = yes
list = yes
auth users = user
secrets file = /path/to/secret/file

How to modify a global variable within a function in bash?

A solution to this problem, without having to introduce complex functions and heavily modify the original one, is to store the value in a temporary file and read / write it when needed.

This approach helped me greatly when I had to mock a bash function called multiple times in a bats test case.

For example, you could have:

# Usage read_value path_to_tmp_file
function read_value {
  cat "${1}"
}

# Usage: set_value path_to_tmp_file the_value
function set_value {
  echo "${2}" > "${1}"
}
#----

# Original code:

function test1() {
  e=4
  set_value "${tmp_file}" "${e}"
  echo "hello"
}


# Create the temp file
# Note that tmp_file is available in test1 as well
tmp_file=$(mktemp)

# Your logic
e=2
# Store the value
set_value "${tmp_file}" "${e}"

# Run test1
test1

# Read the value modified by test1
e=$(read_value "${tmp_file}")
echo "$e"

The drawback is that you might need multiple temp files for different variables. And also you might need to issue a sync command to persist the contents on the disk between one write and read operations.

Get the index of a certain value in an array in PHP

Could you be a little more specific?

$key = array_search('string2',$list)

works fine for me. Are you trying to accomplish something more complex?

How to change the icon of .bat file programmatically?

One of the way you can achieve this is:

  1. Create an executable Jar file
  2. Create a batch file to run the above jar and launch the desktop java application.
  3. Use Batch2Exe converter and covert to batch file to Exe.
  4. During above conversion, you can change the icon to that of your choice.(must of valid .ico file)
  5. Place the short cut for the above exe on desktop.

Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)

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

EugeneXa mentioned it in a comment, but it deserves to be an answer:

var template = $("#modal_template").html().trim();

This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:

var markup = Mustache.render(template, data);
$(markup).appendTo(container);

How to get the squared symbol (²) to display in a string

No need to get too complicated. If all you need is ² then use the unicode representation.

http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts

(which is how I assume you got the ² to appear in your question. )

How to use SearchView in Toolbar Android

Implementing the SearchView without the use of the menu.xml file and open through button

In your Activity we need to use the method of the onCreateOptionsMenumethod in which we will programmatically inflate the SearchView

private MenuItem searchMenu;
private String mSearchString="";

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);


        SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
        mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
        mSearchView.setMaxWidth(Integer.MAX_VALUE);

        searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
        searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);


        assert searchManager != null;
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        mSearchView.setIconifiedByDefault(false);

        SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
            public boolean onQueryTextChange(String newText) {
                mSearchString = newText;

                return true;
            }

            public boolean onQueryTextSubmit(String query) {
                mSearchString = query;

                searchMenu.collapseActionView();


                return true;
            }
        };

        mSearchView.setOnQueryTextListener(queryTextListener);


        return true;
    }

And in your Activity class, you can open the SearchView on any button click on toolbar like below

YOUR_BUTTON.setOnClickListener(view -> {

            searchMenu.expandActionView();

        });

Artificially create a connection timeout error

How about a software solution:

Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.

What is the difference between an abstract function and a virtual function?

The answer has been provided a number of times but the the question about when to use each is a design-time decision. I would see it as good practice to try to bundle common method definitions into distinct interfaces and pull them into classes at appropriate abstraction levels. Dumping a common set of abstract and virtual method definitions into a class renders the class unistantiable when it may be best to define a non-abstract class that implements a set of concise interfaces. As always, it depends on what best suits your applications specific needs.

How to kill a running SELECT statement

To kill a session in Oracle, you use the ALTER SYSTEM KILL SESSION command.

Details here: http://www.oracle-base.com/articles/misc/KillingOracleSessions.php

Angular2 equivalent of $document.ready()

the accepted answer is not correct, and it makes no sens to accept it considering the question

ngAfterViewInit will trigger when the DOM is ready

whine ngOnInit will trigger when the page component is only starting to be created

How do I get just the date when using MSSQL GetDate()?

It's database specific. You haven't specified what database engine you are using.

e.g. in PostgreSQL you do cast(myvalue as date).

Reading int values from SqlDataReader

based on Sam Holder's answer, you could make an extension method for that

namespace adonet.extensions
{
  public static class AdonetExt
  {
    public static int GetInt32(this SqlDataReader reader, string columnName)
    {
      return reader.GetInt32(reader.GetOrdinal(columnName));
    }
  }
}

and use it like this

using adonet.extensions;

//...

int farmsize = reader.GetInt32("farmsize");

assuming there is no GetInt32(string) already in SqlDataReader - if there is any, just use some other method name instead

Array of an unknown length in C#

A little background information:

As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.

And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.

Best practice multi language website

Database work:

Create Language Table ‘languages’:

Fields:

language_id(primary and auto increamented)

language_name

created_at

created_by

updated_at

updated_by

Create a table in database ‘content’:

Fields:

content_id(primary and auto incremented)

main_content

header_content

footer_content

leftsidebar_content

rightsidebar_content

language_id(foreign key: referenced to languages table)

created_at

created_by

updated_at

updated_by

Front End Work:

When user selects any language from dropdown or any area then save selected language id in session like,

$_SESSION['language']=1;

Now fetch data from database table ‘content’ based on language id stored in session.

Detail may found here http://skillrow.com/multilingual-website-in-php-2/

Add hover text without javascript like we hover on a user's reputation

The title attribute also works well with other html elements, for example a link...

<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>

how to display progress while loading a url to webview in android?

You need to set an own WebViewClient for your WebView by extending the WebViewClient class.

You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).

More guidance for this topic can be found in Google's WebView tutorial

Android: converting String to int

It's already a string? Remove the getText() call.

int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

How do I create a WPF Rounded Corner container?

I just had to do this myself, so I thought I would post another answer here.

Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.

The xaml:

<Border
    Width="200"
    Height="25"
    CornerRadius="11"
    Background="#FF919194"
>
    <Border.Clip>
        <RectangleGeometry
            RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
            RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
        >
            <RectangleGeometry.Rect>
                <MultiBinding
                    Converter="{StaticResource widthAndHeightToRectConverter}"
                >
                    <Binding
                        Path="ActualWidth"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                    <Binding
                        Path="ActualHeight"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                </MultiBinding>
            </RectangleGeometry.Rect>
        </RectangleGeometry>
    </Border.Clip>

    <Rectangle
        Width="100"
        Height="100"
        Fill="Blue"
        HorizontalAlignment="Left"
        VerticalAlignment="Center"
    />
</Border>

The code for the converter:

public class WidthAndHeightToRectConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double width = (double)values[0];
        double height = (double)values[1];
        return new Rect(0, 0, width, height);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

I use serializable classes for the WCF communication between different modules. Below is an example of serializable class which serves as DataContract as well. My approach is to use the power of LINQ to convert the Dictionary into out-of-the-box serializable List<> of KeyValuePair<>:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Xml.Serialization;

    namespace MyFirm.Common.Data
    {
        [DataContract]
        [Serializable]
        public class SerializableClassX
        {
            // since the Dictionary<> class is not serializable,
            // we convert it to the List<KeyValuePair<>>
            [XmlIgnore]
            public Dictionary<string, int> DictionaryX 
            {
                get
                {
                    return  SerializableList == null ? 
                            null :
                            SerializableList.ToDictionary(item => item.Key, item => item.Value);
                }

                set
                {
                    SerializableList =  value == null ?
                                        null :
                                        value.ToList();
                }
            }

            [DataMember]
            [XmlArray("SerializableList")]
            [XmlArrayItem("Pair")]
            public List<KeyValuePair<string, int>> SerializableList { get; set; }
        }
    }

The usage is straightforward - I assign a dictionary to my data object's dictionary field - DictionaryX. The serialization is supported inside the SerializableClassX by conversion of the assigned dictionary into the serializable List<> of KeyValuePair<>:

    // create my data object
    SerializableClassX SerializableObj = new SerializableClassX(param);

    // this will call the DictionaryX.set and convert the '
    // new Dictionary into SerializableList
    SerializableObj.DictionaryX = new Dictionary<string, int>
    {
        {"Key1", 1},
        {"Key2", 2},
    };

css transition opacity fade background

http://jsfiddle.net/6xJQq/13/

.container {
    display: inline-block;
    padding: 5px; /*included padding to see background when img apacity is 100%*/
    background-color: black;
    opacity: 1;
}

.container:hover {
    background-color: red;
}

img {
    opacity: 1;
}

img:hover {
    opacity: 0.7;
}

.transition {
    transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -webkit-transition: all .25s  ease-in-out;
}

SQL Server equivalent of MySQL's NOW()?

getdate() or getutcdate().

How to git ignore subfolders / subdirectories?

You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:

Debug/
Release/

This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.

Virtual network interface in Mac OS X

In regards to @bmasterswizzle's BRILLIANT answer - more specifically - to @DanRamos' question about how to force the new interface's link-state to "up".. I use this script, of whose origin I cannot recall, but which works fabulously (in coordination with @bmasterswizzles "Mona Lisa" of answers)...

#!/bin/zsh

[[ "$UID" -ne "0" ]] && echo "You must be root. Goodbye..." && exit 1
echo "starting"
exec 4<>/dev/tap0
ifconfig tap0 10.10.10.1 10.10.10.255
ifconfig tap0 up
ping -c1 10.10.10.1
echo "ending"
export PS1="tap interface>"
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

I am NOT quite sure I understand the alteration to the prompt at the end, or...

dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

but WHATEVER. it works. link light: green?. loves it.

enter image description here

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

When do I use the PHP constant "PHP_EOL"?

I found PHP_EOL very useful for file handling, specially if you are writing multiple lines of content into a file.

For example, you have a long string that you want to break into the multiple lines while writing into plain file. Using \r\n might not work so simply put PHP_EOL into your script and the result is awesome.

Check out this simple example below:

<?php

$output = 'This is line 1' . PHP_EOL .
          'This is line 2' . PHP_EOL .
          'This is line 3';

$file = "filename.txt";

if (is_writable($file)) {
    // In our example we're opening $file in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $output will go when we fwrite() it.
    if (!$handle = fopen($file, 'a')) {
         echo "Cannot open file ($file)";
         exit;
    }
    // Write $output to our opened file.
    if (fwrite($handle, $output) === FALSE) {
        echo "Cannot write to file ($file)";
        exit;
    }
    echo "Success, content ($output) wrote to file ($file)";
    fclose($handle);
} else {
    echo "The file $file is not writable";
}
?>

c# how to add byte to byte array

Although internally it creates a new array and copies values into it, you can use Array.Resize<byte>() for more readable code. Also you might want to consider checking the MemoryStream class depending on what you're trying to achieve.

SVN - Checksum mismatch while updating

My solution was:

  1. Execute svn cleanup from file system
  2. Switch to another branch
  3. Solve conflicts
  4. Switch to the "problematic" branch
  5. Execute cleanup from Spring Tool Suite
  6. Execute Project Update

Passing variables to the next middleware using next() in Express.js

Attach your variable to the req object, not res.

Instead of

res.somevariable = variable1;

Have:

req.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.

How do I detect IE 8 with jQuery?

You should also look at jQuery.support. Feature detection is a lot more reliable than browser detection for coding your functionality (unless you are just trying to log browser versions).

Url.Action parameters?

This works for MVC 5:

<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
    Link text
</a>

How to get HttpClient to pass credentials along with the request?

In .NET Core, I managed to get a System.Net.Http.HttpClient with UseDefaultCredentials = true to pass through the authenticated user's Windows credentials to a back end service by using WindowsIdentity.RunImpersonated.

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true } );
HttpResponseMessage response = null;

if (identity is WindowsIdentity windowsIdentity)
{
    await WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, async () =>
    {
        var request = new HttpRequestMessage(HttpMethod.Get, url)
        response = await client.SendAsync(request);
    });
}

Using 24 hour time in bootstrap timepicker

<input type="text" name="time" data-provide="timepicker"  id="time" class="form-control" placeholder="Start Time" value="" />


$('#time').timepicker({
        timeFormat: 'H:i',
        'scrollDefaultNow'      : 'true',
        'closeOnWindowScroll'   : 'true',
        'showDuration'          : false,
        'ignoreReadonly'        : true,

})

work for me.

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:

$2a$COST$BASE64

This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

From MYSQL I solved the problem like this:

SUM(CASE WHEN used = 1 THEN 1 ELSE 0 END) as amount_one,

Hope this helps :D

Is it valid to define functions in JSON results?

The problem is that JSON as a data definition language evolved out of JSON as a JavaScript Object Notation. Since Javascript supports eval on JSON, it is legitimate to put JSON code inside JSON (in that use-case). If you're using JSON to pass data remotely, then I would say it is bad practice to put methods in the JSON because you may not have modeled your client-server interaction well. And, further, when wishing to use JSON as a data description language I would say you could get yourself into trouble by embedding methods because some JSON parsers were written with only data description in mind and may not support method definitions in the structure.

Wikipedia JSON entry makes a good case for not including methods in JSON, citing security concerns:

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON compliant, you should avoid eval() and use JSON.parse() or another JSON specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

Rounding a number to the nearest 5 or 10 or X

Try this function

--------------start----------------

Function Round_Up(ByVal d As Double) As Integer
    Dim result As Integer
    result = Math.Round(d)
    If result >= d Then
        Round_Up = result
    Else
        Round_Up = result + 1
    End If
End Function

-------------end ------------

WCF change endpoint address at runtime

So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);   
var client = new EchoServiceClient(address); 
litResponse.Text = client.SendEcho("Hello World"); 
client.Close();

Actual working final version by valamas

EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close(); 

Disabling Log4J Output in Java

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
    logger.setLevel(Level.OFF);
}

How to change root logging level programmatically for logback

Try this:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);

Note that you can also tell logback to periodically scan your config file like this:

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration> 

How to read .pem file to get private and public key

If a PEM contains only one RSA private key without encryption, it must be an ASN.1 sequence structure including 9 numbers to present a Chinese Remainder Theorem (CRT) key:

  1. version (always 0)
  2. modulus (n)
  3. public exponent (e, always 65537)
  4. private exponent (d)
  5. prime p
  6. prime q
  7. d mod (p - 1) (dp)
  8. d mod (q - 1) (dq)
  9. q^-1 mod p (qinv)

We can implement an RSAPrivateCrtKey:

class RSAPrivateCrtKeyImpl implements RSAPrivateCrtKey {
    private static final long serialVersionUID = 1L;

    BigInteger n, e, d, p, q, dp, dq, qinv;

    @Override
    public BigInteger getModulus() {
        return n;
    }

    @Override
    public BigInteger getPublicExponent() {
        return e;
    }

    @Override
    public BigInteger getPrivateExponent() {
        return d;
    }

    @Override
    public BigInteger getPrimeP() {
        return p;
    }

    @Override
    public BigInteger getPrimeQ() {
        return q;
    }

    @Override
    public BigInteger getPrimeExponentP() {
        return dp;
    }

    @Override
    public BigInteger getPrimeExponentQ() {
        return dq;
    }

    @Override
    public BigInteger getCrtCoefficient() {
        return qinv;
    }

    @Override
    public String getAlgorithm() {
        return "RSA";
    }

    @Override
    public String getFormat() {
        throw new UnsupportedOperationException();
    }

    @Override
    public byte[] getEncoded() {
        throw new UnsupportedOperationException();
    }
}

Then read the private key from a PEM file:

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

static RSAPrivateCrtKey getRSAPrivateKey(String keyFile) {
    RSAPrivateCrtKeyImpl prvKey = new RSAPrivateCrtKeyImpl();
    try (BufferedReader in = new BufferedReader(new FileReader(keyFile))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            // skip "-----BEGIN/END RSA PRIVATE KEY-----"
            if (!line.startsWith("--") || !line.endsWith("--")) {
                sb.append(line);
            }
        }
        DerInputStream der = new DerValue(Base64.
                getDecoder().decode(sb.toString())).getData();
        der.getBigInteger(); // 0
        prvKey.n = der.getBigInteger();
        prvKey.e = der.getBigInteger(); // 65537
        prvKey.d = der.getBigInteger();
        prvKey.p = der.getBigInteger();
        prvKey.q = der.getBigInteger();
        prvKey.dp = der.getBigInteger();
        prvKey.dq = der.getBigInteger();
        prvKey.qinv = der.getBigInteger();
    } catch (IllegalArgumentException | IOException e) {
        logger.warn(keyFile + ": " + e.getMessage());
        return null;
    }
}

Include PHP inside JavaScript (.js) files

AddType application/x-httpd-php .js

AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Add the above code in .htaccess file and run php inside js files

DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).

If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"

How to write connection string in web.config file and read from it?

After opening the web.config file in application, add sample db connection in connectionStrings section like this:

<connectionStrings>  
    <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   
</connectionStrings>  

Declaring connectionStrings in web.config file:

 <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient" />   

There is no need of username and password to access the database server. Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

using System.Configuration;

This namespace is used to get configuration section details from web.config file.

using System;  
using System.Data.SqlClient;  
using System.Configuration;  
public partial class _Default: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {  
        //Get connection string from web.config file  
        string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
        //create new sqlconnection and connection to database by using connection string from web.config file  
        SqlConnection con = new SqlConnection(strcon);  
        con.Open();  
    }  
}  

JComboBox Selection Change Listener?

It should respond to ActionListeners, like this:

combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
});

@John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?

How can I make a countdown with NSTimer?

Swift 5 with Closure:

class ViewController: UIViewController {
    
var secondsRemaining = 30
    
@IBAction func startTimer(_ sender: UIButton) {
        
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
        if self.secondsRemaining > 0 {
            print ("\(self.secondsRemaining) seconds")
            self.secondsRemaining -= 1
        } else {
            Timer.invalidate()
        }
    }
            
}

CSS background image alt attribute

The classical way to achieve this is to put the text into the div and use an image replacement technique.

<div class"ir background-image">Your alt text</div>

with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

python: iterate a specific range in a list

A more memory efficient way to iterate over a slice of a list would be to use islice() from the itertools module:

from itertools import islice

listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])

for item in islice(listOfStuff, 1, 3):
    print item

# ['c', 'd']
# ['e', 'f']

However, this can be relatively inefficient in terms of performance if the start value of the range is a large value sinceislicewould have to iterate over the first start value-1 items before returning items.

String date to xmlgregoriancalendar conversion

For me the most elegant solution is this one:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");

Using Java 8.

Extended example:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());

This prints out:

7
1
2014

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I tried almost all the above and nothing worked.

Only when I set the referenced DLLs in the Default Project EntityFramework and EntityFramework.SqlServer properties Copy Local to True did it start working!

How can I pair socks from a pile efficiently?

I came out with another solution which would not promise fewer operations, neither less time consumption, but it should be tried to see if it can be a good-enough heuristic to provide less time consumption in huge series of sock pairing.

Preconditions: There is no guarantee that there are the same socks. If they are of the same color it doesn't mean they have the same size or pattern. Socks are randomly shuffled. There can be odd number of socks (some are missing, we don't know how many). Prepare to remember a variable "index" and set it to 0.

The result will have one or two piles: 1. "matched" and 2. "missing"

Heuristic:

  1. Find most distinctive sock.
  2. Find its match.
  3. If there is no match, put it on the "missing" pile.
  4. Repeat from 1. until there are no more most distinctive socks.
  5. If there are less then 6 socks, go to 11.
  6. Pair blindly all socks to its neighbor (do not pack it)
  7. Find all matched pairs, pack it and move packed pairs to "matched" pile; If there were no new matches - increment "index" by 1
  8. If "index" is greater then 2 (this could be value dependent on sock number because with greater number of socks there are less chance to pair them blindly) go to 11
  9. Shuffle the rest
  10. Go to 1
  11. Forget "index"
  12. Pick a sock
  13. Find its pair
  14. If there is no pair for the sock, move it to the "missing" pile
  15. If match found pair it, pack pair and move it to the "matched" pile
  16. If there are still more then one socks go to 12
  17. If there is just one left go to 14
  18. Smile satisfied :)

Also, there could be added check for damaged socks also, as if the removal of those. It could be inserted between 2 and 3, and between 13 and 14.

I'm looking forward to hear about any experiences or corrections.

Multiple modals overlay

My solution for bootstrap 4, working with unlimited depth of modals and dynamic modal.

$('.modal').on('show.bs.modal', function () {
    var $modal = $(this);
    var baseZIndex = 1050;
    var modalZIndex = baseZIndex + ($('.modal.show').length * 20);
    var backdropZIndex = modalZIndex - 10;
    $modal.css('z-index', modalZIndex).css('overflow', 'auto');
    $('.modal-backdrop.show:last').css('z-index', backdropZIndex);
});
$('.modal').on('shown.bs.modal', function () {
    var baseBackdropZIndex = 1040;
    $('.modal-backdrop.show').each(function (i) {
        $(this).css('z-index', baseBackdropZIndex + (i * 20));
    });
});
$('.modal').on('hide.bs.modal', function () {
    var $modal = $(this);
    $modal.css('z-index', '');
});

Passing arguments to JavaScript function from code-behind

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

        function test(x, y) 
        {
            var cc = "";
            for (var i = 0; i < x.length; i++) 
            {
                cc += x[i]; 
            }
            cc += "\ny: " + y; 
            return cc;
        }

    </script>



</head>

<body>

    <form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Button"   />

        <p>
             <asp:TextBox ID="TextBox1"  Name="TextBox1"  runat="server" AutoPostBack="True"  TextMode="MultiLine"></asp:TextBox>
        </p>



    </form>
</body>

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

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

    string script = String.Format(" var y = test({0},{1}) ; ", xStr, yStr);
    script += String.Format("  document.getElementById(\"TextBox1\").value = y  ");

    this.Page.ClientScript.RegisterStartupScript(this.GetType(),  "testFunction", script, true);
  //  this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "testFunction", script, true); // different result
}




private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}

Can I use jQuery to check whether at least one checkbox is checked?

$('#frmTest').submit(function(){
    if(!$('#frmTest input[type="checkbox"]').is(':checked')){
      alert("Please check at least one.");
      return false;
    }
});

is(':checked') will return true if at least one or more of the checkboxes are checked.

Onclick event to remove default value in a text input field

Use onclick="this.value=''":

<input name="Name" value="Enter Your Name" onclick="this.value=''">

Fastest Way to Find Distance Between Two Lat/Long Points

if you are using MySQL 5.7.*, then you can use st_distance_sphere(POINT, POINT).

Select st_distance_sphere(POINT(-2.997065, 53.404146 ), POINT(58.615349, 23.56676 ))/1000  as distcance

How to test Spring Data repositories?

This may come a bit too late, but I have written something for this very purpose. My library will mock out the basic crud repository methods for you as well as interpret most of the functionalities of your query methods. You will have to inject functionalities for your own native queries, but the rest are done for you.

Take a look:

https://github.com/mmnaseri/spring-data-mock

UPDATE

This is now in Maven central and in pretty good shape.

Check if file exists and whether it contains a specific string

You should use the grep -q flag for quiet output. See the man pages below:

man grep output :

 General Output Control

  -q, --quiet, --silent
              Quiet;  do  not write anything to standard output.  Exit immediately with zero status
              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or
              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

grepUtil.ksh :

#!/bin/ksh

#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"

#Function to initialize variables
initialize(){
    echo "Entering initialize"
    echo "Exiting initialize"
}

#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
    echo "Entering createFileWithInput"
    orgDirectory=${PWD}
    cd ${1}
    > ${2}
    print ${3} >> ${2}
    cd ${orgDirectory}
    echo "Exiting createFileWithInput"
}

#Function to create File with Input
#Params: 1}directoryName
createDir(){
    echo "Entering createDir"
    mkdir -p ${1}
    echo "Exiting createDir"
}

#Params: 1}FileName
readLine(){
    echo "Entering readLine"
    file=${1}
    while read line
    do
        #assign last line to var
        var="$line"
    done <"$file"
    echo "Exiting readLine"
}
#Check if file exists 
#Params: 1}File
doesFileExit(){
    echo "Entering doesFileExit"
    orgDirectory=${PWD}
    cd ${PWD}${dirPath}
    #echo ${PWD}
    if [[ -e "${1}" ]]; then
        echo "${1} exists"
    else
        echo "${1} does not exist"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
    echo "Entering doesFileContainStringQuiet"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep -q ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
    echo "Entering doesFileContainString"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainString"
}

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
    doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh

$(window).scrollTop() vs. $(document).scrollTop()

Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());

Reset all the items in a form

You can create the form again and dispose the old one.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnReset_Click(object sender, EventArgs e)
    {
        Form1 NewForm = new Form1();           
        NewForm.Show();
        this.Dispose(false);
    }
}

'Incorrect SET Options' Error When Building Database Project

In my case I was trying to create a table from one database to another on MS SQL Server 2012. Right-clicking on a table and selecting Script Table as > DROP And CREATE To > New Query Editor Window, following script was created:

USE [SAMPLECOMPANY]
GO

ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO

/****** Object:  Table [dbo].[Employees]    Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO

/****** Object:  Table [dbo].[Employees]    Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employees](
    [EmployeeId] [int] IDENTITY(1,1) NOT NULL,
    [DepartmentId] [int] NOT NULL,
    [FullName] [varchar](50) NOT NULL,
    [HireDate] [datetime] NULL
 CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED 
(
    [EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Employees]  WITH CHECK ADD  CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO

ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO

However when executing above script it was returning the error:

SELECT failed because the following SET options have incorrect settings: 'ANSI_PADDING'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.

The Solution I've found: Enabling the settings on the Top of the script like this:

USE [SAMPLECOMPANY]
GO
/****** Object:  Table [dbo].[Employees]    Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO

/****** Object:  Table [dbo].[Employees]    Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO



CREATE TABLE [dbo].[Employees](
    [EmployeeId] [int] IDENTITY(1,1) NOT NULL,
    [DepartmentId] [int] NOT NULL,
    [FullName] [varchar](50) NOT NULL,
    [HireDate] [datetime] NULL
 CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED 
(
    [EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Employees]  WITH CHECK ADD  CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO

ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO

SET ANSI_PADDING OFF
GO

Hope this help.

Method to Add new or update existing item in Dictionary

There's no problem. I would even remove the CreateNewOrUpdateExisting from the source and use map[key] = value directly in your code, because this this is much more readable, because developers would usually know what map[key] = value means.

Should each and every table have a primary key?

I am in the role of maintaining application created by offshore development team. Now I am having all kinds of issues in the application because original database schema did not contain PRIMARY KEYS on some tables. So please dont let other people suffer because of your poor design. It is always good idea to have primary keys on tables.

Android Fragments and animation

I solve this the way Below

Animation anim = AnimationUtils.loadAnimation(this, R.anim.slide);
fg.startAnimation(anim);
this.fg.setVisibility(View.VISIBLE); //fg is a View object indicate fragment

How to save a pandas DataFrame table as a png

I had the same requirement for a project I am doing. But none of the answers came elegant to my requirement. Here is something which finally helped me, and might be useful for this case:

from bokeh.io import export_png, export_svgs
from bokeh.models import ColumnDataSource, DataTable, TableColumn

def save_df_as_image(df, path):
    source = ColumnDataSource(df)
    df_columns = [df.index.name]
    df_columns.extend(df.columns.values)
    columns_for_table=[]
    for column in df_columns:
        columns_for_table.append(TableColumn(field=column, title=column))

    data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
    export_png(data_table, filename = path)

enter image description here

What is the best way to modify a list in a 'foreach' loop?

I have written one easy step, but because of this performance will be degraded

Here is my code snippet:-

for (int tempReg = 0; tempReg < reg.Matches(lines).Count; tempReg++)
                            {
                                foreach (Match match in reg.Matches(lines))
                                {
                                    var aStringBuilder = new StringBuilder(lines);
                                    aStringBuilder.Insert(startIndex, match.ToString().Replace(",", " ");
                                    lines[k] = aStringBuilder.ToString();
                                    tempReg = 0;
                                    break;
                                }
                            }

Python and pip, list all versions of a package that's available?

My project luddite has this feature.

Example usage:

>>> import luddite
>>> luddite.get_versions_pypi("python-dateutil")
('0.1', '0.3', '0.4', '0.5', '1.0', '1.1', '1.2', '1.4', '1.4.1', '1.5', '2.0', '2.1', '2.2', '2.3', '2.4.0', '2.4.1', '2.4.2', '2.5.0', '2.5.1', '2.5.2', '2.5.3', '2.6.0', '2.6.1', '2.7.0', '2.7.1', '2.7.2', '2.7.3', '2.7.4', '2.7.5', '2.8.0')

It lists all versions of a package available, by querying the json API of https://pypi.org/

Issue with virtualenv - cannot activate

open the folder with any gitbash console. for example using visualCode and Gitbash console program: 1)Install Gitbash for windows

2) using VisualCode IDE, right click over the project open in terminal console option

3) on window console in Visualcode, looking for a Select->default shell and change it for Gitbash

4)now your project is open with bash console and right path, put source ./Scripts/activate

btw : . with blank space = source

enter image description here

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I too had a similar type of problem . The solution is simple . just dont try to enter NULL or None value in values or u might have to use Something like this
dic.update([(key,value)])

Make a dictionary in Python from input values

I have taken an empty dictionary as f and updated the values in f as name,password or balance are keys.

f=dict()
f.update(name=input(),password=input(),balance=input())
print(f)

How do I show/hide a UIBarButtonItem?

With credit to @lnafziger, @MindSpiker, @vishal, et. al,

The simplest one liner that I arrived at for a single right (or left) bar button is:

self.navigationItem.rightBarButtonItem = <#StateExpression#>
    ? <#StrongPropertyButton#> : nil;

As in:

@interface MyClass()

@property (strong, nonatomic) IBOutlet UIBarButtonItem *<#StrongPropertyButton#>;

@end

@implementation

- (void) updateState
{
    self.navigationItem.rightBarButtonItem = <#StateExpression#>
        ? <#StrongPropertyButton#> : nil;
}

@end

I tested this and it works for me (with the strong bar button item wired via IB).

SPAN vs DIV (inline-block)

As others have answered… div is a “block element” (now redefined as Flow Content) and span is an “inline element” (Phrasing Content). Yes, you may change the default presentation of these elements, but there is a difference between “flow” versus “block”, and “phrasing” versus “inline”.

An element classified as flow content can only be used where flow content is expected, and an element classified as phrasing content can be used where phrasing content is expected. Since all phrasing content is flow content, a phrasing element can also be used anywhere flow content is expected. The specs provide more detailed info.

All phrasing elements, such as strong and em, can only contain other phrasing elements: you can’t put a table inside a cite for instance. Most flow content such as div and li can contain all types of flow content (as well as phrasing content), but there are a few exceptions: p, pre, and th are examples of non-phrasing flow content (“block elements”) that can only contain phrasing content (“inline elements”). And of course there are the normal element restrictions such as dl and table only being allowed to contain certain elements.

While both div and p are non-phrasing flow content, the div can contain other flow content children (including more divs and ps). On the other hand, p may only contain phrasing content children. That means you can’t put a div inside a p, even though both are non-phrasing flow elements.

Now here’s the kicker. These semantic specifications are unrelated to how the element is displayed. Thus, if you have a div inside a span, you will get a validation error even if you have span {display: block;} and div {display: inline;} in your CSS.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'

As a function:

def yesterday(string=False):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

Accessing variables from other functions without using global variables

What you're looking for is technically known as currying.

function getMyCallback(randomValue)
{
    return function(otherParam)
    {
        return randomValue * otherParam //or whatever it is you are doing.
    }

}

var myCallback = getMyCallBack(getRand())

alert(myCallBack(1));
alert(myCallBack(2));

The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.

Auto generate function documentation in Visual Studio

You can use code snippets to insert any lines you want.

Also, if you type three single quotation marks (''') on the line above the function header, it will insert the XML header template that you can then fill out.

These XML comments can be interpreted by documentation software, and they are included in the build output as an assembly.xml file. If you keep that XML file with the DLL and reference that DLL in another project, those comments become available in intellisense.

How do I change the data type for a column in MySQL?

If you want to change all columns of a certain type to another type, you can generate queries using a query like this:

select distinct concat('alter table ',
                       table_name,
                       ' modify ',
                       column_name,
                       ' <new datatype> ',
                       if(is_nullable = 'NO', ' NOT ', ''),
                       ' NULL;')
  from information_schema.columns
  where table_schema = '<your database>' 
    and column_type = '<old datatype>';

For instance, if you want to change columns from tinyint(4) to bit(1), run it like this:

select distinct concat('alter table ',
                       table_name,
                       ' modify ',
                       column_name,
                       ' bit(1) ',
                       if(is_nullable = 'NO', ' NOT ', ''),
                       ' NULL;')
  from information_schema.columns
  where table_schema = 'MyDatabase' 
    and column_type = 'tinyint(4)';

and get an output like this:

alter table table1 modify finished bit(1)  NOT  NULL;
alter table table2 modify canItBeTrue bit(1)  NOT  NULL;
alter table table3 modify canBeNull bit(1)  NULL;

!! Does not keep unique constraints, but should be easily fixed with another if-parameter to concat. I'll leave it up to the reader to implement that if needed..

CSS height 100% percent not working

For code mirror divs refer to the manual, these sections might be useful to you:

http://codemirror.net/demo/fullscreen.html

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  theme: "night",
  extraKeys: {
    "F11": function(cm) {
      cm.setOption("fullScreen", !cm.getOption("fullScreen"));
    },
    "Esc": function(cm) {
      if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
    }
  }
});

And also take a look at:

http://codemirror.net/demo/resize.html

Also a comment:

Inline styling is horrible you should avoid this at all costs, not only will it confuse you, it's poor practice.

How can I use mySQL replace() to replace strings in multiple records?

UPDATE some_table SET some_field = REPLACE(some_field, '&lt;', '<')

htaccess redirect to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Notes: Make sure you have done the following steps

  1. sudo a2enmod rewrite
  2. sudo service apache2 restart
  3. Add Following in your vhost file, located at /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  allow from all
  Require all granted
</Directory>

Now your .htaccess will work and your site will redirect to http:// to https://www

Combining node.js and Python

Update 2019

There are several ways to achieve this and here is the list in increasing order of complexity

  1. Python Shell, you will write streams to the python console and it will write back to you
  2. Redis Pub Sub, you can have a channel listening in Python while your node js publisher pushes data
  3. Websocket connection where Node acts as the client and Python acts as the server or vice-versa
  4. API connection with Express/Flask/Tornado etc working separately with an API endpoint exposed for the other to query

Approach 1 Python Shell Simplest approach

source.js file

const ps = require('python-shell')
// very important to add -u option since our python script runs infinitely
var options = {
    pythonPath: '/Users/zup/.local/share/virtualenvs/python_shell_test-TJN5lQez/bin/python',
    pythonOptions: ['-u'], // get print results in real-time
    // make sure you use an absolute path for scriptPath
    scriptPath: "./subscriber/",
    // args: ['value1', 'value2', 'value3'],
    mode: 'json'
};

const shell = new ps.PythonShell("destination.py", options);

function generateArray() {
    const list = []
    for (let i = 0; i < 1000; i++) {
        list.push(Math.random() * 1000)
    }
    return list
}

setInterval(() => {
    shell.send(generateArray())
}, 1000);

shell.on("message", message => {
    console.log(message);
})

destination.py file

import datetime
import sys
import time
import numpy
import talib
import timeit
import json
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

size = 1000
p = 100
o = numpy.random.random(size)
h = numpy.random.random(size)
l = numpy.random.random(size)
c = numpy.random.random(size)
v = numpy.random.random(size)

def get_indicators(values):
    # Return the RSI of the values sent from node.js
    numpy_values = numpy.array(values, dtype=numpy.double) 
    return talib.func.RSI(numpy_values, 14)

for line in sys.stdin:
    l = json.loads(line)
    print(get_indicators(l))
    # Without this step the output may not be immediately available in node
    sys.stdout.flush()

Notes: Make a folder called subscriber which is at the same level as source.js file and put destination.py inside it. Dont forget to change your virtualenv environment

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

Resize command prompt through commands

I know, that's a 8 years old question, but that can still happen today.

Powershell ca be used for that. An example is shown here. The shortest command for the cmd is:

powershell -command "&{(get-host).ui.rawui.windowsize=@{width=100;height=55};}"

Set your wanted window size to the width and hight vars. However, this short line has two limitations:

  • Be sure that the window size is not larger than the predefined buffer sizes. Otherwise there occur an error message.
  • Depending on the system, loading and processing of Powershell takes 2...4 seconds. Sometimes this is a long time to wait.

To avoid that, in the command below the buffer size is defined. In addition, the process runs parallel to the other following cmd commands:

start /b powershell -command "&{$w=(get-host).ui.rawui;$w.buffersize=@{width=177;height=999};$w.windowsize=@{width=155;height=55};}"

The width and height values to the buffersize object, here 177 and 999, must be bigger or equal to the window size values.

The EntityManager is closed

For what it's worth I found this issue was happening in a batch import command because of a try/catch loop catching an SQL error (with em->flush()) that I didn't do anything about. In my case it was because I was trying to insert a record with a non-nullable property left as null.

Typically this would cause a critical exception to happen and the command or controller to halt, but I was just logging this problem instead and carrying on. The SQL error had caused the entity manager to close.

Check your dev.log file for any silly SQL errors like this as it could be your fault. :)

MATLAB, Filling in the area between two sets of data, lines in one figure

Personally, I find it both elegant and convenient to wrap the fill function. To fill between two equally sized row vectors Y1 and Y2 that share the support X (and color C):

fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)],  [Y1 fliplr(Y2)], C );

MySQL "WITH" clause

Have you ever tried Temporary Table? This solved my convern:

create temporary table abc (
column1 varchar(255)
column2 decimal
);
insert into abc
select ...
or otherwise
insert into abc
values ('text', 5.5), ('text2', 0815.8);

Then you can use this table in every select in this session:

select * from abc inner join users on ...;

Generics/templates in python?

Fortunately there has been some efforts for the generic programming in python . There is a library : generic

Here is the documentation for it: http://generic.readthedocs.org/en/latest/

It hasn't progress over years , but you can have a rough idea how to use & make your own library.

Cheers

How to set dropdown arrow in spinner?

                   <Spinner
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="16dp"
                    android:paddingLeft="10dp"
                    android:spinnerMode="dropdown" />

Remove blank attributes from an Object in Javascript

JSON.stringify removes the undefined keys.

removeUndefined = function(json){
  return JSON.parse(JSON.stringify(json))
}

Pass a PHP array to a JavaScript function

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });

How to set the title text color of UIButton?

Swift UI solution

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))

Swift 3, Swift 4, Swift 5

to improve comments. This should work:

button.setTitleColor(.red, for: .normal)

Javascript to sort contents of select element

Vanilla JS es6 Localization Options Sorting Example

const optionNodes = Array.from(selectNode.children);
const comparator = new Intl.Collator(lang.slice(0, 2)).compare;

optionNodes.sort((a, b) => comparator(a.textContent, b.textContent));
optionNodes.forEach((option) => selectNode.appendChild(option));

My use case was to localize a country select dropdown with locale aware sorting. This was used on 250 + options and was very performant ~10ms on my machine.

How to deal with page breaks when printing a large HTML table

I recently solved this problem with a good solution.

CSS:

.avoidBreak { 
    border: 2px solid;
    page-break-inside:avoid;
}

JS:

function Print(){
    $(".tableToPrint td, .tableToPrint th").each(function(){ $(this).css("width",  $(this).width() + "px")  });
    $(".tableToPrint tr").wrap("<div class='avoidBreak'></div>");
    window.print();
}

Works like a charm!

How to merge a specific commit in Git

In my use case we had a similar need for CI CD. We used git flow with develop and master branches. Developers are free to merge their changes directly to develop or via a pull request from a feature branch. However to master we merge only the stable commits from the develop branch in an automated way via Jenkins.

In this case doing cherry-pick is not a good option. However we create a local-branch from the commit-id then merge that local-branch to master and perform mvn clean verify(we use maven). If success then release production version artifact to nexus using maven release plugin with localCheckout=true option and pushChanges=false. Finally when everything is success then push the changes and tag to origin.

A sample code snippet:

Assuming you are on master if done manually. However on jenkins, when you checkout the repo you will be on the default branch(master if configured).

git pull  // Just to pull any changes.
git branch local-<commitd-id> <commit-id>  // Create a branch from the given commit-id
git merge local-<commit-id>  // Merge that local branch to master.
mvn clean verify   // Verify if the code is build able
mvn <any args> release:clean release:prepare release:perform // Release artifacts
git push origin/master  // Push the local changes performed above to origin.
git push origin <tag>  // Push the tag to origin

This will give you a full control with a fearless merge or conflict hell.

Feel free to advise in case there is any better option.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to transform numpy.matrix or array to scipy sparse matrix

As for the inverse, the function is inv(A), but I won't recommend using it, since for huge matrices it is very computationally costly and unstable. Instead, you should use an approximation to the inverse, or if you want to solve Ax = b you don't really need A-1.

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

Why is my asynchronous function returning Promise { <pending> } instead of a value?

I had the same issue earlier, but my situation was a bit different in the front-end. I'll share my scenario anyway, maybe someone might find it useful.

I had an api call to /api/user/register in the frontend with email, password and username as request body. On submitting the form(register form), a handler function is called which initiates the fetch call to /api/user/register. I used the event.preventDefault() in the beginning line of this handler function, all other lines,like forming the request body as well the fetch call was written after the event.preventDefault(). This returned a pending promise.

But when I put the request body formation code above the event.preventDefault(), it returned the real promise. Like this:

event.preventDefault();
    const data = {
        'email': email,
        'password': password
    }
    fetch(...)
     ...

instead of :

     const data = {
            'email': email,
            'password': password
        }
     event.preventDefault();
     fetch(...)
     ...

How to show progress dialog in Android?

Simple coding in your activity like below:

private ProgressDialog dialog = new ProgressDialog(YourActivity.this);    
dialog.setMessage("please wait...");
dialog.show();
dialog.dismiss();

How do you stop tracking a remote branch in Git?

This is not an answer to the question, but I couldn't figure out how to get decent code formatting in a comment above... so auto-down-reputation-be-damned here's my comment.

I have the recipe submtted by @Dobes in a fancy shmancy [alias] entry in my .gitconfig:

# to untrack a local branch when I can't remember 'git config --unset'
cbr = "!f(){ git symbolic-ref -q HEAD 2>/dev/null | sed -e 's|refs/heads/||'; }; f"
bruntrack = "!f(){ br=${1:-`git cbr`};  \
    rm=`git config --get branch.$br.remote`; \
    tr=`git config --get branch.$br.merge`; \
    [ $rm:$tr = : ] && echo \"# untrack: not a tracking branch: $br\" && return 1; \
    git config --unset branch.$br.remote; git config --unset branch.$br.merge; \
    echo \"# untrack: branch $br no longer tracking $rm:$tr\"; return 0; }; f"

Then I can just run

$ git bruntrack branchname

How to install plugins to Sublime Text 2 editor?

The instruction has been tested on Mac OSx Catalina.

After installing Sublime Text 3, install Package Control through Tools > Package Control. Use the following instructions to install package or theme:

  1. press CMD + SHIFT + P

  2. choose Package Control: Install Package---or any other options you require. package control

  3. enter the name of required package or theme and press enter.

installing package

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.

Hashing:

public static string HashPassword(string password)
{
    byte[] salt;
    byte[] buffer2;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
    {
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    }
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);
}

Verifying:

public static bool VerifyHashedPassword(string hashedPassword, string password)
{
    byte[] buffer4;
    if (hashedPassword == null)
    {
        return false;
    }
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
    {
        return false;
    }
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
    {
        buffer4 = bytes.GetBytes(0x20);
    }
    return ByteArraysEqual(buffer3, buffer4);
}

How to remove files that are listed in the .gitignore but still on the repository?

I can't say it's an appropriate solution but you can try this.

Steps

  • I am hoping that you have already cloned your repo.
  • Now copy the file somewhere outside of your project.
  • Add that filename with a location in gitigonre file.
  • Remove that file from your local project.
  • Push your code to remote origin.
  • And now add that copied file into your project it'll be ignored.

This is just a hack solution if you want to maintain the history and don't to create mass in it.

If you don't want to use this solution please kindly ignore and try to avoid devote it. Because I am really trying to increase my score on this side

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}

How to declare an array of strings in C++?

You can use the begin and end functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.

const char* array[] = { "cat", "dog", "horse" };
vector<string> vec(begin(array), end(array));

How to keep one variable constant with other one changing with row in excel

There are two kinds of cell reference, and it's really valuable to understand them well.

One is relative reference, which is what you get when you just type the cell: A5. This reference will be adjusted when you paste or fill the formula into other cells.

The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5. This cell reference will not change when pasted or filled.

A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5 and A$5. This comes in handy for producing things like multiplication tables from a single formula.

How do I check if a string contains another string in Objective-C?

NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound) {
  NSLog(@"string does not contain bla");
} else {
  NSLog(@"string contains bla!");
}

The key is noticing that rangeOfString: returns an NSRange struct, and the documentation says that it returns the struct {NSNotFound, 0} if the "haystack" does not contain the "needle".


And if you're on iOS 8 or OS X Yosemite, you can now do: (*NOTE: This WILL crash your app if this code is called on an iOS7 device).

NSString *string = @"hello bla blah";
if ([string containsString:@"bla"]) {
  NSLog(@"string contains bla!");
} else {
  NSLog(@"string does not contain bla");
}

(This is also how it would work in Swift)

join list of lists in python

This is known as flattening, and there are a LOT of implementations out there:

How about this, although it will only work for 1 level deep nesting:

>>> x = [["a","b"], ["c"]]
>>> for el in sum(x, []):
...     print el
...
a
b
c

From those links, apparently the most complete-fast-elegant-etc implementation is the following:

def flatten(l, ltypes=(list, tuple)):
    ltype = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return ltype(l)

Query for documents where array size is greater than 1

None of the above worked for me. This one did so I'm sharing it:

db.collection.find( {arrayName : {$exists:true}, $where:'this.arrayName.length>1'} )

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Really it's interesting. You need just use javax-mail.jar of "com.sun" not "javax.mail".
dwonload com.sun mail jar

What is the curl error 52 "empty reply from server"?

My case was due to SSL certificate expiration

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

What is PostgreSQL equivalent of SYSDATE from Oracle?

NOW() is the replacement of Oracle Sysdate in Postgres.

Try "Select now()", it will give you the system timestamp.

How can I use JQuery to post JSON data?

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

_x000D_
_x000D_
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: '/form/',_x000D_
    data: Data,_x000D_
    success: function(data) { alert('data: ' + data); },_x000D_
    contentType: "application/json",_x000D_
    dataType: 'json'_x000D_
});
_x000D_
_x000D_
_x000D_

AngularJS - difference between pristine/dirty and touched/untouched

$pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

Here's a CodePen that shows the difference in behavior.

Best way to include CSS? Why use @import?

Use @import in your CSS if you are using a CSS RESET, like Eric Meyer's Reset CSS v2.0, so it does it's job before applying your CSS, thus preventing conflicts.

How to pass a parameter like title, summary and image in a Facebook sharer URL

This works at the moment (Oct. 2016), but I can't guarantee how long it will last:

https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]

How to install plugin for Eclipse from .zip

To install the plug-in, unzip the file into the Eclipse installation directory (or the plug-in directory depending on how the plug-in is packaged). The plug-in will not appear until you have restarted your workspace (Reboot Eclipse).

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Vue.js dynamic images not working

You can use try catch block to help with not found images

getProductImage(id) {
          var images = require.context('@/assets/', false, /\.jpg$/)
          let productImage = ''
          try {
            productImage = images(`./product${id}.jpg`)
          } catch (error) {
            productImage = images(`./no_image.jpg`)
          }
          return productImage
},

How to create an Excel File with Nodejs?

Use exceljs library for creating and writing into existing excel sheets.

You can check this tutorial for detailed explanation.

link

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

Inversion of Control vs Dependency Injection

Since all the answers emphasize on theory I would like to demonstrate with an example first approach:

Suppose we are building an application which contains a feature to send SMS confirmation messages once the order has been shipped. We will have two classes, one is responsible for sending the SMS (SMSService), and another responsible for capturing user inputs (UIHandler), our code will look as below:

public class SMSService
{
    public void SendSMS(string mobileNumber, string body)
    {
        SendSMSUsingGateway(mobileNumber, body);
    }

    private void SendSMSUsingGateway(string mobileNumber, string body)
    {
        /*implementation for sending SMS using gateway*/
    }
}

public class UIHandler
{
    public void SendConfirmationMsg(string mobileNumber)
    {
        SMSService _SMSService = new SMSService();
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

Above implementation is not wrong but there are few issues:
-) Suppose On development environment, you want to save SMSs sent to a text file instead of using SMS gateway, to achieve this; we will end up changing the concrete implementation of (SMSService) with another implementation, we are losing flexibility and forced to rewrite the code in this case.
-) We’ll end up mixing responsibilities of classes, our (UIHandler) should never know about the concrete implementation of (SMSService), this should be done outside the classes using “Interfaces”. When this is implemented, it will give us the ability to change the behavior of the system by swapping the (SMSService) used with another mock service which implements the same interface, this service will save SMSs to a text file instead of sending to mobileNumber.

To fix the above issues we use Interfaces which will be implemented by our (SMSService) and the new (MockSMSService), basically the new Interface (ISMSService) will expose the same behaviors of both services as the code below:

public interface ISMSService
{
    void SendSMS(string phoneNumber, string body);
}

Then we will change our (SMSService) implementation to implement the (ISMSService) interface:

public class SMSService : ISMSService
{
    public void SendSMS(string mobileNumber, string body)
    {
        SendSMSUsingGateway(mobileNumber, body);
    }

    private void SendSMSUsingGateway(string mobileNumber, string body)
    {
        /*implementation for sending SMS using gateway*/
        Console.WriteLine("Sending SMS using gateway to mobile: 
        {0}. SMS body: {1}", mobileNumber, body);
    }
}

Now we will be able to create new mock up service (MockSMSService) with totally different implementation using the same interface:

public class MockSMSService :ISMSService
{
    public void SendSMS(string phoneNumber, string body)
    {
        SaveSMSToFile(phoneNumber,body);
    }

    private void SaveSMSToFile(string mobileNumber, string body)
    {
        /*implementation for saving SMS to a file*/
        Console.WriteLine("Mocking SMS using file to mobile: 
        {0}. SMS body: {1}", mobileNumber, body);
    }
}

At this point, we can change the code in (UIHandler) to use the concrete implementation of the service (MockSMSService) easily as below:

public class UIHandler
{
    public void SendConfirmationMsg(string mobileNumber)
    {
        ISMSService _SMSService = new MockSMSService();
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

We have achieved a lot of flexibility and implemented separation of concerns in our code, but still we need to do a change on the code base to switch between the two SMS Services. So we need to implement Dependency Injection.

To achieve this, we need to implement a change to our (UIHandler) class constructor to pass the dependency through it, by doing this, the code which uses the (UIHandler) can determine which concrete implementation of (ISMSService) to use:

public class UIHandler
{
    private readonly ISMSService _SMSService;

    public UIHandler(ISMSService SMSService)
    {
        _SMSService = SMSService;
    }

    public void SendConfirmationMsg(string mobileNumber)
    {
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

Now the UI form which will talk with class (UIHandler) is responsible to pass which implementation of interface (ISMSService) to consume. This means we have inverted the control, the (UIHandler) is no longer responsible to decide which implementation to use, the calling code does. We have implemented the Inversion of Control principle which DI is one type of it.

The UI form code will be as below:

class Program
{
    static void Main(string[] args)
    {
        ISMSService _SMSService = new MockSMSService(); // dependency

        UIHandler _UIHandler = new UIHandler(_SMSService);
        _UIHandler.SendConfirmationMsg("96279544480");

        Console.ReadLine();
    }
}

How do you create different variable names while in a loop?

Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break

JavaScript moving element in the DOM

Trivial with jQuery

$('#div1').insertAfter('#div3');
$('#div3').insertBefore('#div2');

If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.

$(function() {
    setInterval( function() {
        $('div:first').insertAfter($('div').eq(2));
        $('div').eq(1).insertBefore('div:first');
    }, 3000 );
});

jquery change class name

You can do This : $("#td_id").removeClass('Old_class'); $("#td_id").addClass('New_class'); Or You can do This

$("#td_id").removeClass('Old_class').addClass('New_class');

Convert String to Uri

Java's parser in java.net.URI is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog. An exception will be thrown for the vertical bar.

urllib makes it easy to convert a string to a java.net.URI. It will pre-process and escape the URL.

assertEquals("http://www.google.com/search?q=cat%7Cdog",
    Urls.createURI("http://www.google.com/search?q=cat|dog").toString());

Jenkins / Hudson environment variables

Running the command with environment variable set is also effective. Of course, you have to do it for each command you run, but you probably have a job script, so you probably only have one command per build. My job script is a python script that uses the environment to decide which python to use, so I still needed to put /usr/local/bin/python2.7 in its path:

PATH=/usr/local/bin <my-command>

Filter Java Stream to 1 and only 1 element

If you don't mind using a 3rd party library, SequenceM from cyclops-streams (and LazyFutureStream from simple-react) both a have single & singleOptional operators.

singleOptional() throws an exception if there are 0 or more than 1 elements in the Stream, otherwise it returns the single value.

String result = SequenceM.of("x")
                          .single();

SequenceM.of().single(); // NoSuchElementException

SequenceM.of(1, 2, 3).single(); // NoSuchElementException

String result = LazyFutureStream.fromStream(Stream.of("x"))
                          .single();

singleOptional() returns Optional.empty() if there are no values or more than one value in the Stream.

Optional<String> result = SequenceM.fromStream(Stream.of("x"))
                          .singleOptional(); 
//Optional["x"]

Optional<String> result = SequenceM.of().singleOptional(); 
// Optional.empty

Optional<String> result =  SequenceM.of(1, 2, 3).singleOptional(); 
// Optional.empty

Disclosure - I am the author of both libraries.

nullable object must have a value

You should change the line this.MyDateTime = myNewDT.MyDateTime.Value; to just this.MyDateTime = myNewDT.MyDateTime;

The exception you were receiving was thrown in the .Value property of the Nullable DateTime, as it is required to return a DateTime (since that's what the contract for .Value states), but it can't do so because there's no DateTime to return, so it throws an exception.

In general, it is a bad idea to blindly call .Value on a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a .HasValue check).

EDIT

Here's the code for DateTimeExtended that does not throw an exception:

class DateTimeExtended
{
    public DateTime? MyDateTime;
    public int? otherdata;

    public DateTimeExtended() { }

    public DateTimeExtended(DateTimeExtended other)
    {
        this.MyDateTime = other.MyDateTime;
        this.otherdata = other.otherdata;
    }
}

I tested it like this:

DateTimeExtended dt1 = new DateTimeExtended();
DateTimeExtended dt2 = new DateTimeExtended(dt1);

Adding the .Value on other.MyDateTime causes an exception. Removing it gets rid of the exception. I think you're looking in the wrong place.

how to call an ASP.NET c# method using javascript

You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.

in markup:

 var $Username = $("#txtUsername").val();
            var $Password = $("#txtPassword").val();

            //Call the approve method on the code behind
            $.ajax({
                type: "POST",
                url: "Pages/Mobile/Login.aspx/LoginUser",
                data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) },
                success: function (msg) {
                    if (msg.d == true) {
                        window.location.href = "Pages/Mobile/Basic/Index.aspx";
                    }
                    else {
                        //show error
                        alert('login failed');
                    }
                }
            });

In Code Behind:

/// <summary>
/// Logs in the user
/// </summary>
/// <param name="Username">The username</param>
/// <param name="Password">The password</param>
/// <returns>true if login successful</returns>
[WebMethod, ScriptMethod]
public static bool LoginUser( string Username, string Password )
{
    try
    {
        StaticStore.CurrentUser = new User( Username, Password );

        //check the login details were correct
        if ( StaticStore.CurrentUser.IsAuthentiacted )
        {
            //change the status to logged in
            StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn;

            //Store the user ID in the list of active users
            ( HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int> )[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID;

            return true;
        }
        else
        {
            return false;
        }
    }
    catch ( Exception ex )
    {
        return false;
    }
}

How to correctly use "section" tag in HTML5?

that’s just wrong: is not a wrapper. The element denotes a semantic section of your content to help construct a document outline. It should contain a heading. If you’re looking for a page wrapper element (for any flavour of HTML or XHTML), consider applying styles directly to the element as described by Kroc Camen. If you still need an additional element for styling, use a . As Dr Mike explains, div isn’t dead, and if there’s nothing else more appropriate, it’s probably where you really want to apply your CSS.

you can check this : http://html5doctor.com/avoiding-common-html5-mistakes/

Jquery open popup on button click for bootstrap

Below mentioned link gives the clear explanation with example.

http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx

Code from the same link

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            modal: true,
            autoOpen: false,
            title: "jQuery Dialog",
            width: 300,
            height: 150
        });
        $("#btnShow").click(function () {
            $('#dialog').dialog('open');
        });
    });
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
    This is a jQuery Dialog.
</div>

refresh both the External data source and pivot tables together within a time schedule

Auto Refresh Workbook for example every 5 sec. Apply to module

Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll

alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"

End Sub

Apply to Workbook on Open

Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub

:)

install cx_oracle for python

If you are trying to install in MAC , just unzip the Oracle client which you downloaded and place it into the folder where you written python scripts. it will start working.

There is too much problem of setting up environmental variables. It worked for me.

Hope this helps.

Thanks

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

After a sequence of attempts I came into a facile solution. You can try Reinstalling ActiveX plugin for Adobe flashplayer.

How can I read the client's machine/computer name from the browser?

It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.

Like some one answered in one of the previous question today.

I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)

You cannot do it using asp.net as well.

How to read/write a boolean when implementing the Parcelable interface?

It is hard to identify the real question here. I guess it is how to deal with booleans when implementing the Parcelable interface.

Some attributes of MyObject are boolean but Parcel don't have any method read/writeBoolean.

You will have to either store the value as a string or as a byte. If you go for a string then you'll have to use the static method of the String class called valueOf() to parse the boolean value. It isn't as effective as saving it in a byte tough.

String.valueOf(theBoolean);

If you go for a byte you'll have to implement a conversion logic yourself.

byte convBool = -1;
if (theBoolean) {
    convBool = 1;
} else {
    convBool = 0;
}

When unmarshalling the Parcel object you have to take care of the conversion to the original type.

Css height in percent not working

You need to set 100% height on the parent element.

JavaScript equivalent of PHP's in_array()

There is now Array.prototype.includes:

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

Syntax

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

Always pass weak reference of self into block in ARC?

You don't have to always use a weak reference. If your block is not retained, but executed and then discarded, you can capture self strongly, as it will not create a retain cycle. In some cases, you even want the block to hold the self until the completion of the block so it does not deallocate prematurely. If, however, you capture the block strongly, and inside capture self, it will create a retain cycle.

How to add background image for input type="button"?

background-image takes an url as a value. Use either

background-image: url ('/image/btn.png');

or

background: url ('/image/btn.png') no-repeat;

which is a shorthand for

background-image: url ('/image/btn.png');
background-repeat: no-repeat;

Also, you might want to look at the button HTML element for fancy submit buttons.

How to combine paths in Java?

The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.

Replace non ASCII character from string

CharMatcher.retainFrom can be used, if you're using the Google Guava library:

String s = "A função";
String stripped = CharMatcher.ascii().retainFrom(s);
System.out.println(stripped); // Prints "A funo"

How to write Unicode characters to the console?

This works for me:

Console.OutputEncoding = System.Text.Encoding.Default;

To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:

  1. Open Command Prompt;

  2. Right click on the top bar of the Command Prompt;

  3. Click Properties;

  4. If the font is set to Raster Fonts, change it to Lucida Console.

Best way to convert string to bytes in Python 3?

The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode defaults to 'utf-8' ever since Python 3.0. Thus the best way is

b = mystring.encode()

This will also be faster, because the default argument results not in the string "utf-8" in the C code, but NULL, which is much faster to check!

Here be some timings:

In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop

In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop

Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.


Using encode() without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.

>>> 'äöä'.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Regular expression to match numbers with or without commas and decimals in text

Here's a regex:

(?:\d+)((\d{1,3})*([\,\ ]\d{3})*)(\.\d+)?

that accepts numbers:

  • without spaces and/or decimals, eg. 123456789, 123.123
  • with commas or spaces as thousands separator and/or decimals, eg. 123 456 789, 123 456 789.100, 123,456, 3,232,300,000.00

Tests: http://regexr.com/3h1a2

Web API Put Request generates an Http 405 Method Not Allowed error

I'm running an ASP.NET MVC 5 application on IIS 8.5. I tried all the variations posted here, and this is what my web.config looks like:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/> <!-- add this -->
    </modules>  
    <handlers>      
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="WebDAV" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers> 
</system.webServer>

I couldn't uninstall WebDav from my Server because I didn't have admin privileges. Also, sometimes I was getting the method not allowed on .css and .js files. In the end, with the configuration above set up everything started working again.

How to make a function wait until a callback has been called using node.js

If you don't want to use call back then you can Use "Q" module.

For example:

function getdb() {
    var deferred = Q.defer();
    MongoClient.connect(databaseUrl, function(err, db) {
        if (err) {
            console.log("Problem connecting database");
            deferred.reject(new Error(err));
        } else {
            var collection = db.collection("url");
            deferred.resolve(collection);
        }
    });
    return deferred.promise;
}


getdb().then(function(collection) {
   // This function will be called afte getdb() will be executed. 

}).fail(function(err){
    // If Error accrued. 

});

For more information refer this: https://github.com/kriskowal/q

How to manage startActivityForResult on Android?

If you want to update the user interface with activity result, you can't to use this.runOnUiThread(new Runnable() {} Doing this the UI won't refresh with new value. Instead, you can do this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_CANCELED) {
        return;
    }

    global_lat = data.getDoubleExtra("LATITUDE", 0);
    global_lng = data.getDoubleExtra("LONGITUDE", 0);
    new_latlng = true;
}

@Override
protected void onResume() {
    super.onResume();

    if(new_latlng)
    {
        PhysicalTagProperties.this.setLocation(global_lat, global_lng);
        new_latlng=false;
    }
}

This seems silly but works pretty well.

Load a bitmap image into Windows Forms using open file dialog

You have to create an instance of the Bitmap class, using the constructor overload that loads an image from a file on disk. As your code is written now, you're trying to use the PictureBox.Image property as if it were a method.

Change your code to look like this (also taking advantage of the using statement to ensure proper disposal, rather than manually calling the Dispose method):

private void button1_Click(object sender, EventArgs e)
{
    // Wrap the creation of the OpenFileDialog instance in a using statement,
    // rather than manually calling the Dispose method to ensure proper disposal
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            PictureBox PictureBox1 = new PictureBox();

            // Create a new Bitmap object from the picture file on disk,
            // and assign that to the PictureBox.Image property
            PictureBox1.Image = new Bitmap(dlg.FileName);
        }
    }
}

Of course, that's not going to display the image anywhere on your form because the picture box control that you've created hasn't been added to the form. You need to add the new picture box control that you've just created to the form's Controls collection using the Add method. Note the line added to the above code here:

private void button1_Click(object sender, EventArgs e)
{
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            PictureBox PictureBox1 = new PictureBox();
            PictureBox1.Image = new Bitmap(dlg.FileName);

            // Add the new control to its parent's controls collection
            this.Controls.Add(PictureBox1);
        }
    }
}

Print PDF directly from JavaScript

https://github.com/mozilla/pdf.js/

for a live demo http://mozilla.github.io/pdf.js/

it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

Why does modulus division (%) only work with integers?

The % operator gives you a REMAINDER(another name for modulus) of a number. For C/C++, this is only defined for integer operations. Python is a little broader and allows you to get the remainder of a floating point number for the remainder of how many times number can be divided into it:

>>> 4 % math.pi
0.85840734641020688
>>> 4 - math.pi
0.85840734641020688
>>>