Programs & Examples On #Zend db

Database access component for the Zend Framework.

How to print exact sql query in zend framework ?

I have traversed hundred of pages, googled a lot but i have not found any exact solution. Finally this worked for me. Irrespective where you are in either controller or model. This code worked for me every where. Just use this

//Before executing your query
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$db->getProfiler()->setEnabled(true);
$profiler = $db->getProfiler();

// Execute your any of database query here like select, update, insert
//The code below must be after query execution
$query  = $profiler->getLastQueryProfile();
$params = $query->getQueryParams();
$querystr  = $query->getQuery();

foreach ($params as $par) {
    $querystr = preg_replace('/\\?/', "'" . $par . "'", $querystr, 1);
}
echo $querystr;

Finally this thing worked for me.

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

CSS Background image not loading

I had changed the document root for my wamp-server-installed apache web server. so using the relative url i.e. (images/img.png) didn't work. I had to use the absolute url in order for it to work i.e.

background-image:url("http://localhost/project_x/images/img.png");

Integer expression expected error in shell script

./bilet.sh: line 6: [: 7]: integer expression expected

Be careful with " "

./bilet.sh: line 9: [: missing `]'

This is because you need to have space between brackets like:

if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]

look: added space, and no " "

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

How do I find the length of an array?

Simply you can use this snippet:

#include <iostream>
#include <string>
#include <array>

using namespace std;

int main()
{

  array<int,3> values;
  cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
  cout << "sizeof(myints): " << sizeof(values) << endl;

}

and here is the reference : http://www.cplusplus.com/reference/array/array/size/

In Swift how to call method with parameters on GCD main thread?

Swift 3+ & Swift 4 version:

DispatchQueue.main.async {
    print("Hello")
}

Swift 3 and Xcode 9.2:

dispatch_async_on_main_queue {
    print("Hello")
}

ArrayList vs List<> in C#

ArrayList are not type safe whereas List<T> are type safe. Simple :).

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

In later versions of CMake, one way to do it on each target is:

set_target_properties(MyTarget PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")

I don't know of a way to do it globally.

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This works for me:

git init
git config --global http.sslVerify false
git clone https://myurl/myrepo.git

What is the best open XML parser for C++?

Try TinyXML or IrrXML...Both are lightweight XML parsers ( I'd suggest you to use TinyXML, anyway ).

Change New Google Recaptcha (v2) Width

A bit late but I've got an easy workaround:

Just add this code to your "g-recaptcha" class:

width: desired_width;

border-radius: 4px;
border-right: 1px solid #d8d8d8;
overflow: hidden;

File URL "Not allowed to load local resource" in the Internet Browser

You just need to replace all image network paths to byte strings in HTML string. For this first you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

        // Decode the encoded string.
        StringWriter myWriter = new StringWriter();
        HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
        string DecodedHtmlString = myWriter.ToString();

        //find and replace each img src with byte string
         HtmlDocument document = new HtmlDocument();
         document.LoadHtml(DecodedHtmlString);
         document.DocumentNode.Descendants("img")
          .Where(e =>
        {
            string src = e.GetAttributeValue("src", null) ?? "";
            return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
        })
        .ToList()
                    .ForEach(x =>
                    {
                        string currentSrcValue = x.GetAttributeValue("src", null);                                
                        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
                        string filename = Path.GetFileName(currentSrcValue);
                        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
                        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        br.Close();
                        fs.Close();
                        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
                    });

        string result = document.DocumentNode.OuterHtml;
        //Encode HTML string
        string myEncodedString = HttpUtility.HtmlEncode(result);

        Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

How to add a vertical Separator?

This should do exactly what the author wanted:

<StackPanel Orientation="Horizontal">
    <Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />            
</StackPanel>

if you want a horizontal separator, change the Orientation of the StackPanel to Vertical.

What is the backslash character (\\)?

It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.

e.g.

System.out.println("printing \"this\" in quotes");

outputs

printing "this" in quotes

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Oh my God. not need to do anything special. only in your post section do as follows:

    $.post(yourURL,{ '': results})(function(e){ ...}

In server use this:

   public ActionResult MethodName(List<yourViewModel> model){...}

this link help you to done ...

How to align center the text in html table row?

The following worked for me to vertically align content (multi-line) in a list-table

.. list-table::
   :class: longtable
   :header-rows: 1
   :stub-columns: 1
   :align: left
   :widths: 20, 20, 20, 20, 20

   * - Classification
     - Restricted
     - Company |br| Confidential
     - Internal Use Only
     - Public
   * - Row1 col1
     - Row1 col2
     - Row1 col3 
     - Row1 col4
     - Row1 col5

Using theme overrides .css option I defined:

.stub {
       text-align: left;
       vertical-align: top;
}

In the theme that I use 'python-docs-theme', the cell entry is defined as 'stub' class. Use your browser development menu to inspect what your theme class is for cell content and update that accordingly.

How can I increment a date by one day in Java?

Something like this should do the trick:

String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

function declaration isn't a prototype

Try:

extern int testlib(void);

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

CMAKE_MAKE_PROGRAM not found

I have two suggestions:

  1. Do you have make in your %PATH% environment variable? On my system, I need to add %MINGW_DIR%\bin to %PATH%.

  2. Do you have make installed? Depending on your mingw installation, it can be a separate package.

  3. Last resort: Can you pass the full path to make on the commandline? cmake -D"CMAKE_MAKE_PROGRAM:PATH=C:/MinGW-32/bin/make.exe" ..\Source

Javascript Date - set just the date, ignoring time?

How about .toDateString()?

Alternatively, use .getDate(), .getMonth(), and .getYear()?

In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?

Check out all the fun Date methods here: MDN Docs


Edit: If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString());

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.

Syncing Android Studio project with Gradle files

EDIT

Starting with Android Studio 3.1, you should go to:

File -> Sync Project with Gradle Files


OLD

Clicking the button 'Sync Project With Gradle Files' should do the trick:

Tools -> Android -> Sync Project with Gradle Files

If that fails, try running 'Rebuild project':

Build -> Rebuild Project

undefined offset PHP error

Undefined offset means there's an empty array key for example:

$a = array('Felix','Jon','Java');

// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

You can solve the problem using a loop (while):

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row['groupname']));

    // Set the first position of the array to null or empty
    $groupname[0] = "";
}

Bootstrap 3 jquery event for active tab change

Thanks to @Gerben's post came to know there are two events show.bs.tab (before the tab is shown) and shown.bs.tab (after the tab is shown) as explained in the docs - Bootstrap Tab usage

An additional solution if we're only interested in a specific tab, and maybe add separate functions without having to add an if - else block in one function, is to use the a href selector (maybe along with additional selectors if required)

 $("a[href='#tab_target_id']").on('shown.bs.tab', function(e) {
      console.log('shown - after the tab has been shown');
 });

 // or even this one if we want the earlier event
 $("a[href='#tab_target_id']").on('show.bs.tab', function(e) {
      console.log('show - before the new tab has been shown');
 });

demo

Skip to next iteration in loop vba

The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.

What you want inside your for loop follows the pattern

If (your condition) Then
    'Do something
End If

In this case, your condition is Not(Return = 0 And Level = 0), so you would use

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If (Not(Return = 0 And Level = 0)) Then
        'Do something
    End If
Next i

PS: the condition is equivalent to (Return <> 0 Or Level <> 0)

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

Using different Web.config in development and production environment

This is one of the huge benefits of using the machine.config. At my last job, we had development, test and production environments. We could use the machine.config for things like connection strings (to the appropriate, dev/test/prod SQL machine).

This may not be a solution for you if you don't have access to the actual production machine (like, if you were using a hosting company on a shared host).

Is there any way to delete local commits in Mercurial?

Enable the "strip" extension and type the following:

hg strip #changeset# --keep

Where #changeset# is the hash for the changeset you want to remove. This will remove the said changeset including changesets that descend from it and will leave your working directory untouched. If you wish to also revert your committed code changes remove the --keep option.

For more information, check the Strip Extension.

If you get "unkown command 'strip'" you may need to enable it. To do so find the .hgrc or Mercurial.ini file and add the following to it:

[extensions]
strip =

Note that (as Juozas mentioned in his comment) having multiple heads is normal workflow in Mercurial. You should not use the strip command to battle that. Instead, you should merge your head with the incoming head, resolve any conflicts, test, and then push.

The strip command is useful when you really want to get rid of changesets that pollute the branch. In fact, if you're in this question's situation and you want to completely remove all "draft" change sets permanently, check out the top answer, which basically suggests doing:

hg strip 'roots(outgoing())'

How to check if the request is an AJAX request with PHP

From PHP 7 with null coalescing operator it will be shorter:

$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );

Rails: Default sort order for a rails model?

default_scope

This works for Rails 4+:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

For Rails 2.3, 3, you need this instead:

default_scope order('created_at DESC')

For Rails 2.x:

default_scope :order => 'created_at DESC'

Where created_at is the field you want the default sorting to be done on.

Note: ASC is the code to use for Ascending and DESC is for descending (desc, NOT dsc !).

scope

Once you're used to that you can also use scope:

class Book < ActiveRecord::Base
  scope :confirmed, :conditions => { :confirmed => true }
  scope :published, :conditions => { :published => true }
end

For Rails 2 you need named_scope.

:published scope gives you Book.published instead of Book.find(:published => true).

Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed.

With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.

You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:

scope :recent_books, lambda 
  { |since_when| where("created_at >= ?", since_when) }
  # Note the `where` is making use of AREL syntax added in Rails 3.

Finally you can disable default scope with:

Book.with_exclusive_scope { find(:all) } 

or even better:

Book.unscoped.all

which will disable any filter (conditions) or sort (order by).

Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+


So ... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!

In fact they are Class level methods as they operate on the 1 set of 'all' records.

Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }.

As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published where published is a named scope.

In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.

ZIP file content type for HTTP request

The standard MIME type for ZIP files is application/zip. The types for the files inside the ZIP does not matter for the MIME type.

As always, it ultimately depends on your server setup.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

C++ code file extension? .cc vs .cpp

.C and .cc seem to be standard for the (few) Unix-oriented C++ programs I've seen. I've always used .cpp myself, since I only really work on Windows and that's been the standard there since like forever.

I recommend .cpp personally, because... it stands for "C Plus Plus". It is of course vitally important that file extensions are acronyms, but should this rationale prove insufficiently compelling other important things are non-use of the shift key (which rules out .C and .c++) and avoidance of regular expression metacharacters where possible (which rules out .c++ -- unfortunately you can't really avoid the . of course.).

This doesn't rule out .cc, so even though it doesn't really stand for anything (or does it?) it is probably a good choice for Linux-oriented code.

Difference between signed / unsigned char

The same way -- e.g. if you have an 8-bit char, 7 bits can be used for magnitude and 1 for sign. So an unsigned char might range from 0 to 255, whilst a signed char might range from -128 to 127 (for example).

How to change column order in a table using sql query in sql server 2005?

You can change this using SQL query. Here is sql query to change the sequence of column.

ALTER TABLE table name 
CHANGE COLUMN `column1` `column1` INT(11) NOT NULL COMMENT '' AFTER `column2`;

pandas: best way to select all columns whose names start with X

Based on @EdChum's answer, you can try the following solution:

df[df.columns[pd.Series(df.columns).str.contains("foo")]]

This will be really helpful in case not all the columns you want to select start with foo. This method selects all the columns that contain the substring foo and it could be placed in at any point of a column's name.

In essence, I replaced .startswith() with .contains().

Count all values in a matrix greater than a value

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

Right click to select a row in a Datagridview and show a menu to delete it

private void dataGridView1_CellContextMenuStripNeeded(object sender, 
DataGridViewCellContextMenuStripNeededEventArgs e)
{            
    if (e.RowIndex != -1)
    {
        dataGridView1.ClearSelection();
        this.dataGridView1.Rows[e.RowIndex].Selected = true;
        e.ContextMenuStrip = contextMenuStrip1;
    }
}

Add Insecure Registry to Docker

The solution with the /etc/docker/daemon.json file didn't work for me on Ubuntu.

I was able to configure Docker insecure registries on Ubuntu by providing command line options to the Docker daemon in /etc/default/docker file, e.g.:

# /etc/default/docker    
DOCKER_OPTS="--insecure-registry=a.example.com --insecure-registry=b.example.com"

The same way can be used to configure custom directory for docker images and volumes storage, default DNS servers, etc..

Now, after the Docker daemon has restarted (after executing sudo service docker restart), running docker info will show:

Insecure Registries:
  a.example.com
  b.example.com
  127.0.0.0/8

self referential struct definition?

In C, you cannot reference the typedef that you're creating withing the structure itself. You have to use the structure name, as in the following test program:

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

typedef struct Cell {
  int cellSeq;
  struct Cell* next; /* 'tCell *next' will not work here */
} tCell;

int main(void) {
    int i;
    tCell *curr;
    tCell *first;
    tCell *last;

    /* Construct linked list, 100 down to 80. */

    first = malloc (sizeof (tCell));
    last = first;
    first->cellSeq = 100;
    first->next = NULL;
    for (i = 0; i < 20; i++) {
        curr = malloc (sizeof (tCell));
        curr->cellSeq = last->cellSeq - 1;
        curr->next = NULL;
        last->next = curr;
        last = curr;
    }

    /* Walk the list, printing sequence numbers. */

    curr = first;
    while (curr != NULL) {
        printf ("Sequence = %d\n", curr->cellSeq);
        curr = curr->next;
    }

    return 0;
}

Although it's probably a lot more complicated than this in the standard, you can think of it as the compiler knowing about struct Cell on the first line of the typedef but not knowing about tCell until the last line :-) That's how I remember that rule.

Sequence contains no matching element

Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.

_dsACL.Documents.FirstOrDefault(o => o.ID == id);

diff to output only the file names

If you want to get a list of files that are only in one directory and not their sub directories and only their file names:

diff -q /dir1 /dir2 | grep /dir1 | grep -E "^Only in*" | sed -n 's/[^:]*: //p'

If you want to recursively list all the files and directories that are different with their full paths:

diff -rq /dir1 /dir2 | grep -E "^Only in /dir1*" | sed -n 's/://p' | awk '{print $3"/"$4}'

This way you can apply different commands to all the files.

For example I could remove all the files and directories that are in dir1 but not dir2:

diff -rq /dir1 /dir2 | grep -E "^Only in /dir1*" | sed -n 's/://p' | awk '{print $3"/"$4}' xargs -I {} rm -r {}

How to change style of a default EditText

I solved the same issue 10 minutes ago, so I will give you a short effective fix: Place this inside the application tag or your manifest:

 android:theme="@android:style/Theme.Holo"

Also set the Theme of your XML layout to Holo, in the layout's graphical view.

Libraries will be useful if you need to change more complicated theme stuff, but this little fix will work, so you can move on with your app.

Bash: Syntax error: redirection unexpected

Docker:

I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note

To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]

Solution:

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]

Notice the quotes around each parameter.

Load vs. Stress testing

Load - Test S/W at max Load. Stress - Beyond the Load of S/W.Or To determine the breaking point of s/w.

Responsive css background images

background:url("img/content-bg.jpg") no-repeat;
background-position:center; 
background-size:cover;

or

background-size:100%;

How to extract svg as file from web page

Here's a three step solution:

  1. Copy the SVG code snippet, and paste it into a new HTML page.
  2. Save the HTML page as (for example) "logo.html", and then open that HTML page in Chrome hitting > File > Print > "Save as pdf"
  3. This PDF can now be opened in Illustrator - extracting the vector element.

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

How to get the size of a string in Python?

Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.

string = input("Enter the string : ")

print("The string length is : ",len(string))

OUTPUT : -

Enter the string : viral

The string length is : 5

Inserting string at position x of another string

Quick fix! If you don't want to manually add a space, you can do this:

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = "an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

(edit: i see that this is actually answered above, sorry!)

SQL Server 2008 - Case / If statements in SELECT Clause

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx

Loading/Downloading image from URL on Swift

Swift 4.2 and AlamofireImage

If using a library is not an issue, you can do it by help of the AlamofireImage. my samples are from its Github

Placeholder Images Example:

let imageView = UIImageView(frame: frame)
let url = URL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!
imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)

it has many handy functions and extension to work with images. from caching to scaling and resizing or even applying filters on the image. if images are important in your app, I suggest to use this framework and save your time.

Selecting multiple items in ListView

Step 1: setAdapter to your listview.

 listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); 

Step 2: set choice mode for listview .The second line of below code represents which checkbox should be checked.

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemChecked(2, true);

listView.setOnItemClickListener(this);



 private static  String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };

Step 3: Checked views are returned in SparseBooleanArray, so you might use the below code to get key or values.The below sample are simply displayed selected names in a single String.

@Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int arg2, long arg3)
    {

    SparseBooleanArray sp=getListView().getCheckedItemPositions();

    String str="";
    for(int i=0;i<sp.size();i++)
    {
        str+=GENRES[sp.keyAt(i)]+",";
    }
    Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();

    }

How to convert a string with Unicode encoding to a string of letters

Actually, I wrote an Open Source library that contains some utilities. One of them is converting a Unicode sequence to String and vise-versa. I found it very useful. Here is the quote from the article about this library about Unicode converter:

Class StringUnicodeEncoderDecoder has methods that can convert a String (in any language) into a sequence of Unicode characters and vise-versa. For example a String "Hello World" will be converted into

"\u0048\u0065\u006c\u006c\u006f\u0020 \u0057\u006f\u0072\u006c\u0064"

and may be restored back.

Here is the link to entire article that explains what Utilities the library has and how to get the library to use it. It is available as Maven artifact or as source from Github. It is very easy to use. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison

Apply function to all elements of collection through LINQ

For collections that do not support ForEach you can use static ForEach method in Parallel class:

var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };
Parallel.ForEach(_your_collection_, options, x => x._Your_Method_());

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

My problem was the wrong port number for mongoDB server.

I had:

DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"

in my .env file (my environmental variables), but I had written it before running mongoDB server. So when I ran the mongoDB server, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB):

DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"

and now it works fine.

How to add List<> to a List<> in asp.net

Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));

ASP.Net MVC 4 Form with 2 submit buttons/actions

You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:

<form id="myForm">
    <%-- form data inputs here ---%>
    <button id="edit">Edit</button>
    <button id="validate">Validate</button>
</form>

you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):

<script type="text/javascript">
      $("#edit").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Edit","MyController")");
          form.submit();
      });

      $("#validate").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Validate","MyController")");
          form.submit();
      });
</script>

How to remove leading and trailing zeros in a string? Python

Remove leading + trailing '0':

list = [i.strip('0') for i in listOfNum ]

Remove leading '0':

list = [ i.lstrip('0') for i in listOfNum ]

Remove trailing '0':

list = [ i.rstrip('0') for i in listOfNum ]

Excel Formula to SUMIF date falls in particular month

=Sumifs(B:B,A:A,">=1/1/2013",A:A,"<=1/31/2013")

The beauty of this formula is you can add more data to columns A and B and it will just recalculate.

How do I run all Python unit tests in a directory?

This is now possible directly from unittest: unittest.TestLoader.discover.

import unittest
loader = unittest.TestLoader()
start_dir = 'path/to/your/test/files'
suite = loader.discover(start_dir)

runner = unittest.TextTestRunner()
runner.run(suite)

Getting individual colors from a color map in matplotlib

You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap object you have.

import matplotlib

cmap = matplotlib.cm.get_cmap('Spectral')

rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)

For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under() and cmap.set_over().

For "special" numbers such as np.nan and np.inf the default is to use the 0.0 value, this can be changed using cmap.set_bad() similarly to under and over as above.

Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]. This can be done using matplotlib.colors.Normalize simply as shown in the small example below where the arguments vmin and vmax describe what numbers should be mapped to 0.0 and 1.0 respectively.

import matplotlib

norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)

print(norm(15.0)) # 0.5

A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.

(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)

How can one grab a stack trace in C?

You should be using the unwind library.

unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
unsigned long a[100];
int ctr = 0;

while (unw_step(&cursor) > 0) {
  unw_get_reg(&cursor, UNW_REG_IP, &ip);
  unw_get_reg(&cursor, UNW_REG_SP, &sp);
  if (ctr >= 10) break;
  a[ctr++] = ip;
}

Your approach also would work fine unless you make a call from a shared library.

You can use the addr2line command on Linux to get the source function / line number of the corresponding PC.

"PKIX path building failed" and "unable to find valid certification path to requested target"

I was facing the same issue and get it resolved using the below simple steps:

1) Download the InstallCert.java from google

2) Compile it using javac InstallCert.java

3) Run InstallCert.java using java InstallCert.java, with the hostname and https port, and press “1” when asking for input. It will add the “localhost” as a trusted keystore, and generate a file named “jssecacerts“ as below:

java InstallCert localhost:443

4) copy the jssecacerts into $JAVA_HOME/jre/lib/security folder

Main source to resolve the issue here is:

https://ankurjain26.blogspot.in/2017/11/javaxnetsslsslhandshakeexception.html

Visual Studio window which shows list of methods

Do you mean the class view window (View->Class View, or Ctrl+W,C)?

You also have the intellisence popup-window

Delete keychain items when an app is uninstalled

For those looking for a Swift version of @amro's answer:

    let userDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.boolForKey("hasRunBefore") == false {

        // remove keychain items here


        // update the flag indicator
        userDefaults.setBool(true, forKey: "hasRunBefore")
        userDefaults.synchronize() // forces the app to update the NSUserDefaults

        return
    }

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

there might be a problem at your web hosting company from where you are testing the secure communication for gateway, that they might not allow you to do that.

also there might be a username, password that must be provided before connecting to remote host.

or your IP might need to be in the list of approved IP for the remote server for communication to initiate.

iterating through json object javascript

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.

{
"dialog":
{
    "trunks":[
    {
        "trunk_id" : "1",
        "message": "This is just a JSON Test"
    },
    {
        "trunk_id" : "2",
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
    ]
}
}

At that point, I was able to do a fairly simple for loop based on the total number of objects.

var totalMessages = Object.keys(messages.dialog.trunks).length;

    for ( var i = 0; i < totalMessages; i++)
    {
        console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
    }

My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.

Form Google Maps URL that searches for a specific places near specific coordinates

What do you want to search near that known place?

For example if you want to search a restaurant near a known place you can use the parameters "q=" and "near=" and construct this URL: maps.google.com/?q=restaurant&near=47.154719,27.60551

For a list of complete parameters you can see this: https://web.archive.org/web/20070708030513/http://mapki.com/wiki/Google_Map_Parameters

Depending on what is the format you want your information in you can add at the end of the url the parameter output like this: maps.google.com/?q=restaurant&near=47.154719,27.60551&output=kml

For more types of output format you can read chapter 2 of this: http://csie-tw.blogspot.de/2009/06/android-driving-direction-route-path.html

Is it better to use NOT or <> when comparing values?

The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as

If NOT (value1 = value2)

which just makes the use of the NOT keyword pointless.

What is the difference between jQuery: text() and html() ?

Basically, $("#div").html uses element.innerHTML to set contents, and $("#div").text (probably) uses element.textContent.

http://docs.jquery.com/Attributes/html:

Set the html contents of every matched element

http://docs.jquery.com/Attributes/text:

Similar to html(), but escapes HTML (replace "<" and ">" with their HTML 
entities).

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

TextFX menu is missing in Notepad++

A lot of the old TextFX operations like removing empty lines and sorting are available under:

Menu Edit ? Line Operations

is it possible to update UIButton title/text programmatically?

Sometimes it can get really complicated. The easy way is to "refresh" the button view!

//Do stuff to your button here.  For example:

[mybutton setEnabled:YES];

//Refresh it to new state.

[mybutton setNeedsDisplay];

React Native absolute positioning horizontal centre

You can try the code

<View
    style={{
      alignItems: 'center',
      justifyContent: 'center'
    }}
  >
    <View
      style={{
        position: 'absolute',
        margin: 'auto',
        width: 50,
        height: 50
      }}
    />
  </View>

constant pointer vs pointer on a constant value

Trying to answer in simple way:

char * const a;  => a is (const) constant (*) pointer of type char {L <- R}. =>( Constant Pointer )
const char * a;  => a is (*) pointer to char constant             {L <- R}. =>( Pointer to Constant)

Constant Pointer:

pointer is constant !!. i.e, the address it is holding can't be changed. It will be stored in read only memory.

Let's try to change the address of pointer to understand more:

char * const a = &b; 
char c;
a = &c; // illegal , you can't change the address. `a` is const at L-value, so can't change. `a` is read-only variable.

It means once constant pointer points some thing it is forever.

pointer a points only b.

However you can change the value of b eg:

char b='a';
char * const a =&b;

printf("\n print a  : [%c]\n",*a);
*a = 'c';
printf("\n now print a  : [%c]\n",*a);

Pointer to Constant:

Value pointed by the pointer can't be changed.

const char *a;
char b = 'b';
const char * a =&b;
char c;
a=&c; //legal

*a = 'c'; // illegal , *a is pointer to constant can't change!.

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

Counting Number of Letters in a string variable

If you don't need the leading and trailing spaces :

str.Trim().Length

How to pass data from Javascript to PHP and vice versa?

Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.

An example (using traditional event registration model for simplicity):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->

Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)

See also Mozilla's documentation for further examples

With block equivalent in C#?

Sometimes you can get away with doing the following:

var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.Gray);
fill.PatternColor = Color.Black;
fill.Gradient = ...

(Code sample for EPPLus @ http://zeeshanumardotnet.blogspot.com)

How to display an alert box from C# in ASP.NET?

Response.Write("<script>alert('Data inserted successfully')</script>");

How do you programmatically update query params in react-router?

It can also be written this way

this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)

How to terminate the script in JavaScript?

If you don't care that it's an error just write:

fail;

That will stop your main (global) code from proceeding. Useful for some aspects of debugging/testing.

tar: add all files and directories in current directory INCLUDING .svn and so on

You can fix the . form by using --exclude:

tar -czf workspace.tar.gz --exclude=workspace.tar.gz .

How to filter for multiple criteria in Excel?

You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.

This will display PDF, DOC and DOCX filetypes.

Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues

Add URL link in CSS Background Image?

You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:

<a href="whatever.html"><li id="header"></li></a>

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

How to create a sleep/delay in nodejs that is Blocking?

blocking the main thread is not a good style for node because in most cases more then one person is using it. You should use settimeout/setinterval in combination with callbacks.

Git commit date

If you want to see only the date of a tag you'd do:

git show -s --format=%ci <mytagname>^{commit}

which gives: 2013-11-06 13:22:37 +0100

Or do:

git show -s --format=%ct <mytagname>^{commit}

which gives UNIX timestamp: 1383740557

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

This will get you the name of the day:

SELECT DATENAME(weekday, GETDATE())

How do I use Docker environment variable in ENTRYPOINT array?

You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ].
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)

In your case, I would use shell form

ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"

What is meant by the term "hook" in programming?

Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.

As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I have found the problem.

The problem was that the HTML I was trying to validate was not contained within a <form>...</form> tag.

As soon as I did that, I had a context that was not null.

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP ON Mac, I solve my problem by renaming

/Applications/MAMP/tmp/mysql/mysql.sock.lock

to

/Applications/MAMP/tmp/mysql/mysql.sock

How to size an Android view based on its parent's dimensions

I've been struggling this question for a long time, I want to change my DrawerLayout's drawer width, which is the second child of its parent. Recently I figured it out, but doesn't know if there's a better idea.

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
    super.onLayout(changed, l, t, r, b)
    (getChildAt(1).layoutParams as LayoutParams).width = measuredWidth/2
}

How to get unique device hardware id in Android?

Update: 19 -11-2019

The below answer is no more relevant to present day.

So for any one looking for answers you should look at the documentation linked below

https://developer.android.com/training/articles/user-data-ids


Old Answer - Not relevant now. You check this blog in the link below

http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

ANDROID_ID

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                    Secure.ANDROID_ID); 

The above is from the link @ Is there a unique Android device ID?

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

You get the imei number of the device using the below

  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  telephonyManager.getDeviceId();

http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

Add this is manifest

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

PHP ternary operator vs null coalescing operator

When using the superglobals like $_GET or $_REQUEST you should be aware that they could be an empty string. In this specal case this example

$username = $_GET['user'] ?? 'nobody';

will fail because the value of $username now is an empty string.

So when using $_GET or even $_REQUEST you should use the ternary operator instead like this:

$username = (!empty($_GET['user'])?$_GET['user']:'nobody';

Now the value of $username is 'nobody' as expected.

How can I show a hidden div when a select option is selected?

<select id="test" name="form_select" onchange="showDiv()">
   <option value="0">No</option>
   <option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
<script>
    function showDiv(){
        getSelectValue = document.getElementById("test").value;
        if(getSelectValue == "1"){
            document.getElementById("hidden_div").style.display="block";
        }else{
            document.getElementById("hidden_div").style.display="none";
        }
    }
</script>

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

c# Image resizing to different size while preserving aspect ratio

Note: this code resizes and removes everything outside the aspect ratio instead of padding it..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace MyPhotos.Common
{
    public class ThumbCreator
    {

        public enum VerticalAlign
        {
            Top,
            Middle,
            Bottom
        }

        public enum HorizontalAlign
        {
            Left,
            Middle,
            Right
        }

        public void Convert(string sourceFile, string targetFile, ImageFormat targetFormat, int height, int width, VerticalAlign valign, HorizontalAlign halign)
        {
            using (Image img = Image.FromFile(sourceFile))
            {
                using (Image targetImg = Convert(img, height, width, valign, halign))
                {
                    string directory = Path.GetDirectoryName(targetFile);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }
                    if (targetFormat == ImageFormat.Jpeg)
                    {
                        SaveJpeg(targetFile, targetImg, 100);
                    }
                    else
                    {
                        targetImg.Save(targetFile, targetFormat);
                    }
                }
            }
        }

        /// <summary> 
        /// Saves an image as a jpeg image, with the given quality 
        /// </summary> 
        /// <param name="path">Path to which the image would be saved.</param> 
        // <param name="quality">An integer from 0 to 100, with 100 being the 
        /// highest quality</param> 
        public static void SaveJpeg(string path, Image img, int quality)
        {
            if (quality < 0 || quality > 100)
                throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");


            // Encoder parameter for image quality 
            EncoderParameter qualityParam =
                new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            // Jpeg image codec 
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            img.Save(path, jpegCodec, encoderParams);
        }

        /// <summary> 
        /// Returns the image codec with the given mime type 
        /// </summary> 
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats 
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }

        public Image Convert(Image img, int height, int width, VerticalAlign valign, HorizontalAlign halign)
        {
            Bitmap result = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(result))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                float ratio = (float)height / (float)img.Height;
                int temp = (int)((float)img.Width * ratio);
                if (temp == width)
                {
                    //no corrections are needed!
                    g.DrawImage(img, 0, 0, width, height);
                    return result;
                }
                else if (temp > width)
                {
                    //den e för bred!
                    int overFlow = (temp - width);
                    if (halign == HorizontalAlign.Middle)
                    {
                        g.DrawImage(img, 0 - overFlow / 2, 0, temp, height);
                    }
                    else if (halign == HorizontalAlign.Left)
                    {
                        g.DrawImage(img, 0, 0, temp, height);
                    }
                    else if (halign == HorizontalAlign.Right)
                    {
                        g.DrawImage(img, -overFlow, 0, temp, height);
                    }
                }
                else
                {
                    //den e för hög!
                    ratio = (float)width / (float)img.Width;
                    temp = (int)((float)img.Height * ratio);
                    int overFlow = (temp - height);
                    if (valign == VerticalAlign.Top)
                    {
                        g.DrawImage(img, 0, 0, width, temp);
                    }
                    else if (valign == VerticalAlign.Middle)
                    {
                        g.DrawImage(img, 0, -overFlow / 2, width, temp);
                    }
                    else if (valign == VerticalAlign.Bottom)
                    {
                        g.DrawImage(img, 0, -overFlow, width, temp);
                    }
                }
            }
            return result;
        }
    }
}

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

Count number of occurrences by month

Use a pivot table. You can manually refresh a pivot table's data source by right-clicking on it and clicking refresh. Otherwise you can set up a worksheet_change macro - or just a refresh button. Pivot Table tutorial is here: http://chandoo.org/wp/2009/08/19/excel-pivot-tables-tutorial/

1) Create a Month column from your Date column (e.g. =TEXT(B2,"MMM") )

image1

2) Create a Year column from your Date column (e.g. =TEXT(B2,"YYYY") )

image2

3) Add a Count column, with "1" for each value

image3

4) Create a Pivot table with the fields, Count, Month and Year 5) Drag the Year and Month fields into Row Labels. Ensure that Year is above month so your Pivot table first groups by year, then by month 6) Drag the Count field into Values to create a Count of Count

image4

There are better tutorials I'm sure just google/bing "pivot table tutorial".

axios post request to send form data

You can post axios data by using FormData() like:

var bodyFormData = new FormData();

And then add the fields to the form you want to send:

bodyFormData.append('userName', 'Fred');

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile); 

And then you can use axios post method (You can amend it accordingly)

axios({
  method: "post",
  url: "myurl",
  data: bodyFormData,
  headers: { "Content-Type": "multipart/form-data" },
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

Related GitHub issue:

Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios

SQLiteDatabase.query method

if your SQL query is like this

SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5  ORDERBY col-2 DESC LIMIT 15;

Then for query() method, we can do as:-

String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";       
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";

query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Java code for getting current time

Like said above you can use

Date d = new Date();

or use

Calendar.getInstance();

or if you want it in millis

System.currentTimeMillis()

Video 100% width and height

If you're looking for the equivalent to background-size: cover for video.

video {
  object-fit: cover;
}

This will fill the container without distorting the video.


PS: I'm extending on Leo Yu's answer here.

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

Jquery resizing image

$(document).ready(function(){
    $('img').each(function(){
        var maxWidth = 660;
        var ratio = 0;
        var img = $(this);

        if(img.width() > maxWidth){
            ratio = img.height() / img.width();
            img.attr('width', maxWidth);
            img.attr('height', (maxWidth*ratio));   
        }
    });
});

that will do the magic trick for everyone using latest jquery. Be sure you set your selector right (I used $('img') but that can be different in your case). This only works for landscape mode. But if you look at it, only a few things have to be done to set it to portrait, aka, if img.height() > maxHeight) stuff

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

No plot window in matplotlib

The code snippet below works on both Eclipse and the Python shell:

import numpy as np
import matplotlib.pyplot as plt

# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)

# Just print x and y for fun
print x
print y

# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)

# Without the line below, the figure won't show
plt.show()

How can I lock a file using java (if possible)

Use this for unix if you are transferring using winscp or ftp:

public static void isFileReady(File entry) throws Exception {
        long realFileSize = entry.length();
        long currentFileSize = 0;
        do {
            try (FileInputStream fis = new FileInputStream(entry);) {
                currentFileSize = 0;
                while (fis.available() > 0) {
                    byte[] b = new byte[1024];
                    int nResult = fis.read(b);
                    currentFileSize += nResult;
                    if (nResult == -1)
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
        } while (currentFileSize != realFileSize);
    }

php error: Class 'Imagick' not found

On an EC2 at AWS, I did this:

 yum list | grep imagick

Then found a list of ones I could install...

 php -v

told me which version of php I had and thus which version of imagick

yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

Try-Catch-End Try in VBScript doesn't seem to work

Try Catch exists via workaround in VBScript:

http://web.archive.org/web/20140221063207/http://my.opera.com/Lee_Harvey/blog/2007/04/21/try-catch-finally-in-vbscript-sure

Class CFunc1
    Private Sub Class_Initialize
        WScript.Echo "Starting"
        Dim i : i = 65535 ^ 65535 
        MsgBox "Should not see this"
    End Sub

    Private Sub CatchErr
        If Err.Number = 0 Then Exit Sub
        Select Case Err.Number
            Case 6 WScript.Echo "Overflow handled!" 
            Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
        End Select
        Err.Clear
    End Sub

    Private Sub Class_Terminate
        CatchErr
        WScript.Echo "Exiting" 
    End Sub 
End Class

Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing

jQuery - multiple $(document).ready ...?

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

Are the days of passing const std::string & as a parameter over?

Are the days of passing const std::string & as a parameter over?

No. Many people take this advice (including Dave Abrahams) beyond the domain it applies to, and simplify it to apply to all std::string parameters -- Always passing std::string by value is not a "best practice" for any and all arbitrary parameters and applications because the optimizations these talks/articles focus on apply only to a restricted set of cases.

If you're returning a value, mutating the parameter, or taking the value, then passing by value could save expensive copying and offer syntactical convenience.

As ever, passing by const reference saves much copying when you don't need a copy.

Now to the specific example:

However inval is still quite a lot larger than the size of a reference (which is usually implemented as a pointer). This is because a std::string has various components including a pointer into the heap and a member char[] for short string optimization. So it seems to me that passing by reference is still a good idea. Can anyone explain why Herb might have said this?

If stack size is a concern (and assuming this is not inlined/optimized), return_val + inval > return_val -- IOW, peak stack usage can be reduced by passing by value here (note: oversimplification of ABIs). Meanwhile, passing by const reference can disable the optimizations. The primary reason here is not to avoid stack growth, but to ensure the optimization can be performed where it is applicable.

The days of passing by const reference aren't over -- the rules just more complicated than they once were. If performance is important, you'll be wise to consider how you pass these types, based on the details you use in your implementations.

Reactjs convert html string to jsx

i start using npm package called react-html-parser

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

How to create a function in a cshtml template?

why not just declare that function inside the cshtml file?

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}

<h2>index</h2>
@GetSomeString()

'negative' pattern matching in python

Use a negative match. (Also note that whitespace is significant, by default, inside a regex so don't space things out. Alternatively, use re.VERBOSE.)

for item in output:
    matchObj = re.search("^(OK|\\.)", item)
    if not matchObj:
        print "got item " + item

How to apply filters to *ngFor?

Basically, you write a pipe which you can then use in the *ngFor directive.

In your component:

filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];

In your template, you can pass string, number or object to your pipe to use to filter on:

<li *ngFor="let item of items | myfilter:filterargs">

In your pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myfilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: Object): any {
        if (!items || !filter) {
            return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(item => item.title.indexOf(filter.title) !== -1);
    }
}

Remember to register your pipe in app.module.ts; you no longer need to register the pipes in your @Component

import { MyFilterPipe } from './shared/pipes/my-filter.pipe';

@NgModule({
    imports: [
        ..
    ],
    declarations: [
        MyFilterPipe,
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results.

Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.

Please initialize the log4j system properly. While running web service

Those messages are something tricky, enough so that people created this to make it clearer: https://issues.apache.org/bugzilla/show_bug.cgi?id=25747

What's tricky about them is that the warnings are written if Log4j can't find its log4j.properties (or log4j.xml) file, but also if the file is fine and dandy but its content is not complete from a configuration point of view.

The following paragraph is taken from here: http://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_9/docs/TROUBLESHOOT.html

Logging output is written to a target by using an appender. If no appenders are attached to a category nor to any of its ancestors, you will get the following message when trying to log:

log4j: No appenders could be found for category (some.category.name).
log4j: Please initialize the log4j system properly.

Log4j does not have a default logging target. It is the user's responsibility to ensure that all categories can inherit an appender. This can be easily achieved by attaching an appender to the root category.

You can find info on how to configure the root logger (log4j.rootLogger) in the log4j documentation, basically adding something as simple as this at the beginning of the file:

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

This should clear those WARN messages you get on startup (make sure you don't already have an appender named stdout; also be carefull of what level you give the root logger, debug will be very verbose and every library in your app will start writing stuff to the console).

As about the log4j.properties/log4j.xml, I suggest you place this file in /WEB-INF/classes as it is important to have it exposed for different tweaks (activating/deactivating logs, changing log levels etc). You can have it inside a JAR in the classpath also (as you specified in your comment), but it will be enclosed in the archive (hopefully in the right place inside the archive) and won't be as easy to handle as if it were in /WEB-INF/classes.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

You can make the id the primary key, and set member_id to NOT NULL UNIQUE. (Which you've done.) Columns that are NOT NULL UNIQUE can be the target of foreign key references, just like a primary key can. (I'm pretty sure that's true of all SQL platforms.)

At the conceptual level, there's no difference between PRIMARY KEY and NOT NULL UNIQUE. At the physical level, this is a MySQL issue; other SQL platforms will let you use a sequence without making it the primary key.

But if performance is really important, you should think twice about widening your table by four bytes per row for that tiny visual convenience. In addition, if you switch to INNODB in order to enforce foreign key constraints, MySQL will use your primary key in a clustered index. Since you're not using your primary key, I imagine that could hurt performance.

Detecting TCP Client Disconnect

TCP has "open" and a "close" procedures in the protocol. Once "opened", a connection is held until "closed". But there are lots of things that can stop the data flow abnormally. That being said, the techniques to determine if it is possible to use a link are highly dependent on the layers of software between the protocol and the application program. The ones mentioned above focus on a programmer attempting to use a socket in a non-invasive way (read or write 0 bytes) are perhaps the most common. Some layers in libraries will supply the "polling" for a programmer. For example Win32 asych (delayed) calls can Start a read that will return with no errors and 0 bytes to signal a socket that cannot be read any more (presumably a TCP FIN procedure). Other environments might use "events" as defined in their wrapping layers. There is no single answer to this question. The mechanism to detect when a socket cannot be used and should be closed depends on the wrappers supplied in the libraries. It is also worthy to note that sockets themselves can be reused by layers below an application library so it is wise to figure out how your environment deals with the Berkley Sockets interface.

Find and replace with sed in directory and sub directories

grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orage|"

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:

const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] = 
{
  "dll_add",
  "dll_subtract",
  "dll_do_stuff",
  ...
};

Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
  {
    // error handling, most likely you have to terminate the program here
  }
}

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
{
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
  ...
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
{
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

Ajax call Into MVC Controller- Url Issue

starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like:

 $.ajax({
    type: "POST",
    url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

Environment variables in Eclipse

I was able to set the env. variables by sourcing (source command inside the shell (ksh) scirpt) the file that was settign them. Then I called the .ksh script from the external Tools

npm install gives error "can't find a package.json file"

In my case there was mistake in my package.json:

npm ERR! package.json must be actual JSON, not just JavaScript.

Turn on torch/flash on iPhone

See a better answer below: https://stackoverflow.com/a/10054088/308315


Old answer:

First, in your AppDelegate .h file:

#import <AVFoundation/AVFoundation.h>

@interface AppDelegate : NSObject <UIApplicationDelegate> {

    AVCaptureSession *torchSession;

}

@property (nonatomic, retain) AVCaptureSession * torchSession;

@end

Then in your AppDelegate .m file:

@implementation AppDelegate

@synthesize torchSession;

- (void)dealloc {
    [torchSession release];

    [super dealloc];
}

- (id) init {
    if ((self = [super init])) {

    // initialize flashlight
    // test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
        Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
        if (captureDeviceClass != nil) {

            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

            if ([device hasTorch] && [device hasFlash]){

                if (device.torchMode == AVCaptureTorchModeOff) {

                NSLog(@"Setting up flashlight for later use...");

                    AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
                    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

                    AVCaptureSession *session = [[AVCaptureSession alloc] init];

                [session beginConfiguration];
                    [device lockForConfiguration:nil];

                    [session addInput:flashInput];
                    [session addOutput:output];

                    [device unlockForConfiguration];

                    [output release];

                [session commitConfiguration];
                [session startRunning];

                [self setTorchSession:session];
                [session release];
                    }

            }

        }
    } 
    return self;
}

Then anytime you want to turn it on, just do something like this:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOn];
    [device setFlashMode:AVCaptureFlashModeOn];

    [device unlockForConfiguration];

}

And similar for turning it off:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOff];
    [device setFlashMode:AVCaptureFlashModeOff];

    [device unlockForConfiguration];
}

What's the difference between next() and nextLine() methods from Scanner class?

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}

Output:

enter string for c abc def
c is abc

enter string for d

d is def

If you use nextLine() instead of next() then

Output:

enter string for c

ABC DEF
c is ABC DEF
enter string for d

GHI
d is GHI

Creating and Update Laravel Eloquent

Here's a full example of what "lu cip" was talking about:

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();

Below is the updated link of the docs which is on the latest version of Laravel

Docs here: Updated link

How do I tell what type of value is in a Perl variable?

At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref or reftype is a bad idea. I don't recall who put the idea forward, or the link. Sorry.

The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie a filehandle so that it acts like a hash, the testing with reftype will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.

So, the argument went, it is better to use duck typing to find out what a variable is.

Instead of:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;
    if( $type eq 'HASH' ) {
        $result = $var->{foo};
    }
    elsif( $type eq 'ARRAY' ) {
        $result = $var->[3];
    }
    else {
        $result = 'foo';
    }

    return $result;
}

You should do something like this:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;

    eval {
        $result = $var->{foo};
        1; # guarantee a true result if code works.
    }
    or eval { 
        $result = $var->[3];
        1;
    }
    or do {
        $result = 'foo';
    }

    return $result;
}

For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.

Update

I realized I should put forward my thoughts on this approach.

This method has the advantage of handling anything you throw at it.

It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.

I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.

I don't like this implementation.

Java: Unresolved compilation problem

I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

using if else with eval in aspx page

If you absolutely do not want to use code-behind, you can try conditional operator for this:

<%# ((int)Eval("Percentage") < 50) ? "0 %" : Eval("Percentage") %>

That is assuming field Percentage contains integer.

Update: Version for VB.NET, just in case, provided by tomasofen:

<%# If(Eval("Status") < 50, "0 %", Eval("Percentage")) %>

How to change UINavigationBar background color from the AppDelegate

In Swift 4.2 and Xcode 10.1

You can change your navigation bar colour from your AppDelegate directly to your entire project.

In didFinishLaunchingWithOptions launchOptions: write below to lines of code

UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)

Here

tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)

barTintColor is for navigation bar background colour

If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()

//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white

enter image description here

How to edit nginx.conf to increase file size upload

Add client_max_body_size

Now that you are editing the file you need to add the line into the server block, like so;

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so;

http {
    client_max_body_size 8M;

    //other lines...
}

And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Saving in Vi

Once you are done you need to save, this can be done in vi with pressing esc key and typing :wq and returning.

Restarting Nginx and PHP

Now you need to restart nginx and php to reload the configs. This can be done using the following commands;

sudo service nginx restart
sudo service php5-fpm restart

Or whatever your php service is called.

Improve INSERT-per-second performance of SQLite

After reading this tutorial, I tried to implement it to my program.

I have 4-5 files that contain addresses. Each file has approx 30 million records. I am using the same configuration that you are suggesting but my number of INSERTs per second is way low (~10.000 records per sec).

Here is where your suggestion fails. You use a single transaction for all the records and a single insert with no errors/fails. Let's say that you are splitting each record into multiple inserts on different tables. What happens if the record is broken?

The ON CONFLICT command does not apply, cause if you have 10 elements in a record and you need each element inserted to a different table, if element 5 gets a CONSTRAINT error, then all previous 4 inserts need to go too.

So here is where the rollback comes. The only issue with the rollback is that you lose all your inserts and start from the top. How can you solve this?

My solution was to use multiple transactions. I begin and end a transaction every 10.000 records (Don't ask why that number, it was the fastest one I tested). I created an array sized 10.000 and insert the successful records there. When the error occurs, I do a rollback, begin a transaction, insert the records from my array, commit and then begin a new transaction after the broken record.

This solution helped me bypass the issues I have when dealing with files containing bad/duplicate records (I had almost 4% bad records).

The algorithm I created helped me reduce my process by 2 hours. Final loading process of file 1hr 30m which is still slow but not compared to the 4hrs that it initially took. I managed to speed the inserts from 10.000/s to ~14.000/s

If anyone has any other ideas on how to speed it up, I am open to suggestions.

UPDATE:

In Addition to my answer above, you should keep in mind that inserts per second depending on the hard drive you are using too. I tested it on 3 different PCs with different hard drives and got massive differences in times. PC1 (1hr 30m), PC2 (6hrs) PC3 (14hrs), so I started wondering why would that be.

After two weeks of research and checking multiple resources: Hard Drive, Ram, Cache, I found out that some settings on your hard drive can affect the I/O rate. By clicking properties on your desired output drive you can see two options in the general tab. Opt1: Compress this drive, Opt2: Allow files of this drive to have contents indexed.

By disabling these two options all 3 PCs now take approximately the same time to finish (1hr and 20 to 40min). If you encounter slow inserts check whether your hard drive is configured with these options. It will save you lots of time and headaches trying to find the solution

Flutter: Run method on Widget build complete

Best ways of doing this,

1. WidgetsBinding

WidgetsBinding.instance.addPostFrameCallback((_) {
      print("WidgetsBinding");
    });

2. SchedulerBinding

SchedulerBinding.instance.addPostFrameCallback((_) {
  print("SchedulerBinding");
});

It can be called inside initState, both will be called only once after Build widgets done with rendering.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("initState");
    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("WidgetsBinding");
    });
    SchedulerBinding.instance.addPostFrameCallback((_) {
      print("SchedulerBinding");
    });
  }

both above codes will work the same as both use the similar binding framework. For the difference find the below link.

https://medium.com/flutterworld/flutter-schedulerbinding-vs-widgetsbinding-149c71cb607f

Xcode Objective-C | iOS: delay function / NSTimer help?

Try

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

How can I execute a python script from an html button?

Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it's more powerful. Here is Step by guide to get complete your task :

pip install django
django-admin createproject buttonpython

then you have to create a file name views.py in buttonpython directory.

write below code in views.py:

from django.http import HttpResponse

def sample(request):
    #your python script code
    output=code output
    return HttpResponse(output)

Once done navigate to urls.py and add this stanza

from . import views

path('', include('blog.urls')),

Now go to parent directory and execute manage.py

python manage.py runserver 127.0.0.1:8001

Step by Step Guide in Detail: Run Python script on clicking HTML button

jQuery How to Get Element's Margin and Padding?

var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();

var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';

Check the jQuery API docs for information on each:

Here's the edited jsFiddle showing the result.

You can perform the same type of operations for the Height to get its margin, border, and padding.

How do I include a pipe | in my linux find -exec command?

I found that running a string shell command (sh -c) works best, for example:

find -name 'file_*' -follow -type f -exec bash -c "zcat \"{}\" | agrep -dEOE 'grep'" \;

How can I specify the required Node.js version in package.json?

I think you can use the "engines" field:

{ "engines" : { "node" : ">=0.12" } }

As you're saying your code definitely won't work with any lower versions, you probably want the "engineStrict" flag too:

{ "engineStrict" : true }

Documentation for the package.json file can be found on the npmjs site

Update

engineStrict is now deprecated, so this will only give a warning. It's now down to the user to run npm config set engine-strict true if they want this.

Update 2

As ben pointed out below, creating a .npmrc file at the root of your project (the same level as your package.json file) with the text engine-strict=true will force an error during installation if the Node version is not compatible.

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

Applying styles to tables with Twitter Bootstrap

You can also apply TR classes: info, error, warning, or success.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

How to multiply all integers inside list

Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial to utilize the two-parameter operator.mul with a fixed multiple

>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]

How does the getView() method work when creating your own custom adapter?

You can also find useful information about getView at the Adapter interface in Adapter.java file. It says;

/**
 * Get a View that displays the data at the specified position in the data set. You can either
 * create a View manually or inflate it from an XML layout file. When the View is inflated, the
 * parent View (GridView, ListView...) will apply default layout parameters unless you use
 * {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
 * to specify a root view and to prevent attachment to the root.
 * 
 * @param position The position of the item within the adapter's data set of the item whose view
 *        we want.
 * @param convertView The old view to reuse, if possible. Note: You should check that this view
 *        is non-null and of an appropriate type before using. If it is not possible to convert
 *        this view to display the correct data, this method can create a new view.
 *        Heterogeneous lists can specify their number of view types, so that this View is
 *        always of the right type (see {@link #getViewTypeCount()} and
 *        {@link #getItemViewType(int)}).
 * @param parent The parent that this view will eventually be attached to
 * @return A View corresponding to the data at the specified position.
 */
View getView(int position, View convertView, ViewGroup parent);

Styling the arrow on bootstrap tooltips

I have created fiddle for you.

Take a look at here

<p>
    <a class="tooltip" href="#">Tooltip
        <span>
            <img alt="CSS Tooltip callout"
                 src="http://www.menucool.com/tooltip/src/callout.gif" class="callout">
            <strong>Most Light-weight Tooltip</strong><br>
            This is the easy-to-use Tooltip driven purely by CSS.
        </span>
    </a>
</p>

 

a.tooltip {
    outline: none;
}

a.tooltip strong {
    line-height: 30px;
}

a.tooltip:hover {
    text-decoration: none;
}

a.tooltip span {
    z-index: 10;
    display: none;
    padding: 14px 20px;
    margin-top: -30px;
    margin-left: 28px;
    width: 240px;
    line-height: 16px;
}

a.tooltip:hover span {
    display: inline;
    position: absolute;
    color: #111;
    border: 1px solid #DCA;
    background: #fffAF0;
}

.callout {
    z-index: 20;
    position: absolute;
    top: 30px;
    border: 0;
    left: -12px;
}
/*CSS3 extras*/
a.tooltip span {
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-box-shadow: 5px 5px 8px #CCC;
    -webkit-box-shadow: 5px 5px 8px #CCC;
    box-shadow: 5px 5px 8px #CCC;
}

Plotting a fast Fourier transform in Python

There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:

Adding the required modules:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal

Generating sample data:

N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise

Sorting the data set:

order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]

Resampling:

T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)

Plotting the data and resampled data:

plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")
plt.legend()
plt.ylabel("X")
plt.xlabel("t")

Enter image description here

Now calculating the FFT:

Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]

plt.ylabel("Y")
plt.xlabel("f")
plt.plot(f, P1)

Enter image description here

P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.

Is there a Google Chrome-only CSS hack?

Only Chrome CSS hack:

@media all and (-webkit-min-device-pixel-ratio:0) and (min-resolution: .001dpcm) {
    #selector {
        background: red;
    }
}

Cannot find JavaScriptSerializer in .Net 4.0

You have to add the reference to the project.

In Assemblies, there is a System.Web.Extensions Add that.

Once that is done put:

    using System.Web;
    using System.Web.Script;
    using System.Web.Script.Serialization;

That worked for me.

Short IF - ELSE statement

The "ternary expression" x ? y : z can only be used for conditional assignment. That is, you could do something like:

String mood = inProfit() ? "happy" : "sad";

because the ternary expression is returning something (of type String in this example).

It's not really meant to be used as a short, in-line if-else. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).

So the proper way to do this would just be with an if-else block:

if (jXPanel6.isVisible()) {
    jXPanel6.setVisible(true);
}
else {
    jXPanel6.setVisible(false);
}

which of course can be shortened to

jXPanel6.setVisible(jXPanel6.isVisible());

Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).

Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.

Working with time DURATION, not time of day

The best way I found to resolve this issue was by using a combination of the above. All my cells were entered as a Custom Format to only show "HH:MM" - if I entered in "4:06" (being 4 minutes and 6 seconds) the field would show the numbers I entered correctly - but the data itself would represent HH:MM in the background.

Fortunately time is based on factors of 60 (60 seconds = 60 minutes). So 7H:15M / 60 = 7M:15S - I hope you can see where this is going. Accordingly, if I take my 4:06 and divide by 60 when working with the data (eg. to total up my total time or average time across 100 cells I would use the normal SUM or AVERAGE formulas and then divide by 60 in the formula.

Example =(SUM(A1:A5))/60. If my data was across the 5 time tracking fields was the 4:06, 3:15, 9:12, 2:54, 7:38 (representing MM:SS for us, but the data in the background is actually HH:MM) then when I work out the sum of those 5 fields are, what I want should be 27M:05S but what shows instead is 1D:03H:05M:00S. As mentioned above, 1D:3H:5M divided by 60 = 27M:5S ... which is the sum I am looking for.

Further examples of this are: =(SUM(G:G))/60 and =(AVERAGE(B2:B90)/60) and =MIN(C:C) (this is a direct check so no /60 needed here!).

Note that your "formula" or "calculation" fields (average, total time, etc) MUST have the custom format of MM:SS once you have divided by 60 as Excel's default thinking is in HH:MM (hence this issue). Your data fields where you are entering in your times should need to be changed from "General" or "Number" format to the custom format of HH:MM.

This process is still a little bit cumbersome to use - but it does mean that your data entry is still entered in very easy and is "correctly" displayed on screen as 4:06 (which most people would view as minutes:seconds when under a "Minutes" header). Generally there will only be a couple of fields needing to be used for formulas such as "best time", "average time", "total time" etc when tracking times and they will not usually be changed once the formula is entered so this will be a "one off" process - I use this for my call tracking sheet at work to track "average call", "total call time for day".

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

How to stop event propagation with inline onclick attribute?

This also works - In the link HTML use onclick with return like this :

<a href="mypage.html" onclick="return confirmClick();">Delete</a>

And then the comfirmClick() function should be like:

function confirmClick() {
    if(confirm("Do you really want to delete this task?")) {
        return true;
    } else {
        return false;
    }
};

adding child nodes in treeview

It looks like you are only adding children to the first parent treeView2.Nodes[0].Nodes.Add(yourChildNode)
Depending on how you want it to behave, you need to be explicit about the parent node you wish to add the child to.
For Example, from your screenshot, if you wanted to add the child to the second node you would need:
treeView2.Nodes[1].Nodes.Add(yourChildNode)
If you want to add the children to the currently selected node, get the TreeView.SelectedNode and add the children to it.

Try TreeView to get an idea of how the class operates. Unfortunately the msdn documentation is pretty light on the code samples...

I'm missing a whole lot of safety checks here!

Something like (untested):

private void addChildNode_Click(object sender, EventArgs e) {
  TreeNode ParentNode = treeView2.SelectedNode;  // for ease of debugging!
  if (ParentNode != null) {
    ParentNode.Nodes.Add("Name Of Node");
    treeView2.ExpandAll();   // so you can see what's been added              
    treeView2.Invalidate();  // requests a redraw
  }
}

What is the difference between angular-route and angular-ui-router?

1- ngRoute is developed by angular team whereas ui-router is a 3rd party module. 2- ngRoute implements routing based on the route URL whereas ui-router implements routing based on the state of the application. 3- ui-router provides everything that the ng-route provides plus some additional features like nested states and multiple named views.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I had similar issue and just wanted to post an answer for others in my situation.

I have a solution running a ASP.NET Web Application with multiple other C# class lib projects.

My ASP.NET Web Application wasn't using json, but other projects where.

This is how I fixed it:

  1. I made sure all projects where using latest version (6) using NuGet Update on all projects currently using any version of json - this didn't fix the issue
  2. I added json to the web application using NuGet - this fixed the issue (let me dive into why):

Step 2 was first of all adding a configuration information for json, that suggest that all projects, use the latest version (6) no matter what version they have. Adding the assembly binding to Web.Config is most likely the fix.

However, step 2 also cleaned up som legacy code. It turned out we have previously used an old version (5) of json in our Web Application and the NuGet folders wasn't deleted when the reference was (I suspect: manually) removed. Adding the latest json (6), removed the old folders (json v5). This might be part of the fix as well.

Converting list to *args when calling function

*args just means that the function takes a number of arguments, generally of the same type.

Check out this section in the Python tutorial for more info.

How do you run your own code alongside Tkinter's event loop?

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

How do I send a POST request as a JSON?

You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4

code:

    import urllib2,json

    url = 'http://www.google.com/someservice'
    postdata = {'key':'value'}

    req = urllib2.Request(url)
    req.add_header('Content-Type','application/json')
    data = json.dumps(postdata)

    response = urllib2.urlopen(req,data)

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

if your intention is send the full array from the html to the controller, can use this:

from the blade.php:

 <input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}"> 

in controller

    public function Get(Request $req) {

    $quotation = array('quotation' => json_decode($req->quotation));

    //or

    return view('quotation')->with('quotation',json_decode($req->quotation))


}

How to make a custom LinkedIn share button

LinkedIn revised their site recently, so there are a ton of old links just redirecting to the developer support homepage. Here is an updated link to the relevant page on LinkedIn's support site (as of Feb 16, 2015): https://developer.linkedin.com/docs/share-on-linkedin

How to read a file line-by-line into a list?

I would try one of the below mentioned methods. The example file that I use has the name dummy.txt. You can find the file here. I presume, that the file is in the same directory as the code (you can change fpath to include the proper file name and folder path.)

In both the below mentioned examples, the list that you want is given by lst.

1.> First method:

fpath = 'dummy.txt'
with open(fpath, "r") as f: lst = [line.rstrip('\n \t') for line in f]

print lst
>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']

2.> In the second method, one can use csv.reader module from Python Standard Library:

import csv
fpath = 'dummy.txt'
with open(fpath) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='   ')
    lst = [row[0] for row in csv_reader] 

print lst
>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']

You can use either of the two methods. Time taken for the creation of lst is almost equal in the two methods.

Create excel ranges using column numbers in vba?

I really like stackPusher's ConvertToLetter function as a solution. However, in working with it I noticed several errors occurring at very specific inputs due to some flaws in the math. For example, inputting 392 returns 'N\', 418 returns 'O\', 444 returns 'P\', etc.

I reworked the function and the result produces the correct output for all input up to 703 (which is the first triple-letter column index, AAA).

Function ConvertToLetter2(iCol As Integer) As String
    Dim First As Integer
    Dim Second As Integer
    Dim FirstChar As String
    Dim SecondChar As String

    First = Int(iCol / 26)
    If First = iCol / 26 Then
        First = First - 1
    End If
    If First = 0 Then
        FirstChar = ""
    Else
        FirstChar = Chr(First + 64)
    End If

    Second = iCol Mod 26
    If Second = 0 Then
        SecondChar = Chr(26 + 64)
    Else
        SecondChar = Chr(Second + 64)
    End If

    ConvertToLetter2 = FirstChar & SecondChar

End Function

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

package javax.servlet.http does not exist

If you are using Ant and trying to build then you need to :

  1. Specify tomcat location by <property name="tomcat-home" value="C:\xampp\tomcat" />

  2. Add tomcat libs to your already defined path for jars by

    <path id="libs"> <fileset includes="*.jar" dir="${WEB-INF}/lib" /> <fileset includes="*.jar" dir="${tomcat-home}/bin" /> <fileset includes="*.jar" dir="${tomcat-home}/lib" /> </path>

How to send email from MySQL 5.1

If you have vps or dedicated server, You can code your own module using C programming.

para.h

/* 
 * File:   para.h
 * Author: rahul
 *
 * Created on 10 February, 2016, 11:24 AM
 */

#ifndef PARA_H
#define  PARA_H

#ifdef  __cplusplus
extern "C" {
#endif


#define From "<[email protected]>"
#define To "<[email protected]>" 
#define From_header "Rahul<[email protected]>"   
#define TO_header "Mini<[email protected]>"   
#define UID "smtp server account ID"
#define PWD "smtp server account PWD"
#define domain "dfgdfgdfg.com"


#ifdef  __cplusplus
}
#endif

#endif  
/* PARA_H */

main.c

/* 
 * File:   main.c
 * Author: rahul
 *
 * Created on 10 February, 2016, 10:29 AM
 */
#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "time.h"
#include "para.h"

/*
 * 
 */

my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message);
void SendEmail_deinit(UDF_INIT *initid __attribute__((unused)));
char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error);

/*
 * base64
 */
int Base64encode_len(int len);
int Base64encode(char * coded_dst, const char *plain_src,int len_plain_src);

int Base64decode_len(const char * coded_src);
int Base64decode(char * plain_dst, const char *coded_src);

/* aaaack but it's fast and const should make it shared text page. */
static const unsigned char pr2six[256] =
{
    /* ASCII table */
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
    64,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
    64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};

int Base64decode_len(const char *bufcoded)
{
    int nbytesdecoded;
    register const unsigned char *bufin;
    register int nprbytes;

    bufin = (const unsigned char *) bufcoded;
    while (pr2six[*(bufin++)] <= 63);

    nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
    nbytesdecoded = ((nprbytes + 3) / 4) * 3;

    return nbytesdecoded + 1;
}

int Base64decode(char *bufplain, const char *bufcoded)
{
    int nbytesdecoded;
    register const unsigned char *bufin;
    register unsigned char *bufout;
    register int nprbytes;

    bufin = (const unsigned char *) bufcoded;
    while (pr2six[*(bufin++)] <= 63);
    nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
    nbytesdecoded = ((nprbytes + 3) / 4) * 3;

    bufout = (unsigned char *) bufplain;
    bufin = (const unsigned char *) bufcoded;

    while (nprbytes > 4) {
    *(bufout++) =
        (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
    *(bufout++) =
        (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
    *(bufout++) =
        (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
    bufin += 4;
    nprbytes -= 4;
    }

    /* Note: (nprbytes == 1) would be an error, so just ingore that case */
    if (nprbytes > 1) {
    *(bufout++) =
        (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
    }
    if (nprbytes > 2) {
    *(bufout++) =
        (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
    }
    if (nprbytes > 3) {
    *(bufout++) =
        (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
    }

    *(bufout++) = '\0';
    nbytesdecoded -= (4 - nprbytes) & 3;
    return nbytesdecoded;
}

static const char basis_64[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

int Base64encode_len(int len)
{
    return ((len + 2) / 3 * 4) + 1;
}

int Base64encode(char *encoded, const char *string, int len)
{
    int i;
    char *p;

    p = encoded;
    for (i = 0; i < len - 2; i += 3) {
    *p++ = basis_64[(string[i] >> 2) & 0x3F];
    *p++ = basis_64[((string[i] & 0x3) << 4) |
                    ((int) (string[i + 1] & 0xF0) >> 4)];
    *p++ = basis_64[((string[i + 1] & 0xF) << 2) |
                    ((int) (string[i + 2] & 0xC0) >> 6)];
    *p++ = basis_64[string[i + 2] & 0x3F];
    }
    if (i < len) {
    *p++ = basis_64[(string[i] >> 2) & 0x3F];
    if (i == (len - 1)) {
        *p++ = basis_64[((string[i] & 0x3) << 4)];
        *p++ = '=';
    }
    else {
        *p++ = basis_64[((string[i] & 0x3) << 4) |
                        ((int) (string[i + 1] & 0xF0) >> 4)];
        *p++ = basis_64[((string[i + 1] & 0xF) << 2)];
    }
    *p++ = '=';
    }

    *p++ = '\0';
    return p - encoded;
}

/*
 end of base64
 */

const char* GetIPAddress(const char* target_domain) {
    const char* target_ip;
    struct in_addr *host_address;
    struct hostent *raw_list = gethostbyname(target_domain);
    int i = 0;
    for (i; raw_list->h_addr_list[i] != 0; i++) {
        host_address = raw_list->h_addr_list[i];
        target_ip = inet_ntoa(*host_address);
    }
    return target_ip;
}

char * MailHeader(const char* from, const char* to, const char* subject, const char* mime_type, const char* charset) {

    time_t now;
    time(&now);
    char *app_brand = "Codevlog Test APP";
    char* mail_header = NULL;
    char date_buff[26];
    char Branding[6 + strlen(date_buff) + 2 + 10 + strlen(app_brand) + 1 + 1];
    char Sender[6 + strlen(from) + 1 + 1];
    char Recip[4 + strlen(to) + 1 + 1];
    char Subject[8 + 1 + strlen(subject) + 1 + 1];
    char mime_data[13 + 1 + 3 + 1 + 1 + 13 + 1 + strlen(mime_type) + 1 + 1 + 8 + strlen(charset) + 1 + 1 + 2];

    strftime(date_buff, (33), "%a , %d %b %Y %H:%M:%S", localtime(&now));

    sprintf(Branding, "DATE: %s\r\nX-Mailer: %s\r\n", date_buff, app_brand);
    sprintf(Sender, "FROM: %s\r\n", from);
    sprintf(Recip, "To: %s\r\n", to);
    sprintf(Subject, "Subject: %s\r\n", subject);
    sprintf(mime_data, "MIME-Version: 1.0\r\nContent-type: %s; charset=%s\r\n\r\n", mime_type, charset);

    int mail_header_length = strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject) + strlen(mime_data) + 10;

    mail_header = (char*) malloc(mail_header_length);

    memcpy(&mail_header[0], &Branding, strlen(Branding));
    memcpy(&mail_header[0 + strlen(Branding)], &Sender, strlen(Sender));
    memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender)], &Recip, strlen(Recip));
    memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip)], &Subject, strlen(Subject));
    memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject)], &mime_data, strlen(mime_data));
    return mail_header;
}

my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message){
     if (!(arg->arg_count == 2)) {
        strcpy(message, "Expected two arguments");
        return 1;
    }

    arg->arg_type[0] = STRING_RESULT;// smtp server address
    arg->arg_type[1] = STRING_RESULT;// email body
    initid->ptr = (char*) malloc(2050 * sizeof (char));
    memset(initid->ptr, '\0', sizeof (initid->ptr));
    return 0;
}

void SendEmail_deinit(UDF_INIT *initid __attribute__((unused))){
    if (initid->ptr) {
        free(initid->ptr);
    }
}

char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error){
   char *header = MailHeader(From_header, TO_header, "Hello Its a test Mail from Codevlog", "text/plain", "US-ASCII");
    int connected_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof (addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(25);
    if (inet_pton(AF_INET, GetIPAddress(arg->args[0]), &addr.sin_addr) == 1) {
        connect(connected_fd, (struct sockaddr*) &addr, sizeof (addr));
    }
    if (connected_fd != -1) {
        int recvd = 0;
        const char recv_buff[4768];
        int sdsd;
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char buff[1000];
        strcpy(buff, "EHLO "); //"EHLO sdfsdfsdf.com\r\n"
        strcat(buff, domain);
        strcat(buff, "\r\n");
        send(connected_fd, buff, strlen(buff), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd2[1000];
        strcpy(_cmd2, "AUTH LOGIN\r\n");
        int dfdf = send(connected_fd, _cmd2, strlen(_cmd2), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd3[1000];
        Base64encode(&_cmd3, UID, strlen(UID));
        strcat(_cmd3, "\r\n");
        send(connected_fd, _cmd3, strlen(_cmd3), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd4[1000];
        Base64encode(&_cmd4, PWD, strlen(PWD));
        strcat(_cmd4, "\r\n");
        send(connected_fd, _cmd4, strlen(_cmd4), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd5[1000];
        strcpy(_cmd5, "MAIL FROM: ");
        strcat(_cmd5, From);
        strcat(_cmd5, "\r\n");
        send(connected_fd, _cmd5, strlen(_cmd5), 0);
        char skip[1000];
        sdsd = recv(connected_fd, skip, sizeof (skip), 0);

        char _cmd6[1000];
        strcpy(_cmd6, "RCPT TO: ");
        strcat(_cmd6, To); //
        strcat(_cmd6, "\r\n");
        send(connected_fd, _cmd6, strlen(_cmd6), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd7[1000];
        strcpy(_cmd7, "DATA\r\n");
        send(connected_fd, _cmd7, strlen(_cmd7), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        send(connected_fd, header, strlen(header), 0);
        send(connected_fd, arg->args[1], strlen(arg->args[1]), 0);
        char _cmd9[1000];
        strcpy(_cmd9, "\r\n.\r\n.");
        send(connected_fd, _cmd9, sizeof (_cmd9), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd10[1000];
        strcpy(_cmd10, "QUIT\r\n");
        send(connected_fd, _cmd10, sizeof (_cmd10), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);

        memcpy(initid->ptr, recv_buff, strlen(recv_buff));
        *length = recvd;
    }
    free(header);
    close(connected_fd);
    return initid->ptr;
}

To configure your project go through this video: https://www.youtube.com/watch?v=Zm2pKTW5z98 (Send Email from MySQL on Linux) It will work for any mysql version (5.5, 5.6, 5.7)

I will resolve if any error appear in above code, Just Inform in comment

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

There is not official api support which means that it is not documented for the public and the libraries may change at any time. I realize you don't want to leave the application but here's how you do it with an intent for anyone else wondering.

public void sendData(int num){
    String fileString = "..."; //put the location of the file here
    Intent mmsIntent = new Intent(Intent.ACTION_SEND);
    mmsIntent.putExtra("sms_body", "text");
    mmsIntent.putExtra("address", num);
    mmsIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fileString)));
    mmsIntent.setType("image/jpeg");
    startActivity(Intent.createChooser(mmsIntent, "Send"));

}

I haven't completely figured out how to do things like track the delivery of the message but this should get it sent.

You can be alerted to the receipt of mms the same way as sms. The intent filter on the receiver should look like this.

<intent-filter>
    <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
    <data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>

importing pyspark in python shell

I got this error because the python script I was trying to submit was called pyspark.py (facepalm). The fix was to set my PYTHONPATH as recommended above, then rename the script to pyspark_test.py and clean up the pyspark.pyc that was created based on my scripts original name and that cleared this error up.

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> 
>>> #setup cursor
... cursor = db.cursor()
>>> 
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>> 
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
0L
>>> 
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
... 
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>> 
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
|  188 |   90 |
+------+------+
1 row in set (0.00 sec)

mysql> 

The simplest way to resize an UIImage?

Proper Swift 3.0 for iOS 10+ solution: Using ImageRenderer and closure syntax:

func imageWith(newSize: CGSize) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: newSize)
    let image = renderer.image { _ in
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
    }

    return image.withRenderingMode(self.renderingMode)
}

And here's the Objective-C version:

@implementation UIImage (ResizeCategory)
- (UIImage *)imageWithSize:(CGSize)newSize
{
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
    UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull myContext) {
        [self drawInRect:(CGRect) {.origin = CGPointZero, .size = newSize}];
    }];
    return [image imageWithRenderingMode:self.renderingMode];
}
@end

Set cookies for cross origin requests

For express, upgrade your express library to 4.17.1 which is the latest stable version. Then;

In CorsOption: Set origin to your localhost url or your frontend production url and credentials to true e.g

  const corsOptions = {
    origin: config.get("origin"),
    credentials: true,
  };

I set my origin dynamically using config npm module.

Then , in res.cookie:

For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly to true for http cookie to prevent XSS attack and other useful options depending on your use case.

For production environment, you need to set sameSite to none for cross-origin request and secure to true. Remember sameSite works with express latest version only as at now and latest chrome version only set cookie over https, thus the need for secure option.

Here is how I made mine dynamic

 res
    .cookie("access_token", token, {
      httpOnly: true,
      sameSite: app.get("env") === "development" ? true : "none",
      secure: app.get("env") === "development" ? false : true,
    })

Can you have multiline HTML5 placeholder text in a <textarea>?

Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.

(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());

Connecting to smtp.gmail.com via command line

Try this:

telnet smtp.gmail.com 587

How to set Java environment path in Ubuntu

open jdk once installed resides generally in your /usr/lib/java-6-openjdk As usual you would need to set the JAVA_HOME, calsspath and Path In ubuntu 11.04 there is a environment file available in /etc where you need to set all the three paths . And then you would need to restart your system for the changes to take effect..

Here is a site to help you around http://aliolci.blogspot.com/2011/05/ubuntu-1104-set-new-environment.html

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

php random x digit number

function random_number($size = 5)
{
    $random_number='';
    $count=0;
    while ($count < $size ) 
        {
            $random_digit = mt_rand(0, 9);
            $random_number .= $random_digit;
            $count++;
        }
    return $random_number;  
}

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

Get only specific attributes with from Laravel Collection

this seems to work, but not sure if it's optimized for performance or not.

$request->user()->get(['id'])->groupBy('id')->keys()->all();

output:

array:2 [
  0 => 4
  1 => 1
]

How do I parse a URL into hostname and path in javascript?

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"

In Java, how do I parse XML as a String instead of a file?

I have this function in my code base, this should work for you.

public static Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

also see this similar question

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

We have following script for create new table:

CREATE TABLE new_table
(
id                     NUMBER(32) PRIMARY KEY,
referenced_table_id    NUMBER(32)    NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
    FOREIGN KEY (referenced_table_id)
        REFERENCES referenced_table (id)
);

and we were getting this error on execute:

[42000][2270] ORA-02270: no matching unique or primary key for this column-list

The issue was due to disabled primary key of referenced table in our case. We have enabled it by

ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;

after that we created new table using first script without any issues

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

Checkbox for nullable boolean

My model has a boolean that has to be nullable

Why? This doesn't make sense. A checkbox has two states: checked/unchecked, or True/False if you will. There is no third state.

Or wait you are using your domain models in your views instead of view models? That's your problem. So the solution for me is to use a view model in which you will define a simple boolean property:

public class MyViewModel
{
    public bool Foo { get; set; }
}

and now you will have your controller action pass this view model to the view and generate the proper checkbox.

How to place object files in separate subdirectory

For anyone that is working with a directory style like this:

project
    > src
        > pkgA     
        > pkgB
        ...
    > bin
        > pkgA
        > pkgB
        ...

The following worked very well for me. I made this myself, using the GNU make manual as my main reference; this, in particular, was extremely helpful for my last rule, which ended up being the most important one for me.

My Makefile:

PROG := sim
CC := g++
ODIR := bin
SDIR := src
MAIN_OBJ := main.o
MAIN := main.cpp
PKG_DIRS := $(shell ls $(SDIR))
CXXFLAGS = -std=c++11 -Wall $(addprefix -I$(SDIR)/,$(PKG_DIRS)) -I$(BOOST_ROOT)
FIND_SRC_FILES = $(wildcard $(SDIR)/$(pkg)/*.cpp) 
SRC_FILES = $(foreach pkg,$(PKG_DIRS),$(FIND_SRC_FILES)) 
OBJ_FILES = $(patsubst $(SDIR)/%,$(ODIR)/%,\
$(patsubst %.cpp,%.o,$(filter-out $(SDIR)/main/$(MAIN),$(SRC_FILES))))

vpath %.h $(addprefix $(SDIR)/,$(PKG_DIRS))
vpath %.cpp $(addprefix $(SDIR)/,$(PKG_DIRS)) 
vpath $(MAIN) $(addprefix $(SDIR)/,main)

# main target
#$(PROG) : all
$(PROG) : $(MAIN) $(OBJ_FILES) 
    $(CC) $(CXXFLAGS) -o $(PROG) $(SDIR)/main/$(MAIN) 

# debugging
all : ; $(info $$PKG_DIRS is [${PKG_DIRS}])@echo Hello world

%.o : %.cpp
    $(CC) $(CXXFLAGS) -c $< -o $@

# This one right here, folks. This is the one.
$(OBJ_FILES) : $(ODIR)/%.o : $(SDIR)/%.h
    $(CC) $(CXXFLAGS) -c $< -o $@

# for whatever reason, clean is not being called...
# any ideas why???
.PHONY: clean

clean :
    @echo Build done! Cleaning object files...
    @rm -r $(ODIR)/*/*.o

By using $(SDIR)/%.h as a prerequisite for $(ODIR)/%.o, this forced make to look in source-package directories for source code instead of looking in the same folder as the object file.

I hope this helps some people. Let me know if you see anything wrong with what I've provided.

BTW: As you may see from my last comment, clean is not being called and I am not sure why. Any ideas?

Cannot open new Jupyter Notebook [Permission Denied]

None of the above worked for me but the below did:

sudo chown -R user: /Library/Frameworks/Python.framework/Versions/3.9/share/jupyter/

Where user is your username.