Programs & Examples On #Facebook ads api

The Facebook Ads API (aka Marketing API) is used by application developers to create, manage and measure ad campaigns that run on Facebook.

How to save image in database using C#

You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:

http://www.eggheadcafe.com/articles/20020929.asp

How can I convert uppercase letters to lowercase in Notepad++

Just select the text you want to change, right click and select UPPERCASE or lowercase depending on what you want.

Connection string using Windows Authentication

For the correct solution after many hours:

  1. Open the configuration file
  2. Change the connection string with the following

<add name="umbracoDbDSN" connectionString="data source=YOUR_SERVER_NAME;database=nrc;Integrated Security=SSPI;persist security info=True;" providerName="System.Data.SqlClient" />

  1. Change the YOUR_SERVER_NAME with your current server name and save
  2. Open the IIS Manager
  3. Find the name of the application pool that the website or web application is using
  4. Right-click and choose Advanced settings
  5. From Advanced settings under Process Model change the Identity to Custom account and add your Server Admin details, please see the attached images:

enter image description here

Hope this will help.

Git - push current branch shortcut

With the help of ceztko's answer I wrote this little helper function to make my life easier:

function gpu()
{
    if git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
        git push origin HEAD
    else
        git push -u origin HEAD
    fi
}

It pushes the current branch to origin and also sets the remote tracking branch if it hasn't been setup yet.

Confirm Password with jQuery Validate

Remove the required: true rule.

Demo: Fiddle

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

How can I load the contents of a text file into a batch file variable?

If your set command supports the /p switch, then you can pipe input that way.

set /p VAR1=<test.txt
set /? |find "/P"

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

This has the added benefit of working for un-registered file types (which the accepted answer does not).

How does one output bold text in Bash?

The most compatible way of doing this is using tput to discover the right sequences to send to the terminal:

bold=$(tput bold)
normal=$(tput sgr0)

then you can use the variables $bold and $normal to format things:

echo "this is ${bold}bold${normal} but this isn't"

gives

this is bold but this isn't

How can I disable the UITableView selection?

Scenario - 1

If you don't want selection for some specific cells on the tableview, you can set selection style in cellForRow function for those cells.

Objective-C

cell.selectionStyle = UITableViewCellSelectionStyleNone;

Swift 4.2

cell.selectionStyle = .none

Scenario - 2

For disabling selection on the whole table view :

Objective-C

self.tableView.allowsSelection = false;

Swift 4.2

self.tableView.allowsSelection = false

A valid provisioning profile for this executable was not found... (again)

After spending the day I realized it was a simple change in Project Settings

File -> Project Settings... -> Build System -> Legacy Build System.

In a project setting, you will see Build System named drop down and in that drop down select Legacy Build System

Adding text to ImageView in Android

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_weight="30" >

        <ImageButton
            android:id="@+id/imgbtnUploadPendingPods"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/hello_world"
            android:src="@drawable/upload_icon" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingTop="30dp"
            android:text="@string/pendingpods"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </FrameLayout>

What is the easiest way to install BLAS and LAPACK for scipy?

I got this problem on freeBSD. It seems lapack packages are missing, I solved it installing them (as root) with:

pkg install lapack
pkg install atlas-devel  #not sure this is needed, but just in case

I imagine it could work on other system too using the appropriate package installer (e.g. apt-get)

In Python how should I test if a variable is None, True or False

I believe that throwing an exception is a better idea for your situation. An alternative will be the simulation method to return a tuple. The first item will be the status and the second one the result:

result = simulate(open("myfile"))
if not result[0]:
  print "error parsing stream"
else:
  ret= result[1]

jQuery get input value after keypress

Just use a timeout to make your call; the timeout will be called when the event stack is finished (i.e. after the default event is called)

$("body").on('keydown', 'input[type=tel]', function (e) {
    setTimeout(() => {
        formatPhone(e)
    }, 0)
});

How to get relative path from absolute path

If you are using .NET Core 2.0, Path.GetRelativePath() is available providing this specific functionality:

        var relativeTo = @"C:\Program Files\Dummy Folder\MyProgram";
        var path = @"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat";

        string relativePath = System.IO.Path.GetRelativePath(relativeTo, path);

        System.Console.WriteLine(relativePath);
        // output --> Data\datafile1.dat 

Otherwise, for .NET full framework (as of v4.7) recommend using one of the other suggested answers.

How to Lazy Load div background images

I do it like this:

<div class="lazyload" style="width: 1000px; height: 600px" data-src="%s">
    <img class="spinner" src="spinner.gif"/>
</div>

and load with

$(window).load(function(){

    $('.lazyload').each(function() {

        var lazy = $(this);
        var src = lazy.attr('data-src');

        $('<img>').attr('src', src).load(function(){
            lazy.find('img.spinner').remove();
            lazy.css('background-image', 'url("'+src+'")');
        });

    });

});

How do I cancel a build that is in progress in Visual Studio?

Go to the Window menu and choose "Web Publish Activity" There will be a cancel button. Cancel button on "Web Publish Activity" tab

How to check if Location Services are enabled?

Can do in simplest way

private boolean isLocationEnabled(Context context){
int mode =Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                        Settings.Secure.LOCATION_MODE_OFF);
                final boolean enabled = (mode != android.provider.Settings.Secure.LOCATION_MODE_OFF);
return enabled;
}

Different CURRENT_TIMESTAMP and SYSDATE in oracle

  • SYSDATE provides date and time of a server.
  • CURRENT_DATE provides date and time of client.(i.e., your system)
  • CURRENT_TIMESTAMP provides data and timestamp of a clinet.

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

Different between parseInt() and valueOf() in java?

  • valueOf - converts to Wrapper class
  • parseInt - converts to primitive type

Integer.parseInt accept only String and return primitive integer type (int).

   public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

Iteger.valueOf accept int and String. If value is String, valueOf convert it to the the simple int using parseInt and return new Integer if input is less than -128 or greater than 127. If input is in range (-128 - 127) it always return the Integer objects from an internal IntegerCache. Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 (for example) we always get the same object.

Iteger.valueOf(200) will give new Integer from 200. It's like new Integer(200) Iteger.valueOf(127) is the same as Integer = 127;

If you wont to convert String to the Integer use Iteger.valueOf.

If you wont to convert String to the simple int use Integer.parseInt. It works faster.

  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

  public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
  }

  private static class IntegerCache {
      static final int low = -128;
      static final int high;
      static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
  }

And comparing Integer.valueOf(127) == Integer.valueOf(127) return true

Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
a == b; // return true 

Because it takes the Integer objects with the same references from the cache.

But Integer.valueOf(128) == Integer.valueOf(128) is false, because 128 is out of IntegerCache range and it return new Integer, so objects will have different references.

C/C++ Struct vs Class

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)

While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.

Overflow:hidden dots at the end

You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.

Here's a demo on jsbin.

_x000D_
_x000D_
.cut-text { 
  text-overflow: ellipsis;
  overflow: hidden; 
  width: 160px; 
  height: 1.2em; 
  white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
_x000D_
_x000D_

MySQL Insert query doesn't work with WHERE clause

A way to use INSERT and WHERE is

INSERT INTO MYTABLE SELECT 953,'Hello',43 WHERE 0 in (SELECT count(*) FROM MYTABLE WHERE myID=953); In this case ist like an exist-test. There is no exception if you run it two or more times...

How to push a single file in a subdirectory to Github (not master)

Let me start by saying that the way git works is you are not pushing/fetching files; well, at least not directly.

You are pushing/fetching refs, that point to commits. Then a commit in git is a reference to a tree of objects (where files are represented as objects, among other objects).

So, when you are pushing a commit, what git does it pushes a set of references like in this picture:

git commits

If you didn't push your master branch yet, the whole history of the branch will get pushed.

So, in your example, when you commit and push your file, the whole master branch will be pushed, if it was not pushed before.

To do what you asked for, you need to create a clean branch with no history, like in this answer.

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

  • you can also indent a whole section by selecting it and clicking TAB
  • and also indent backward using Shift+TAB

And of course for auto indentation and formatting, following the language you're using, you can see which good extensions do the good job, and which formatters to install or which parameters settings to enable or set for each language and its available tools. Just make sure to read well the documentation of the extension, to install and set all what it need.

Up to now the indentation problem bothers me with Python when copy pasting a block of code. If that's the case, here is how you solve that: Visual Studio Code indentation for Python

How to subtract 30 days from the current datetime in mysql?

You can also use

select CURDATE()-INTERVAL 30 DAY

Select rows with same id but different value in another column

$sql="SELECT * FROM TABLE_NAME WHERE item_id=".$item_id;

$query=mysql_query($sql);

while($myrow=mysql_fetch_array($query)) {

echo   print_r($myrow,1);


}

How to manually update datatables table with new JSON data

Here is solution for legacy datatable 1.9.4

    var myData = [
      {
        "id": 1,
        "first_name": "Andy",
        "last_name": "Anderson"
      }
   ];
    var myData2 = [
      {
        "id": 2,
        "first_name": "Bob",
        "last_name": "Benson"
      }
    ];

  $('#table').dataTable({
  //  data: myData,
       aoColumns: [
         { mData: 'id' },
         { mData: 'first_name' },
         { mData: 'last_name' }
      ]
  });

 $('#table').dataTable().fnClearTable();
 $('#table').dataTable().fnAddData(myData2);

How to find specific lines in a table using Selenium?

Well previously, I used the approach that you can find inside the WebElement:

WebElement baseTable = driver.findElement(By.tagName("table"));
WebElement tableRow = baseTable.findElement(By.xpath("//tr[2]")); //should be the third row
webElement cellIneed = tableRow.findElement(By.xpath("//td[2]"));
String valueIneed = cellIneed.getText();

Please note that I find inside the found WebElement instance.

The above is Java code, assuming that driver variable is healthy instance of WebDriver

Setting an image for a UIButton in code

Don't worry so much framing the button from code, you can do that on the storyboard. This worked for me, one line...more simple.

[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal];

Where in an Eclipse workspace is the list of projects stored?

If you are using Perforce (imported the project as a Perforce project), then .cproject and .project will be located under the root of the PERFORCE project, not on the workspace folder.

Hope this helps :)

How can I remove the top and right axis in matplotlib?

If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround:

Make the axis invisible (e.g. with plt.gca().axison = False) and then draw them manually with plt.arrow.

Get all photos from Instagram which have a specific hashtag with PHP

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}

unable to install pg gem

Use with ARCH flag.

sudo env ARCHFLAGS="-arch x86_64" gem install pg

This resolved the same issue you are having.

Angular 5 - Copy to clipboard

Solution 1: Copy any text

HTML

<button (click)="copyMessage('This goes to Clipboard')" value="click to copy" >Copy this</button>

.ts file

copyMessage(val: string){
    const selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = val;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);
  }

Solution 2: Copy from a TextBox

HTML

 <input type="text" value="User input Text to copy" #userinput>
      <button (click)="copyInputMessage(userinput)" value="click to copy" >Copy from Textbox</button>

.ts file

    /* To copy Text from Textbox */
  copyInputMessage(inputElement){
    inputElement.select();
    document.execCommand('copy');
    inputElement.setSelectionRange(0, 0);
  }

Demo Here


Solution 3: Import a 3rd party directive ngx-clipboard

<button class="btn btn-default" type="button" ngxClipboard [cbContent]="Text to be copied">copy</button>

Solution 4: Custom Directive

If you prefer using a custom directive, Check Dan Dohotaru's answer which is an elegant solution implemented using ClipboardEvent.


Solution 5: Angular Material

Angular material 9 + users can utilize the built-in clipboard feature to copy text. There are a few more customization available such as limiting the number of attempts to copy data.

How to return a string from a C++ function?

Assign something to your strings. This will definitely help.

Rename all files in a folder with a prefix in a single command

I recently faced this same situation and found an easier inbuilt solution. I am sharing it here so that it might help other people looking for solution.

With OS X Yosemite, Apple has integrated the batch renaming capabilities directly into Finder. Details information is available here. I have copied the steps below as well,

Rename multiple items

  1. Select the items, then Control-click one of them.

  2. In the shortcut menu, select Rename Items.

  3. In the pop-up menu below Rename Folder Items, choose to replace text in the names, add text to the names, or change the name format.

    • Replace text: Enter the text you want to remove in the Find field, then enter the text you want to add in the “Replace with” field.

    • Add text: Enter the text to you want to add in the field, then choose to add the text before or after the current name.

    • Format: Choose a name format for the files, then choose to put the index, counter, or date before or after the name. Enter a name in the Custom Format field, then enter the number you want to start with.

  4. Click Rename.

If you have a common pattern in your files than you can use Replace text otherwise Add text would also do the job.

Bootstrap 3: Keep selected tab on page refresh

I tried this and it works: ( Please replace this with the pill or tab you are using )

    jQuery(document).ready(function() {
        jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
            localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
        });

        // Here, save the index to which the tab corresponds. You can see it 
        // in the chrome dev tool.
        var activeTab = localStorage.getItem('activeTab');

        // In the console you will be shown the tab where you made the last 
        // click and the save to "activeTab". I leave the console for you to 
        // see. And when you refresh the browser, the last one where you 
        // clicked will be active.
        console.log(activeTab);

        if (activeTab) {
           jQuery('a[href="' + activeTab + '"]').tab('show');
        }
    });

I hope it would help somebody.

Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/

Can jQuery read/write cookies to a browser?

You'll need the cookie plugin, which provides several additional signatures to the cookie function.

$.cookie('cookie_name', 'cookie_value') stores a transient cookie (only exists within this session's scope, while $.cookie('cookie_name', 'cookie_value', 'cookie_expiration") creates a cookie that will last across sessions - see http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ for more information on the JQuery cookie plugin.

If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:

document.cookie = "name=value; expires=date; domain=domain; path=path; secure"

Why can't I inherit static classes?

The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).

So this:

static class Foo { }

compiles to this IL:

.class private abstract auto ansi sealed beforefieldinit Foo
  extends [mscorlib]System.Object
 {
 }

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

Vuex - Computed property "name" was assigned to but it has no setter

For me it was changing.

this.name = response.data;

To what computed returns so;

this.$store.state.name = response.data;

Can I set an opacity only to the background image of a div?

This can be done by using the different div class for the text Hi There...

<div class="myDiv">
    <div class="bg">
   <p> Hi there</p>
</div>
</div>

Now you can apply the styles to the

tag. otherwise for bg class. I am sure it works fine

"Logging out" of phpMyAdmin?

The second button from the left. The one on the right of the house in the image you posted is your logout button.

For your error message try this link in the documentation: http://wiki.phpmyadmin.net/pma/Configuration_storage

Make certain you have a phpadmin control user account created. This is covered in the second paragraph in on the documentation page in the link.

Reading the selected value from asp:RadioButtonList using jQuery

Why so complex?

$('#id:checked').val();

Will work just fine!

How to run multiple DOS commands in parallel?

You can execute commands in parallel with start like this:

start "" ping myserver
start "" nslookup myserver
start "" morecommands

They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.

Hope this helps!

Make $JAVA_HOME easily changable in Ubuntu

Traditionally, if you only want to change the variable in your terminal windows, set it in .bashrc file, which is sourced each time a new terminal is opened. .profile file is not sourced each time you open a new terminal.

See the difference between .profile and .bashrc in question: What's the difference between .bashrc, .bash_profile, and .environment?

.bashrc should solve your problem. However, it is not the proper solution since you are using Ubuntu. See the relevant Ubuntu help page "Session-wide environment variables". Thus, no wonder that .profile does not work for you. I use Ubuntu 12.04 and xfce. I set up my .profile and it is simply not taking effect even if I log out and in. Similar experience here. So you may have to use .pam_environment file and totally forget about .profile, and .bashrc. And NOTE that .pam_environment is not a script file.

Rethrowing exceptions in Java without losing the stack trace

In Java, you just throw the exception you caught, so throw e rather than just throw. Java maintains the stack trace.

Property 'value' does not exist on type 'Readonly<{}>'

event.target is of type EventTarget which doesn't always have a value. If it's a DOM element you need to cast it to the correct type:

handleChange(event) {
    this.setState({value: (event.target as HTMLInputElement).value});
}

This will infer the "correct" type for the state variable as well though being explicit is probably better

Understanding events and event handlers in C#

To understand event handlers, you need to understand delegates. In C#, you can think of a delegate as a pointer (or a reference) to a method. This is useful because the pointer can be passed around as a value.

The central concept of a delegate is its signature, or shape. That is (1) the return type and (2) the input arguments. For example, if we create a delegate void MyDelegate(object sender, EventArgs e), it can only point to methods which return void, and take an object and EventArgs. Kind of like a square hole and a square peg. So we say these methods have the same signature, or shape, as the delegate.

So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called.

So the default EventHandler (and many like it) represents a specific shape of method (again, void/object-EventArgs). When you declare an event, you are saying which shape of method (EventHandler) that event will invoke, by specifying a delegate:

//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyEventHandler(string foo);

//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyEventHandler SomethingHappened;

//Here is some code I want to be executed
//when SomethingHappened fires.
void HandleSomethingHappened(string foo)
{
    //Do some stuff
}

//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);

//To raise the event within a method.
SomethingHappened("bar");

(*This is the key to events in .NET and peels away the "magic" - an event is really, under the covers, just a list of methods of the same "shape". The list is stored where the event lives. When the event is "raised", it's really just "go through this list of methods and call each one, using these values as the parameters". Assigning an event handler is just a prettier, easier way of adding your method to this list of methods to be called).

php convert datetime to UTC

Do this way:

gmdate('Y-m-d H:i:s', $timestamp)

or simply

gmdate('Y-m-d H:i:s')

to get "NOW" in UTC.

Check the reference:

http://www.php.net/manual/en/function.gmdate.php

Convert generic List/Enumerable to DataTable?

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.ComponentModel;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt = lstEmployee.ConvertToDataTable();
    }
    public static DataTable ConvertToDataTable<T>(IList<T> list) where T : class
    {
        try
        {
            DataTable table = CreateDataTable<T>();
            Type objType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor property in properties)
                {
                    if (!CanUseType(property.PropertyType)) continue;
                    row[property.Name] = property.GetValue(item) ?? DBNull.Value;
                }

                table.Rows.Add(row);
            }
            return table;
        }
        catch (DataException ex)
        {
            return null;
        }
        catch (Exception ex)
        {
            return null;
        }

    }
    private static DataTable CreateDataTable<T>() where T : class
    {
        Type objType = typeof(T);
        DataTable table = new DataTable(objType.Name);
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
        foreach (PropertyDescriptor property in properties)
        {
            Type propertyType = property.PropertyType;
            if (!CanUseType(propertyType)) continue;

            //nullables must use underlying types
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                propertyType = Nullable.GetUnderlyingType(propertyType);
            //enums also need special treatment
            if (propertyType.IsEnum)
                propertyType = Enum.GetUnderlyingType(propertyType);
            table.Columns.Add(property.Name, propertyType);
        }
        return table;
    }


    private static bool CanUseType(Type propertyType)
    {
        //only strings and value types
        if (propertyType.IsArray) return false;
        if (!propertyType.IsValueType && propertyType != typeof(string)) return false;
        return true;
    }
}

How to enable php7 module in apache?

First, disable the php5 module:

a2dismod php5

then, enable the php7 module:

a2enmod php7.0

Next, reload/restart the Apache service:

service apache2 restart

Update 2018-09-04

wrt the comment, you need to specify exact installed version.

RedirectToAction with parameter

I had this issue as well, and quite a nice way to do it if you are within the same controller is to use named parameters:

return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

PHP: How to use array_filter() to filter array keys?

With this function you can filter a multidimensional array

function filter_array_keys($array,$filter_keys=array()){

    $l=array(&$array);
    $c=1;
    //This first loop will loop until the count var is stable//
    for($r=0;$r<$c;$r++){
        //This loop will loop thru the child element list//
        $keys = array_keys($l[$r]);

        for($z=0;$z<count($l[$r]);$z++){
            $object = &$l[$r][$keys[$z]];

            if(is_array($object)){
                $i=0;
                $keys_on_array=array_keys($object);
                $object=array_filter($object,function($el) use(&$i,$keys_on_array,$filter_keys){
                    $key = $keys_on_array[$i];
                    $i++;

                    if(in_array($key,$filter_keys) || is_int($key))return false;                
                    return true;                        
                });
            }

            if(is_array($l[$r][$keys[$z]])){
                $l[] = &$l[$r][$keys[$z]];
                $c++;
            }//IF           
        }//FOR
    }//FOR  

    return $l[0];

}

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

How to copy and paste code without rich text formatting?

I usually work with Notepad2, all the text I copy from the web are pasted there and then reused, that allows me to clean it (from format and make modifications).

You can download Notepad2 here

Android: adb: Permission Denied

According to adb help:

adb root                     - restarts the adbd daemon with root permissions

Which indeed resolved the issue for me.

How do I access my webcam in Python?

John Montgomery's, answer is great, but at least on Windows, it is missing the line

vc.release()

before

cv2.destroyWindow("preview")

Without it, the camera resource is locked, and can not be captured again before the python console is killed.

HTML radio buttons allowing multiple selections

I've done it this way in the past, JsFiddle:

CSS:

.radio-option {
    cursor: pointer;
    height: 23px;
    width: 23px;
    background: url(../images/checkbox2.png) no-repeat 0px 0px;
}

.radio-option.click {
    background: url(../images/checkbox1.png) no-repeat 0px 0px;
}

HTML:

<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>

jQuery:

<script>
    $(document).ready(function() {
        $('.radio-option').click(function () {
            $(this).not(this).removeClass('click');
            $(this).toggleClass("click");
        });
    });
</script>

What does Ruby have that Python doesn't, and vice versa?

Ruby has embedded documentation:

 =begin

 You could use rdoc to generate man pages from this documentation

 =end

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I also had the same problem. In starting, it was working fine then, but sometime later I uninstalled my application completely from my device (I was running it on my mobile) and ran it again, and it shows me the same error.

I had all lib and resources included as it was working, but still I was getting this error so I removed all references and lib from my project build, updated google service play to revision 10, uninstalled application completely from the device and then again added all resources and libs and ran it and it started working again.

One thing to note here is while running I am still seeing this error message in my LogCat, but on my device it is working fine now.

"Missing return statement" within if / for / while

This will return the string only if the condition is true.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
    else
       return "";
}

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

You can try the following. Works fine in my case:

  1. Download the current jTDS JDBC Driver
  2. Put jtds-x.x.x.jar in your classpath.
  3. Copy ntlmauth.dll to windows/system32. Choose the dll based on your hardware x86,x64...
  4. The connection url is: 'jdbc:jtds:sqlserver://localhost:1433/YourDB' , you don't have to provide username and password.

Hope that helps.

Is there a "null coalescing" operator in JavaScript?

Yes, and its proposal is Stage 4 now. This means that the proposal is ready for inclusion in the formal ECMAScript standard. You can already use it in recent desktop versions of Chrome, Edge and Firefox, but we will have to wait for a bit longer until this feature reaches cross-browser stability.

Have a look at the following example to demonstrate its behavior:

_x000D_
_x000D_
// note: this will work only if you're running latest versions of aforementioned browsers_x000D_
const var1 = undefined;_x000D_
const var2 = "fallback value";_x000D_
_x000D_
const result = var1 ?? var2;_x000D_
console.log(`Nullish coalescing results in: ${result}`);
_x000D_
_x000D_
_x000D_

Previous example is equivalent to:

_x000D_
_x000D_
const var1 = undefined;_x000D_
const var2 = "fallback value";_x000D_
_x000D_
const result = (var1 !== null && var1 !== undefined) ?_x000D_
    var1 :_x000D_
    var2;_x000D_
console.log(`Nullish coalescing results in: ${result}`);
_x000D_
_x000D_
_x000D_

Note that nullish coalescing will not threat falsy values the way the || operator did (it only checks for undefined or null values), hence the following snippet will act as follows:

_x000D_
_x000D_
// note: this will work only if you're running latest versions of aforementioned browsers_x000D_
const var1 = ""; // empty string_x000D_
const var2 = "fallback value";_x000D_
_x000D_
const result = var1 ?? var2;_x000D_
console.log(`Nullish coalescing results in: ${result}`);
_x000D_
_x000D_
_x000D_


For TypesScript users, starting off TypeScript 3.7, this feature is also available now.

Use Mockito to mock some methods but not others

To directly answer your question, yes, you can mock some methods without mocking others. This is called a partial mock. See the Mockito documentation on partial mocks for more information.

For your example, you can do something like the following, in your test:

Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
when(stock.getValue()).thenCallRealMethod();  // Real implementation

In that case, each method implementation is mocked, unless specify thenCallRealMethod() in the when(..) clause.

There is also a possibility the other way around with spy instead of mock:

Stock stock = spy(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
// All other method call will use the real implementations

In that case, all method implementation are the real one, except if you have defined a mocked behaviour with when(..).

There is one important pitfall when you use when(Object) with spy like in the previous example. The real method will be called (because stock.getPrice() is evaluated before when(..) at runtime). This can be a problem if your method contains logic that should not be called. You can write the previous example like this:

Stock stock = spy(Stock.class);
doReturn(100.00).when(stock).getPrice();    // Mock implementation
doReturn(200).when(stock).getQuantity();    // Mock implementation
// All other method call will use the real implementations

Another possibility may be to use org.mockito.Mockito.CALLS_REAL_METHODS, such as:

Stock MOCK_STOCK = Mockito.mock( Stock.class, CALLS_REAL_METHODS );

This delegates unstubbed calls to real implementations.


However, with your example, I believe it will still fail, since the implementation of getValue() relies on quantity and price, rather than getQuantity() and getPrice(), which is what you've mocked.

Another possibility is to avoid mocks altogether:

@Test
public void getValueTest() {
    Stock stock = new Stock(100.00, 200);
    double value = stock.getValue();
    assertEquals("Stock value not correct", 100.00*200, value, .00001);
}

How to determine if one array contains all elements of another array

This can be achieved by doing

(a2 & a1) == a2

This creates the intersection of both arrays, returning all elements from a2 which are also in a1. If the result is the same as a2, you can be sure you have all elements included in a1.

This approach only works if all elements in a2 are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).

Format certain floating dataframe columns into percentage in pandas

As a similar approach to the accepted answer that might be considered a bit more readable, elegant, and general (YMMV), you can leverage the map method:

# OP example
df['var3'].map(lambda n: '{:,.2%}'.format(n))

# also works on a series
series_example.map(lambda n: '{:,.2%}'.format(n))

Performance-wise, this is pretty close (marginally slower) than the OP solution.

As an aside, if you do choose to go the pd.options.display.float_format route, consider using a context manager to handle state per this parallel numpy example.

Request string without GET arguments

Here is a solution that takes into account different ports and https:

$pageURL = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';

if ($_SERVER['SERVER_PORT'] != '80')
  $pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF'];
else 
  $pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];  

Or a more basic solution that does not take other ports into account:

$pageURL = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']; 

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You Can Go To setting > editor > general > code folding and check "show code folding outline" .

VBA Excel sort range by specific column

If the starting cell of the range and of the key is static, the solution can be very simple:

Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Sort key1:=Range("B3", Range("B3").End(xlDown)), _
order1:=xlAscending, Header:=xlNo

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Commenting here as this seems to be the most popular answer on the subject for searching for files whilst excluding certain directories in powershell.

To avoid issues with post filtering of results (i.e. avoiding permission issues etc), I only needed to filter out top level directories and that is all this example is based on, so whilst this example doesn't filter child directory names, it could very easily be made recursive to support this, if you were so inclined.

Quick breakdown of how the snippet works

$folders << Uses Get-Childitem to query the file system and perform folder exclusion

$file << The pattern of the file I am looking for

foreach << Iterates the $folders variable performing a recursive search using the Get-Childitem command

$folders = Get-ChildItem -Path C:\ -Directory -Name -Exclude Folder1,"Folder 2"
$file = "*filenametosearchfor*.extension"

foreach ($folder in $folders) {
   Get-Childitem -Path "C:/$folder" -Recurse -Filter $file | ForEach-Object { Write-Output $_.FullName }
}

Unix: How to delete files listed in a file

This is not very efficient, but will work if you need glob patterns (as in /var/www/*)

for f in $(cat 1.txt) ; do 
  rm "$f"
done

If you don't have any patterns and are sure your paths in the file do not contain whitespaces or other weird things, you can use xargs like so:

xargs rm < 1.txt

Android Image View Pinch Zooming

Using a ScaleGestureDetector

When learning a new concept I don't like using libraries or code dumps. I found a good description here and in the documentation of how to resize an image by pinching. This answer is a slightly modified summary. You will probably want to add more functionality later, but it will help you get started.

Animated gif: Scale image example

Layout

The ImageView just uses the app logo since it is already available. You can replace it with any image you like, though.

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Activity

We use a ScaleGestureDetector on the activity to listen to touch events. When a scale (ie, pinch) gesture is detected, then the scale factor is used to resize the ImageView.

public class MainActivity extends AppCompatActivity {

    private ScaleGestureDetector mScaleGestureDetector;
    private float mScaleFactor = 1.0f;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // initialize the view and the gesture detector
        mImageView = findViewById(R.id.imageView);
        mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
    }

    // this redirects all touch events in the activity to the gesture detector
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mScaleGestureDetector.onTouchEvent(event);
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        // when a scale gesture is detected, use it to resize the image
        @Override
        public boolean onScale(ScaleGestureDetector scaleGestureDetector){
            mScaleFactor *= scaleGestureDetector.getScaleFactor();
            mImageView.setScaleX(mScaleFactor);
            mImageView.setScaleY(mScaleFactor);
            return true;
        }
    }
}

Notes

  • Although the activity had the gesture detector in the example above, it could have also been set on the image view itself.
  • You can limit the size of the scaling with something like

    mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
    
  • Thanks again to Pinch-to-zoom with multi-touch gestures In Android

  • Documentation
  • Use Ctrl + mouse drag to simulate a pinch gesture in the emulator.

Going on

You will probably want to do other things like panning and scaling to some focus point. You can develop these things yourself, but if you would like to use a pre-made custom view, copy TouchImageView.java into your project and use it like a normal ImageView. It worked well for me and I only ran into one bug. I plan to further edit the code to remove the warning and the parts that I don't need. You can do the same.

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

So in Short,

vi ~/.proxy_info

export http_proxy=<username>:<password>@<proxy>:8080
export https_proxy=<username>:<password>@<proxy>:8080

source ~/.proxy_info

Hope this helps someone in hurry :)

"Sub or Function not defined" when trying to run a VBA script in Outlook

I solved the problem by following the instructions on msdn.microsoft.com more closely. There, it is stated that one must create the new macro by selecting Developer -> Macros, typing a new macro name, and clicking "Create". Creating the macro in this way, I was able to run it (see message box below).

enter image description here

How to have image and text side by side

Use following code : jsfiddle.net/KqHEC/

HTML

<div class='container2'>
        <div class="left">
            <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
        </div>  
    <div   class="right" >
    <h4>Facebook</h4>
    <div style="font-size:.7em;width:160px;float:left;">fine location, GPS, coarse location</div>
    <div style="float:right;font-size:.7em">0 mins ago</div>
    </div>
</div>

CSS

.iconDetails {
 margin-left:2%;
float:left; 
height:40px;
width:40px; 
} 

.container2 {
    width:270px;
    height:auto;
    padding:1%;
    float:left;
}
h4{margin:0}
.left {float:left;width:45px;}
.right {float:left;margin:0 0 0 5px;width:215px;}

http://jsfiddle.net/KqHEC/1/

SQL: How do I SELECT only the rows with a unique value on certain column?

SELECT DISTINCT Contract, Activity
FROM Contract WHERE Contract IN (
SELECT Contract 
FROM Contract
GROUP BY Contract
HAVING COUNT( DISTINCT Activity ) = 1 )

How to prevent tensorflow from allocating the totality of a GPU memory?

All the answers above refer to either setting the memory to a certain extent in TensorFlow 1.X versions or to allow memory growth in TensorFlow 2.X.

The method tf.config.experimental.set_memory_growth indeed works for allowing dynamic growth during the allocation/preprocessing. Nevertheless one may like to allocate from the start a specific GPU memory.

The logic behind allocating a specific GPU memory would also be to prevent OOM memory during training sessions. For example, if one trains while opening video-memory consuming Chrome tabs/any other video consumption process, the tf.config.experimental.set_memory_growth(gpu, True) could result in OOM errors thrown, hence the necessity of allocating from the start more memory in certain cases.

The recommended and correct way in which to allot memory per GPU in TensorFlow 2.X is done in the following manner:

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)]

Is there any way to prevent input type="number" getting negative values?

Just for reference: with jQuery you can overwrite negative values on focusout with the following code:

$(document).ready(function(){
    $("body").delegate('#myInputNumber', 'focusout', function(){
        if($(this).val() < 0){
            $(this).val('0');
        }
    });
});

This does not replace server side validation!

Close Window from ViewModel

This is a way I did it pretty simply:

YourWindow.xaml.cs

//In your constructor
public YourWindow()
{
    InitializeComponent();
    DataContext = new YourWindowViewModel(this);
}

YourWindowViewModel.cs

private YourWindow window;//so we can kill the window

//In your constructor
public YourWindowViewModel(YourWindow window)
{
    this.window = window;
}

//to close the window
public void CloseWindow()
{
    window.Close();
}

I don't see anything wrong with the answer you chose, I just thought this might be a more simple way to do it!

AngularJS format JSON string output

If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:

https://github.com/mohsen1/json-formatter/

enter image description here

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It's the part after the headers and the CRLF of a HTTP Request.

A request with Content-Type: application/json may look like this:

POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.

If you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded

foo=bar&name=John

In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.

So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.

Recommended way to get hostname in Java

If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.

https://github.com/mattsheppard/gethostname4j

MySQL Database won't start in XAMPP Manager-osx

For me the following worked: Change permission into 'read only' for 'everyone' to the file /Applications/XAMPP/xamppfiles/etc/my.cnf. Then start MySQL from XAMPP manager.

Inline labels in Matplotlib

A simpler approach like the one Ioannis Filippidis do :

import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)

# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')

factor=3/4 ;offset=20  # text position in view  
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()

code python 3 on sageCell

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

How to get the first and last date of the current year?

select to_date(substr(sysdate,1, 4) || '01/01'), to_date(substr(sysdate,1, 4) || '12/31') 
from dual

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

ORDER_BY cast(registration_no as unsigned) ASC

explicitly converts the value to a number. Another possibility to achieve the same would be

ORDER_BY registration_no + 0 ASC

which will force an implicit conversation.

Actually you should check the table definition and change it. You can change the data type to int like this

ALTER TABLE your_table MODIFY COLUMN registration_no int;

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

How to run ~/.bash_profile in mac terminal

If the problem is that you are not seeing your changes to the file take effect, just open a new terminal window, and it will be "sourced". You will be able to use the proper PATH etc with each subsequent terminal window.

How can I disable a specific LI element inside a UL?

Using JQuery : http://api.jquery.com/hide/

$('li.two').hide()

In :

<ul class="lul">
    <li class="one">a</li>
    <li class="two">b</li>
    <li class="three">c</li>
</ul>

On document ready.

http://jsfiddle.net/2dDSG/

Is background-color:none valid CSS?

You probably want transparent as none is not a valid background-color value.

The CSS 2.1 spec states the following for the background-color property:

Value: <color> | transparent | inherit

<color> can be either a keyword or a numerical representation of a colour. Valid color keywords are:

aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow

transparent and inherit are valid keywords in their own right, but none is not.

Convert StreamReader to byte[]

You can use this code: You shouldn't use this code:

byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());

Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.

Removing nan values from an array

Simply fill with

 x = numpy.array([
 [0.99929941, 0.84724713, -0.1500044],
 [-0.79709026, numpy.NaN, -0.4406645],
 [-0.3599013, -0.63565744, -0.70251352]])

x[numpy.isnan(x)] = .555

print(x)

# [[ 0.99929941  0.84724713 -0.1500044 ]
#  [-0.79709026  0.555      -0.4406645 ]
#  [-0.3599013  -0.63565744 -0.70251352]]

How to create a CPU spike with a bash command

You can also do

dd if=/dev/zero of=/dev/null

To run more of those to put load on more cores, try to fork it:

fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd

Repeat the command in the curly brackets as many times as the number of threads you want to produce (here 4 threads). Simple enter hit will stop it (just make sure no other dd is running on this user or you kill it too).

Which comment style should I use in batch files?

tl;dr: REM is the documented and supported way to embed comments in batch files.


:: is essentially a blank label that can never be jumped to, whereas REM is an actual command that just does nothing. In neither case (at least on Windows 7) does the presence of redirection operators cause a problem.

However, :: is known to misbehave in blocks under certain circumstances, being parsed not as a label but as some sort of drive letter. I'm a little fuzzy on where exactly but that alone is enough to make me use REM exclusively. It's the documented and supported way to embed comments in batch files whereas :: is merely an artifact of a particular implementation.


Here is an example where :: produces a problem in a FOR loop.

This example will not work in a file called test.bat on your desktop:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    ::echo hello>C:\Users\%username%\Desktop\text.txt
)
pause

While this example will work as a comment correctly:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    REM echo hello>C:\Users\%username%\Desktop\text.txt
)
pause

The problem appears to be when trying to redirect output into a file. My best guess is that it is interpreting :: as an escaped label called :echo.

PHP Accessing Parent Class Variable

class A {
    private $aa;
    protected $bb = 'parent bb';

    function __construct($arg) {
       //do something..
    }

    private function parentmethod($arg2) {
       //do something..
    }
}

class B extends A {
    function __construct($arg) {
        parent::__construct($arg);
    }
    function childfunction() {
        echo parent::$this->bb; //works by M
    }
}

$test = new B($some);
$test->childfunction();`

How do I connect to a Websphere Datasource with a given JNDI name?

DNS for Services

JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.

What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.

Simple example.

javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");

Here is IBM's reference page.

If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE

How do you run CMD.exe under the Local System Account?

I use the RunAsTi utility to run as TrustedInstaller (high privilege). The utility can be used even in recovery mode of Windows (the mode you enter by doing Shift+Restart), the psexec utility doesn't work there. But you need to add your C:\Windows and C:\Windows\System32 (not X:\Windows and X:\Windows\System32) paths to the PATH environment variable, otherwise RunAsTi won't work in recovery mode, it will just print: AdjustTokenPrivileges for SeImpersonateName: Not all privileges or groups referenced are assigned to the caller.

Open Source Alternatives to Reflector?

Another replacement would be dotPeek. JetBrains announced it as a free tool. It will probably have more features when used with their Resharper but even when used alone it works very well.

User experience is more like MSVS than a standalone disassembler. I like code reading more than in Reflector. Ctrl+T navigation suits me better too. Just synchronizing the tree with the code pane could be better.

All in all, it is still in development but very well usable already.

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

Make a dictionary in Python from input values

This is what we ended up using:

n = 3
d = dict(raw_input().split() for _ in range(n))
print d

Input:

A1023 CRT
A1029 Regulator
A1030 Therm

Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

ExpressJS How to structure an application?

This is how most of my express project directory structure looks.

I usually do a express dirname to initialise the project, forgive my laziness, but it's very flexible and extendable. PS - you need to get express-generator for that (for those who're looking for it sudo npm install -g express-generator, sudo because you're installing it globally)

|-- bin
    |-- www //what we start with "forever"
|-- bower_components
|-- models
    |-- database.js
    |-- model1.js //not this exact name ofcourse.
    |-- .
|-- node_modules
|-- public
    |-- images
    |-- javascripts
        |-- controllers
        |-- directives
        |-- services
        |-- app.js
        |-- init.js //contains config and used for initializing everything, I work with angular a lot.
    |-- stylesheets
|-- routes
    |-- some
    |-- hierarchy
    .
    .
|-- views
    |-- partials
    |-- content
|-- .env
|-- .env.template
|-- app.js
|-- README.md

You must be wondering why .env files? Because they work! I use dotenv module in my projects (a lot recently) and it works! Pop in these 2 statements in app.js or www

var dotenv = require('dotenv');
dotenv.config({path: path.join(__dirname + "/.env")});

And another line to quickly set /bower_components to serve static content under the resource /ext

app.use('/ext', express.static(path.join(__dirname, 'bower_components')));

It probably can be a fit for people who're looking to use Express and Angular together, or just express without that javascripts hierarchy of course.

How to detect pressing Enter on keyboard using jQuery?

this my how I solved you shoud give return false;

_x000D_
_x000D_
 
 $(document).on('keypress',function(e) {
            if(e.which == 13) {
                $('#sub_btn').trigger('click');
                alert('You pressed a "enter" key in somewhere'); 
                return false;     
            }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
                    <div class="modal-header">
                        <button type="button" class="close" id="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Subscribe to our Technical Analysis</h4>
                    </div>
                    <div class="modal-body">
                        <p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
                        <div class="input-group">
                            <input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
                        </div>
                        <span id="save-error"></span>
                    </div>
                    <div class="modal-footer">
                        <div class="input-group-append">
                            <input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
                        </div>
                    </div>
                </form>
_x000D_
_x000D_
_x000D_

`

What exactly do "u" and "r" string flags do, and what are raw string literals?

Let me explain it simply: In python 2, you can store string in 2 different types.

The first one is ASCII which is str type in python, it uses 1 byte of memory. (256 characters, will store mostly English alphabets and simple symbols)

The 2nd type is UNICODE which is unicode type in python. Unicode stores all types of languages.

By default, python will prefer str type but if you want to store string in unicode type you can put u in front of the text like u'text' or you can do this by calling unicode('text')

So u is just a short way to call a function to cast str to unicode. That's it!

Now the r part, you put it in front of the text to tell the computer that the text is raw text, backslash should not be an escaping character. r'\n' will not create a new line character. It's just plain text containing 2 characters.

If you want to convert str to unicode and also put raw text in there, use ur because ru will raise an error.

NOW, the important part:

You cannot store one backslash by using r, it's the only exception. So this code will produce error: r'\'

To store a backslash (only one) you need to use '\\'

If you want to store more than 1 characters you can still use r like r'\\' will produce 2 backslashes as you expected.

I don't know the reason why r doesn't work with one backslash storage but the reason isn't described by anyone yet. I hope that it is a bug.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

What does "async: false" do in jQuery.ajax()?

Does it have something to do with preventing other events on the page from firing?

Yes.

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

For more insight see: jQuery ajax success anonymous function scope

Can I restore a single table from a full mysql mysqldump file?

You can import single table using terminal line as given below. Here import single user table into specific database.

mysql -u root -p -D my_database_name < var/www/html/myproject/tbl_user.sql

How to add minutes to my Date

use this format,

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

mm for minutes and MM for mounth

What is an unsigned char?

quoted frome "the c programming laugage" book:

The qualifier signed or unsigned may be applied to char or any integer. unsigned numbers are always positive or zero, and obey the laws of arithmetic modulo 2^n, where n is the number of bits in the type. So, for instance, if chars are 8 bits, unsigned char variables have values between 0 and 255, while signed chars have values between -128 and 127 (in a two' s complement machine.) Whether plain chars are signed or unsigned is machine-dependent, but printable characters are always positive.

How to generate class diagram from project in Visual Studio 2013?

Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.


For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio


This feature still available, but it is NOT available by default, you have to install it separately.

  1. Open VS 2019 go to Tools -> Get Tools and Features
  2. Select the Individual components tab and search for Class Designer
  3. Select this Component and Install it, After finish installing this component (you may need to restart visual studio)
  4. Right-click on the project and select Add -> Add New Item
  5. Search for 'class' word and NOW you can see Class Diagram component

see this answer also to see an image associated

https://stackoverflow.com/a/66289543/4390133

(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)


Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)

  1. Add class diagram to the project
  2. if the option Preview Selected Items is enabled in the solution explorer, disabled it temporarily, you can re-enable it later

enter image description here

  1. open the class diagram that you created in step 2 (by double-clicking on it)
  2. drag-and-drop the project from the solution explorer to the class diagram

you could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)

Blurry text after using CSS transform: scale(); in Chrome

None of the above worked for me.

It worked when I added perspective

ie from

transform : translate3d(-10px,-20px,0) scale3d(0.7,0.7, 1)

i changed to

transform : perspective(1px) translate3d(-10px,-20px,0) scale3d(0.7,0.7, 1)

Stop form refreshing page on submit

I hope this will be the last answer


_x000D_
_x000D_
$('#the_form').submit(function(e){_x000D_
  e.preventDefault()_x000D_
  alert($(this).serialize())_x000D_
  // var values = $(this).serialize()_x000D_
  // logic...._x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form id="the_form">_x000D_
   Label-A <input type="text" name='a'required><br>_x000D_
   Label-B <input type="text" name="b" required><br>_x000D_
   Label-C <input type="password" name="c" required><br>_x000D_
   Label-D <input type="number" name="d" required><br>_x000D_
   <input type="submit" value="Save without refresh">_x000D_
</form>
_x000D_
_x000D_
_x000D_

how to generate public key from windows command prompt

Just download and install openSSH for windows. It is open source, and it makes your cmd ssh ready. A quick google search will give you a tutorial on how to install it, should you need it.

After it is installed you can just go ahead and generate your public key if you want to put in on a server. You generate it by running:

ssh-keygen -t rsa

After that you can just can just press enter, it will automatically assign a name for the key (example: id_rsa.pub)

How do I store and retrieve a blob from sqlite?

You need to use sqlite's prepared statements interface. Basically, the idea is that you prepare a statement with a placeholder for your blob, then use one of the bind calls to "bind" your data...

SQLite Prepared Statements

How to get the day of week and the month of the year?

var GetWeekDays = function (format) {
    var weekDays = {};

    var curDate = new Date();
    for (var i = 0; i < 7; ++i) {
        weekDays[curDate.getDay()] = curDate.toLocaleDateString('ru-RU', {
            weekday: format ? format : 'short'
        });

        curDate.setDate(curDate.getDate() + 1);
    }

    return weekDays;
};

me.GetMonthNames = function (format) {
    var monthNames = {};

    var curDate = new Date();
    for (var i = 0; i < 12; ++i) {
        monthNames[curDate.getMonth()] = curDate.toLocaleDateString('ru-RU', {
            month: format ? format : 'long'
        });

        curDate.setMonth(curDate.getMonth() + 1);
    }

    return monthNames;
};

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

how to set length of an column in hibernate with maximum length

Use @Column annotation and define its length attribute. Check Hibernate's documentation for references (section 2.2.2.3).

What causes "Unable to access jarfile" error?

I use NetBeans and had the same issue. After I ran build and clean project my program was executable. The Java documentation says that the build/clean command is for rebuilding the project from scratch basically and removing any past compiles. I hope this helps. Also, I'd read the documentation. Oracle has NetBeans and Java learning trails. Very helpful. Good luck!

Latex Multiple Linebreaks

You can use the setspace package which gives you spacing environments, e.g.:

\documentclass{article}
\usepackage{setspace}
\begin{document}
\doublespace
my line of text blah blah blah

new line of text with blank line between
\end{document}

Or use a verbatim environment to control the layout of your code precisely.

Scroll part of content in fixed position container

Set the scrollable div to have a max-size and add overflow-y: scroll; to it's properties.

Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.

echo key and value of an array without and with loop

Without a loop, just for the kicks of it...


You can either convert the array to a non-associative one, by doing:

$page = array_values($page);

And then acessing each element by it's zero-based index:

echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'

Or you can use a slightly more complicated version:

$value = array_slice($page, 0, 1);

echo key($value); // Home
echo current($value); // index.html

$value = array_slice($page, 1, 1);

echo key($value); // Service
echo current($value); // services.html

How do I do redo (i.e. "undo undo") in Vim?

CTRL+r

The "r" is lower-case.

How to define a Sql Server connection string to use in VB.NET?

Set the connection string in your config file:

<connectionStrings>
    <add name="ConnString"
         connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gadgetDatabase.mdf;Integrated Security=True" />
</connectionStrings>

How to read fetch(PDO::FETCH_ASSOC);

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.

You can access the name field like this: $user['name'].

I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

How to search contents of multiple pdf files?

Your distribution should provide a utility called pdftotext:

find /path -name '*.pdf' -exec sh -c 'pdftotext "{}" - | grep --with-filename --label="{}" --color "your pattern"' \;

The "-" is necessary to have pdftotext output to stdout, not to files. The --with-filename and --label= options will put the file name in the output of grep. The optional --color flag is nice and tells grep to output using colors on the terminal.

(In Ubuntu, pdftotext is provided by the package xpdf-utils or poppler-utils.)

This method, using pdftotext and grep, has an advantage over pdfgrep if you want to use features of GNU grep that pdfgrep doesn't support. Note: pdfgrep-1.3.x supports -C option for printing line of context.

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

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

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

Copy an entire worksheet to a new worksheet in Excel 2010

' Assume that the code name the worksheet is Sheet1

' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)

' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"

How to read the content of a file to a string in C?

If "read its contents into a string" means that the file does not contain characters with code 0, you can also use getdelim() function, that either accepts a block of memory and reallocates it if necessary, or just allocates the entire buffer for you, and reads the file into it until it encounters a specified delimiter or end of file. Just pass '\0' as the delimiter to read the entire file.

This function is available in the GNU C Library, http://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getdelim-994

The sample code might look as simple as

char* buffer = NULL;
size_t len;
ssize_t bytes_read = getdelim( &buffer, &len, '\0', fp);
if ( bytes_read != -1) {
  /* Success, now the entire file is in the buffer */

Iterate through every file in one directory

This is my favorite method for being easy to read:

Dir.glob("*/*.txt") do |my_text_file|
  puts "working on: #{my_text_file}..."
end

And you can even extend this to work on all files in subdirs:

Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
  puts "working on: #{my_text_file}..."
end

how to set ul/li bullet point color?

I believe this is controlled by the css color property applied to the element.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

If a array is of type multidimension like below then we have to write below linq to check the data.

example: here elements are 0 and i am checking all values are 0 or not.
ip1=
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

    var value=ip1[0][0];  //got the first index value
    var equalValue = ip1.Any(x=>x.Any(xy=>xy.Equals()));  //check with all elements value 
    if(equalValue)//returns true or false  
    {  
    return "Same Numbers";  
    }else{  
    return "Different Numbers";   
    }

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

Format Date time in AngularJS

Add $filter dependency in controller.

var formatted_datetime = $filter('date')(variable_Containing_time,'yyyy-MM-dd HH:mm:ss Z')

How can I select random files from a directory in bash?

MacOS does not have the sort -R and shuf commands, so I needed a bash only solution that randomizes all files without duplicates and did not find that here. This solution is similar to gniourf_gniourf's solution #4, but hopefully adds better comments.

The script should be easy to modify to stop after N samples using a counter with if, or gniourf_gniourf's for loop with N. $RANDOM is limited to ~32000 files, but that should do for most cases.

#!/bin/bash

array=(*)  # this is the array of files to shuffle
# echo ${array[@]}
for dummy in "${array[@]}"; do  # do loop length(array) times; once for each file
    length=${#array[@]}
    randomi=$(( $RANDOM % $length ))  # select a random index

    filename=${array[$randomi]}
    echo "Processing: '$filename'"  # do something with the file

    unset -v "array[$randomi]"  # set the element at index $randomi to NULL
    array=("${array[@]}")  # remove NULL elements introduced by unset; copy array
done

Google Script to see if text contains a value

Google Apps Script is javascript, you can use all the string methods...

var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }

You can find doc on many sites, this one for example.

Convert Little Endian to Big Endian

You could do this:

int x = 0x12345678;

x = ( x >> 24 ) | (( x << 8) & 0x00ff0000 )| ((x >> 8) & 0x0000ff00) | ( x << 24)  ; 

printf("value = %x", x);  // x will be printed as 0x78563412

Can't clone a github repo on Linux via HTTPS

Make sure you have git 1.7.10 or later, it now prompts for user/password correctly. (You can download the latest version here)

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

How can I get the max (or min) value in a vector?

Using c++11/c++0x compile flags, you can

auto it = max_element(std::begin(cloud), std::end(cloud)); // c++11

Otherwise, write your own:

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }    
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

See it live at http://ideone.com/aDkhW:

#include <iostream>
#include <algorithm>

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }    
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

int main()
{
    const int cloud[] = { 1,2,3,4,-7,999,5,6 };

    std::cout << *std::max_element(mybegin(cloud), myend(cloud)) << '\n';
    std::cout << *std::min_element(mybegin(cloud), myend(cloud)) << '\n';
}

Oh, and use std::minmax_element(...) if you need both at once :/

JavaScript property access: dot notation vs. brackets?

Be careful while using these notations: For eg. if we want to access a function present in the parent of a window. In IE :

window['parent']['func']

is not equivalent to

window.['parent.func']

We may either use:

window['parent']['func'] 

or

window.parent.func 

to access it

Error: TypeError: $(...).dialog is not a function

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

Find empty or NaN entry in Pandas Dataframe

Try this:

df[df['column_name'] == ''].index

and for NaNs you can try:

pd.isna(df['column_name'])

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

What does "Content-type: application/json; charset=utf-8" really mean?

To substantiate @deceze's claim that the default JSON encoding is UTF-8...

From IETF RFC4627:

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.

      00 00 00 xx  UTF-32BE
      00 xx 00 xx  UTF-16BE
      xx 00 00 00  UTF-32LE
      xx 00 xx 00  UTF-16LE
      xx xx xx xx  UTF-8

Scrolling an iframe with JavaScript?

I've also had trouble using any type of javascript "scrollTo" function in an iframe on an iPad. Finally found an "old" solution to the problem, just hash to an anchor.

In my situation after an ajax return my error messages were set to display at the top of the iframe but if the user had scrolled down in what is an admittedly long form the submission goes out and the error appears "above the fold". Additionally, assuming the user did scroll way down the top level page was scrolled away from 0,0 and was also hidden.

I added

<a name="ptop"></a>

to the top of my iframe document and

<a name="atop"></a>

to the top of my top level page

then

    $(document).ready(function(){
      $("form").bind("ajax:complete",
        function() {
          location.hash = "#";
          top.location.hash = "#";
          setTimeout('location.hash="#ptop"',150);
          setTimeout('top.location.hash="#atop"',350);
        }
      )
    });

in the iframe.

You have to hash the iframe before the top page or only the iframe will scroll and the top will remain hidden but while it's a tiny bit "jumpy" due to the timeout intervals it works. I imagine tags throughout would allow various "scrollTo" points.

Android: Changing Background-Color of the Activity (Main View)

First Method

 View someView = findViewById(R.id.randomViewInMainLayout);// get Any child View

  // Find the root view
  View root = someView.getRootView()

  // Set the color
  root.setBackgroundColor(getResources().getColor(android.R.color.red));

Second Method

Add this single line after setContentView(...);

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

Third Method

set background color to the rootView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="@+id/rootView"
</LinearLayout>

Important Thing

rootView.setBackgroundColor(0xFF00FF00); //after 0x the other four pairs are alpha,red,green,blue color. 

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

Concatenating strings in C, which method is more efficient?

size_t lf = strlen(first);
size_t ls = strlen(second);

char *both = (char*) malloc((lf + ls + 2) * sizeof(char));

strcpy(both, first);

both[lf] = ' ';
strcpy(&both[lf+1], second);

LINQ: Distinct values

I'm a bit late to the answer, but you may want to do this if you want the whole element, not only the values you want to group by:

var query = doc.Elements("whatever")
               .GroupBy(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Select(e => e.First());

This will give you the first whole element matching your group by selection, much like Jon Skeets second example using DistinctBy, but without implementing IEqualityComparer comparer. DistinctBy will most likely be faster, but the solution above will involve less code if performance is not an issue.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Please take a look here

HH is hour in a day (starting from 0 to 23)

hh are hours in am/pm format

kk is hour in day (starting from 1 to 24)

mm is minute in hour

ss are the seconds in a minute

Checking length of dictionary object

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.

I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

Edit #1: Why can't you just do this?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The length is already set.

Auto Scale TextView Text to Fit within Bounds

From June 2018 Android officially started supporting this feature for Android 4.0 (API level 14) and higher.
Check it out at: Autosizing TextViews

With Android 8.0 (API level 26) and higher:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
    android:autoSizeMinTextSize="12sp"
    android:autoSizeMaxTextSize="100sp"
    android:autoSizeStepGranularity="2sp" />

Programmatically:

setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, 
        int autoSizeStepGranularity, int unit)

textView.setAutoSizeTextTypeUniformWithConfiguration(
                1, 17, 1, TypedValue.COMPLEX_UNIT_DIP);


Android versions prior to Android 8.0 (API level 26):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <TextView
      android:layout_width="match_parent"
      android:layout_height="200dp"
      app:autoSizeTextType="uniform"
      app:autoSizeMinTextSize="12sp"
      app:autoSizeMaxTextSize="100sp"
      app:autoSizeStepGranularity="2sp" />

</LinearLayout>

Programmatically:

TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
TextView textView, int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit) 

TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(textView, 1, 17, 1,
TypedValue.COMPLEX_UNIT_DIP);

Attention: TextView must have layout_width="match_parent" or absolute size!

How to download source in ZIP format from GitHub?

To clone that repository via a URL like that: yes, you do need a client, and that client is Git. That will let you make changes, your own branches, merge back in sync with other developers, maintain your own source that you can easily keep up to date without downloading the whole thing each time and writing over your own changes etc. A ZIP file won't let you do that.

It is mostly meant for people who want to develop the source rather than people who just want to get the source one off and not make changes.

But it just so happens you can get a ZIP file as well:

Click on http://github.com/zoul/Finch/ and then click on the green Clone or Download button. See here:

enter image description here

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I got similar error (org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15) while using aspectj 1.8.13. Solution was to align all compilation into jdk 8 and being careful not to put aspectj library's (1.6.13 for instance) other versions to buildpath/classpath.

How to submit an HTML form without redirection

You can achieve that by redirecting the form's action to an invisible <iframe>. It doesn't require any JavaScript or any other type of scripts.

<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>

<form action="submitscript.php" target="dummyframe">
    <!-- Form body here -->
</form>

Returning Promises from Vuex actions

TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.

For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.

But, there are EDGE CASES where returning a promise from your actions might be "necessary".

Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.

Dumb example

Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.

Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.

How does Java resolve a relative path in new File()?

When your path starts with a root dir i.e. C:\ in windows or / in Unix or in java resources path, it is considered to be an absolute path. Everything else is relative, so

new File("test.txt") is the same as new File("./test.txt")

new File("test/../test.txt") is the same as new File("./test/../test.txt")

The major difference between getAbsolutePath and getCanonicalPath is that the first one concatenates a parent and a child path, so it may contain dots: .. or .. getCanonicalPath will always return the same path for a particular file.

Note: File.equals uses an abstract form of a path (getAbsolutePath) to compare files, so this means that two File objects for the same might not be equal and Files are unsafe to use in collections like Map or Set.

What is the purpose of using -pedantic in GCC/G++ compiler?

If your code needs to be portable then you can test that it compiles without any gcc extensions or other non-standard features. If your code compiles with -pedantic -ansi then in theory it should compile OK with any other ANSI standard compiler.

MySQL/SQL: Group by date only on a Datetime column

SELECT SUM(No), HOUR(dateofissue) 
FROM tablename 
WHERE dateofissue>='2011-07-30' 
GROUP BY HOUR(dateofissue)

It will give the hour by sum from a particular day!

Ruby on Rails generates model field:type - what are the options for field:type?

Remember to not capitalize your text when writing this command. For example:

Do write:

rails g model product title:string description:text image_url:string price:decimal

Do not write:

rails g Model product title:string description:text image_url:string price:decimal

At least it was a problem to me.

What is Options +FollowSymLinks?

You might try searching the internet for ".htaccess Options not allowed here".

A suggestion I found (using google) is:

Check to make sure that your httpd.conf file has AllowOverride All.

A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):

# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html

# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>

# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.

Save file to specific folder with curl command

For powershell in Windows, you can add relative path + filename to --output flag:

curl -L  http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip

here build_firefox is relative folder.

How to get address of a pointer in c/c++?

Having this C source:

int a = 10;
int * ptr = &a;

Use this

printf("The address of ptr is %p\n", (void *) &ptr);

to print the address of ptr.

Please note that the conversion specifier p is the only conversion specifier to print a pointer's value and it is defined to be used with void* typed pointers only.

From man printf:

p

The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx).

Unable to convert MySQL date/time value to System.DateTime

i added both Convert Zero Datetime=True & Allow Zero Datetime=True and it works fine

What is middleware exactly?

If I am not wrong, in software application framework, based on the context, you can consider middleware for the following roles that can be combined in order to perform certain activities in between the user request and the application response.

  • Adapter
  • Sanitizer
  • Validator

Why Is `Export Default Const` invalid?

const is like let, it is a LexicalDeclaration (VariableStatement, Declaration) used to define an identifier in your block.

You are trying to mix this with the default keyword, which expects a HoistableDeclaration, ClassDeclaration or AssignmentExpression to follow it.

Therefore it is a SyntaxError.


If you want to const something you need to provide the identifier and not use default.

export by itself accepts a VariableStatement or Declaration to its right.


AFAIK the export in itself should not add anything to your current scope.


The following is fineexport default Tab;

Tab becomes an AssignmentExpression as it's given the name default ?

export default Tab = connect( mapState, mapDispatch )( Tabs ); is fine

Here Tab = connect( mapState, mapDispatch )( Tabs ); is an AssignmentExpression.

Javascript ES6/ES5 find in array and change

May be use Filter.

const list = [{id:0}, {id:1}, {id:2}];
let listCopy = [...list];
let filteredDataSource = listCopy.filter((item) => {
       if (item.id === 1) {
           item.id = 12345;
        }

        return item;
    });
console.log(filteredDataSource);

Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]

Java HTTP Client Request with defined timeout

It looks like you are using the HttpClient API, which I know nothing about, but you could write something similar to this using core Java.

try {

   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");
   con.setConnectTimeout(5000); //set timeout to 5 seconds
   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);

} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

jquery/javascript convert date string to date

I used the javascript date funtion toLocaleDateString to get

var Today = new Date();
var r = Today.toLocaleDateString();

The result of r will be

11/29/2016

More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp

Setup a Git server with msysgit on Windows

You don't need SSH for sharing git. If you're on a LAN or VPN, you can export a git project as a shared folder, and mount it on a remote machine. Then configure the remote repo using "file://" URLs instead of "git@" URLs. Takes all of 30 seconds. Done!

Implementing a HashMap in C

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

jquery toggle slide from left to right and back

Hide #categories initially

#categories {
    display: none;
}

and then, using JQuery UI, animate the Menu slowly

var duration = 'slow';

$('#cat_icon').click(function () {
    $('#cat_icon').hide(duration, function() {
        $('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

You can use any time in milliseconds as well

var duration = 2000;

If you want to hide on class='panel_item' too, select both panel_title and panel_item

$('.panel_title,.panel_item').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

Switch statement multiple cases in JavaScript

Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:

var i = 3
switch (i) {
    case ((i>=0 && i<=5) ? i : -1):
        console.log('0-5');
        break;

    case 6: console.log('6');
}

So in your problem, you could do something like:

var varName = "afshin"
switch (varName) {
    case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
      console.log("hey");
      break;

    default:
      console.log('Default case');
}

Although it is so much DRY...

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.

Angular2 set value for formGroup

As pointed out in comments, this feature wasn't supported at the time this question was asked. This issue has been resolved in angular 2 rc5

jQuery .val() vs .attr("value")

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

How to get scrollbar position with Javascript?

document.getScroll = function() {
    if (window.pageYOffset != undefined) {
        return [pageXOffset, pageYOffset];
    } else {
        var sx, sy, d = document,
            r = d.documentElement,
            b = d.body;
        sx = r.scrollLeft || b.scrollLeft || 0;
        sy = r.scrollTop || b.scrollTop || 0;
        return [sx, sy];
    }
}

returns an array with two integers- [scrollLeft, scrollTop]

String's Maximum length in Java - calling length() method

As mentioned in Takahiko Kawasaki's answer, java represents Unicode strings in the form of modified UTF-8 and in JVM-Spec CONSTANT_UTF8_info Structure, 2 bytes are allocated to length (and not the no. of characters of String).
To extend the answer, the ASM jvm bytecode library's putUTF8 method, contains this:

public ByteVector putUTF8(final String stringValue) {
    int charLength = stringValue.length();
    if (charLength > 65535) {   
   // If no. of characters> 65535, than however UTF-8 encoded length, wont fit in 2 bytes.
      throw new IllegalArgumentException("UTF8 string too large");
    }
    for (int i = 0; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= '\u0001' && charValue <= '\u007F') {
        // Unicode code-point encoding in utf-8 fits in 1 byte.
        currentData[currentLength++] = (byte) charValue;
      } else {
        // doesnt fit in 1 byte.
        length = currentLength;
        return encodeUtf8(stringValue, i, 65535);
      }
    }
    ...
}

But when code-point mapping > 1byte, it calls encodeUTF8 method:

final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength /*= 65535 */) {
    int charLength = stringValue.length();
    int byteLength = offset;
    for (int i = offset; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= 0x0001 && charValue <= 0x007F) {
        byteLength++;
      } else if (charValue <= 0x07FF) {
        byteLength += 2;
      } else {
        byteLength += 3;
      }
    }
   ...
}

In this sense, the max string length is 65535 bytes, i.e the utf-8 encoding length. and not char count
You can find the modified-Unicode code-point range of JVM, from the above utf8 struct link.

Character Limit in HTML

use the "maxlength" attribute as others have said.

if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

What is the purpose of nameof?

The purpose of the nameof operator is to provide the source name of the artifacts.

Usually the source name is the same name as the metadata name:

public void M(string p)
{
    if (p == null)
    {
        throw new ArgumentNullException(nameof(p));
    }
    ...
}

public int P
{
    get
    {
        return p;
    }
    set
    {
        p = value;
        NotifyPropertyChanged(nameof(P));
    }
}

But this may not always be the case:

using i = System.Int32;
...
Console.WriteLine(nameof(i)); // prints "i"

Or:

public static string Extension<T>(this T t)
{
    return nameof(T); returns "T"
}

One use I've been giving to it is for naming resources:

[Display(
    ResourceType = typeof(Resources),
    Name = nameof(Resources.Title_Name),
    ShortName = nameof(Resources.Title_ShortName),
    Description = nameof(Resources.Title_Description),
    Prompt = nameof(Resources.Title_Prompt))]

The fact is that, in this case, I didn't even need the generated properties to access the resources, but now I have a compile time check that the resources exist.

Excel: the Incredible Shrinking and Expanding Controls

Now using Excel 2013 and this happens EVERY time I extend my display while Excel is running (and every time I remove the extension).

The fix I've started implementing is using hyperlinks instead of buttons and one to open a userform with all the other activeX controls on.

map vs. hash_map in C++

I don't know what gives, but, hash_map takes more than 20 seconds to clear() 150K unsigned integer keys and float values. I am just running and reading someone else's code.

This is how it includes hash_map.

#include "StdAfx.h"
#include <hash_map>

I read this here https://bytes.com/topic/c/answers/570079-perfomance-clear-vs-swap

saying that clear() is order of O(N). That to me, is very strange, but, that's the way it is.

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

How can I split a string into segments of n characters?

Building on the previous answers to this question; the following function will split a string (str) n-number (size) of characters.

function chunk(str, size) {
    return str.match(new RegExp('.{1,' + size + '}', 'g'));
}

Demo

_x000D_
_x000D_
(function() {_x000D_
  function chunk(str, size) {_x000D_
    return str.match(new RegExp('.{1,' + size + '}', 'g'));_x000D_
  }_x000D_
  _x000D_
  var str = 'HELLO WORLD';_x000D_
  println('Simple binary representation:');_x000D_
  println(chunk(textToBin(str), 8).join('\n'));_x000D_
  println('\nNow for something crazy:');_x000D_
  println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join('  '));_x000D_
  _x000D_
  // Utiliy functions, you can ignore these._x000D_
  function textToBin(text) { return textToBase(text, 2, 8); }_x000D_
  function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); }_x000D_
  function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); }_x000D_
  function print(text) { document.getElementById('out').innerHTML += (text || ''); }_x000D_
  function println(text) { print((text || '') + '\n'); }_x000D_
  function repeat(chr, n) { return new Array(n + 1).join(chr); }_x000D_
  function textToBase(text, radix, n) {_x000D_
    return text.split('').reduce(function(result, chr) {_x000D_
      return result + pad(chr.charCodeAt(0).toString(radix), n, '0');_x000D_
    }, '');_x000D_
  }_x000D_
  function roundUp(numToRound, multiple) { _x000D_
    if (multiple === 0) return numToRound;_x000D_
    var remainder = numToRound % multiple;_x000D_
    return remainder === 0 ? numToRound : numToRound + multiple - remainder;_x000D_
  }_x000D_
}());
_x000D_
#out {_x000D_
  white-space: pre;_x000D_
  font-size: 0.8em;_x000D_
}
_x000D_
<div id="out"></div>
_x000D_
_x000D_
_x000D_