Programs & Examples On #Tabpage

Check if a specific tab page is selected (active)

To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}

This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

Activate tabpage of TabControl

For Windows Smart device (compact frame work ) (MC75-Motorola devices)

     mytabControl.SelectedIndex = 1

How to hide TabPage from TabControl

I combined the answer from @Jack Griffin and the one from @amazedsaint (the dotnetspider code snippet respectively) into a single TabControlHelper.

The TabControlHelper lets you:

  • Show / Hide all tab pages
  • Show / Hide single tab pages
  • Keep the original position of the tab pages
  • Swap tab pages

public class TabControlHelper
{
    private TabControl _tabControl;
    private List<KeyValuePair<TabPage, int>> _pagesIndexed;
    public TabControlHelper(TabControl tabControl)
    {
        _tabControl = tabControl;
        _pagesIndexed = new List<KeyValuePair<TabPage, int>>();

        for (int i = 0; i < tabControl.TabPages.Count; i++)
        {
            _pagesIndexed.Add(new KeyValuePair<TabPage, int> (tabControl.TabPages[i], i ));
        }
    }

    public void HideAllPages()
    {
        for (int i = 0; i < _pagesIndexed.Count; i++)
        {
            _tabControl.TabPages.Remove(_pagesIndexed[i].Key);
        }
    }

    public void ShowAllPages()
    {
        for (int i = 0; i < _pagesIndexed.Count; i++)
        {
            _tabControl.TabPages.Add(_pagesIndexed[i].Key);
        }
    }

    public void HidePage(TabPage tabpage)
    {
        if (!_tabControl.TabPages.Contains(tabpage)) return;
        _tabControl.TabPages.Remove(tabpage);
    }

    public void ShowPage(TabPage tabpage)
    {
        if (_tabControl.TabPages.Contains(tabpage)) return;
        InsertTabPage(GetTabPage(tabpage).Key, GetTabPage(tabpage).Value);
    }

    private void InsertTabPage(TabPage tabpage, int index)
    {
        if (index < 0 || index > _tabControl.TabCount)
            throw new ArgumentException("Index out of Range.");
        _tabControl.TabPages.Add(tabpage);
        if (index < _tabControl.TabCount - 1)
            do
            {
                SwapTabPages(tabpage, (_tabControl.TabPages[_tabControl.TabPages.IndexOf(tabpage) - 1]));
            }
            while (_tabControl.TabPages.IndexOf(tabpage) != index);
        _tabControl.SelectedTab = tabpage;
    }

    private void SwapTabPages(TabPage tabpage1, TabPage tabpage2)
    {
        if (_tabControl.TabPages.Contains(tabpage1) == false || _tabControl.TabPages.Contains(tabpage2) == false)
            throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

        int Index1 = _tabControl.TabPages.IndexOf(tabpage1);
        int Index2 = _tabControl.TabPages.IndexOf(tabpage2);
        _tabControl.TabPages[Index1] = tabpage2;
        _tabControl.TabPages[Index2] = tabpage1;
    }

    private KeyValuePair<TabPage, int> GetTabPage(TabPage tabpage)
    {
        return _pagesIndexed.Where(p => p.Key == tabpage).First();
    }
}

Can't Load URL: The domain of this URL isn't included in the app's domains

Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.

I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.

Hiding and Showing TabPages in tabControl

Someone merged the C# answer into this one so I have to post my answer here. I didn't love the other solutions so I made a helper class that will make it easier to hide / show your tabs while retaining the order of tabs.

/// <summary>
/// Memorizes the order of tabs upon creation to make hiding / showing tabs more
/// straightforward. Instead of interacting with the TabCollection, use this class
/// instead.
/// </summary>
public class TabPageHelper
{
    private List<TabPage> _allTabs;
    private TabControl.TabPageCollection _tabCollection;
    public Dictionary<string, int> TabOrder { get; private set; }

    public TabPageHelper( TabControl.TabPageCollection tabCollection )
    {
        _allTabs = new List<TabPage>();
        TabOrder = new Dictionary<string, int>();
        foreach ( TabPage tab in tabCollection )
        {
            _allTabs.Add( tab );
        }
        _tabCollection = tabCollection;
        foreach ( int index in Enumerable.Range( 0, tabCollection.Count ) )
        {
            var tab = tabCollection[index];
            TabOrder[tab.Name] = index;
        }
    }

    public void ShowTabPage( string tabText )
    {
        TabPage page = _allTabs
            .Where( t => string.Equals( t.Text, tabText, StringComparison.CurrentCultureIgnoreCase ) )
            .First();
        int tabPageOrder = TabOrder[page.Name];
        if ( !_tabCollection.Contains( page ) )
        {
            _tabCollection.Insert( tabPageOrder, page );
        }
    }

    public void HideTabPage( string tabText )
    {
        TabPage page = _allTabs
            .Where( t => string.Equals( t.Text, tabText, StringComparison.CurrentCultureIgnoreCase ) )
            .First();
        int tabPageOrder = TabOrder[page.Name];
        if ( _tabCollection.Contains( page ) )
        {
            _tabCollection.Remove( page );
        }
    }
}

To use the class, instantiate it in your form load method after initializing your components by passing in the tab control's TabPages property.

public Form1()
{
    InitializeComponent();
    _tabHelper = new TabPageHelper( tabControl1.TabPages );
}

All of your tab pages should exist on application load (ie: in the Design view) because the class will remember the order of the tab pages when hiding / showing. You can hide or show them selectively throughout your application like this:

_tabHelper.HideTabPage("Settings");
_tabHelper.ShowTabPage("Schedule");

Passing string parameter in JavaScript function

Change your code to

document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")

Multi-dimensional associative arrays in JavaScript

Javascript is flexible:

var arr = {
  "fred": {"apple": 2, "orange": 4},
  "mary": {}
  //etc, etc
};

alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
    alert(key + ": " + arr.fred[key]);

How to get a list of installed Jenkins plugins with name and version pair

I think these are not good enough answer(s)... many involve a couple of extra under-the-hood steps. Here's how I did it.

sudo apt-get install jq

...because the JSON output needs to be consumed after you call the API.

#!/bin/bash
server_addr = 'jenkins'
server_port = '8080'

curl -s -k "http://${server_addr}:${server_port}/pluginManager/api/json?depth=1" \
  | jq '.plugins[]|{shortName, version,longName,url}' -c | sort \
  > plugin-list

echo "dude, here's your list: "
cat plugin-list

How to insert an item into an array at a specific index (JavaScript)?

Immutable insertion

Using splice method is surely the best answer if you need to insert into an array in-place.

However, if you are looking for an immutable function that returns a new updated array instead of mutating the original array on insert, you can use the following function.

_x000D_
_x000D_
function insert(array, index) {
  const items = Array.prototype.slice.call(arguments, 2);

  return [].concat(array.slice(0, index), items, array.slice(index));
}

const list = ['one', 'two', 'three'];

const list1 = insert(list, 0, 'zero'); // Insert single item
const list2 = insert(list, 3, 'four', 'five', 'six'); // Insert multiple


console.log('Original list: ', list);
console.log('Inserted list1: ', list1);
console.log('Inserted list2: ', list2);
_x000D_
_x000D_
_x000D_

Note: This is a pre-ES2015 way of doing it so it works for both older and newer browsers.

If you're using ES6 then you can try out rest parameters too; see this answer.

How do you get the current time of day?

Get the current date and time, then just use the time portion of it. Look at the possibilities for formatting a date time string in the MSDN docs.

Substring in excel

kennytm's links are dead and he doesn't provide an example so here's how you do substrings:

=MID(text, start_num, char_num)

Let's say cell A1 is Hello.

=MID(A1, 2, 3) 

Would return

ell

Because it says to start at character 2, e, and to return 3 characters.

excel VBA run macro automatically whenever a cell is changed

In an attempt to spot a change somewhere in a particular column (here in "W", i.e. "23"), I modified Peter Alberts' answer to:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Target.Column = 23 Then Exit Sub
    Application.EnableEvents = False             'to prevent endless loop
    On Error GoTo Finalize                       'to re-enable the events
    MsgBox "You changed a cell in column W, row " & Target.Row
    MsgBox "You changed it to: " & Target.Value
Finalize:
    Application.EnableEvents = True
End Sub

Razor MVC Populating Javascript array with Model Array

To expand on the top-voted answer, for reference, if the you want to add more complex items to the array:

@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");

etc.

Furthermore, if you want to pass the array as a parameter to your controller, you can stringify it first:

myArray = JSON.stringify({ 'myArray': myArray });

LaTeX Optional Arguments

The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar is quite useful for such things.

The best answer for your question is to use the new xparse package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.

In your example you have a \sec macro that either takes one or two braced arguments. This would be implemented using xparse with the following:

\documentclass{article}
\usepackage{xparse}
\begin{document}
\DeclareDocumentCommand\sec{ m g }{%
    {#1%
        \IfNoValueF {#2} { and #2}%
    }%
}
(\sec{Hello})
(\sec{Hello}{Hi})
\end{document}

The argument { m g } defines the arguments of \sec; m means "mandatory argument" and g is "optional braced argument". \IfNoValue(T)(F) can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.

Set background color in PHP?

You must use CSS. Can't be done with PHP.

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

Adding to Nils Kaspersson's solution, I am resolving for the width of the vertical scrollbar as well. I am using 16px as an example, which is subtracted from the view-port width. This will avoid the horizontal scrollbar from appearing.

width: calc(100vw - 16px);
left: calc(-1 * (((100vw - 16px) - 100%) / 2));

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

What does the 'export' command do?

export in sh and related shells (such as bash), marks an environment variable to be exported to child-processes, so that the child inherits them.

export is defined in POSIX:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Node.js - use of module.exports as a constructor

At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.

This way actually you are creating a new function, as we created using JS on Web Browser environment for example.

Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor

Laravel Eloquent get results grouped by days

I built a laravel package for making statistics : https://github.com/Ifnot/statistics

It is based on eloquent, carbon and indicators so it is really easy to use. It may be usefull for extracting date grouped indicators.

$statistics = Statistics::of(MyModel::query());

$statistics->date('validated_at');

$statistics->interval(Interval::$DAILY, Carbon::createFromFormat('Y-m-d', '2016-01-01'), Carbon::now())

$statistics->indicator('total', function($row) {
    return $row->counter;
});

$data = $statistics->make();

echo $data['2016-01-01']->total;

```

How to set a ripple effect on textview or imageview on Android?

You can use android-ripple-background

Start Effect

final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.content);
ImageView imageView=(ImageView)findViewById(R.id.centerImage);
imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        rippleBackground.startRippleAnimation();
    }
});

Stop animation:

rippleBackground.stopRippleAnimation();

For KOTLIN

val rippleBackground = findViewById(R.id.content) as RippleBackground
val imageView: ImageView = findViewById(R.id.centerImage) as ImageView
imageView.setOnClickListener(object : OnClickListener() {
    fun onClick(view: View?) {
        rippleBackground.startRippleAnimation()
    }
})

Get index of a key/value pair in a C# dictionary based on the value

    You can find index by key/values in dictionary
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
myDictionary.Add("a", "x");
myDictionary.Add("b", "y");
int i = Array.IndexOf(myDictionary.Keys.ToArray(), "a");
int j = Array.IndexOf(myDictionary.Values.ToArray(), "y");

What is a mixin, and why are they useful?

Maybe an example from ruby can help:

You can include the mixin Comparable and define one function "<=>(other)", the mixin provides all those functions:

<(other)
>(other)
==(other)
<=(other)
>=(other)
between?(other)

It does this by invoking <=>(other) and giving back the right result.

"instance <=> other" returns 0 if both objects are equal, less than 0 if instance is bigger than other and more than 0 if other is bigger.

Difference between logical addresses, and physical addresses?

logical address is address relative to program. It tells how much memory a particular process will take, not tell what will the exact location of the process and this exact location will we generated by using some mapping, and is known as physical address.

Get a list of all the files in a directory (recursive)

Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:

import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };

See also [1] for more examples.

[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html

Routing with multiple Get methods in ASP.NET Web API

Also you will specify route on action for set route

[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
   //gets all customer logic
}

[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
     //gets some customer 
}

[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
  //gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
    //gets customer by its username
}

IntelliJ - show where errors are

Do you have a yellow icon like this [_] at the bottom of the main window? It is a "type-aware highlighting" switch which could be disabled accidentally. You should re-enable it by clicking on the icon.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How to write dynamic variable in Ansible playbook

I am sure there is a smarter way for doing what you want but this should work:

- name         : Test var
  hosts        : all
  gather_facts : no
  vars:
    myvariable : false
  tasks:
    - name: param1
      set_fact:
        myvariable: "{{param1}}"
      when: param1 is defined

    - name: param2
      set_fact:
        myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
      when: param2 is defined

    - name: param3
      set_fact:
        myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
      when: param3 is defined

    - name: default
      set_fact:
        myvariable: "default"
      when: not myvariable

    - debug:
       var=myvariable

Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

Checking version of angular-cli that's installed?

Execute:

ng v

or

ng --version

tell you the current angular cli version number

enter image description here

How to delete all data from solr and hbase

I've used this query to delete all my records.

http://host/solr/core-name/update?stream.body=%3Cdelete%3E%3Cquery%3E*:*%3C/query%3E%3C/delete%3E&commit=true

What's the difference between window.location and document.location in JavaScript?

As far as I know, Both are same. For cross browser safety you can use window.location rather than document.location.

All modern browsers map document.location to window.location, but I still prefer window.location as that's what I've used since I wrote my first web page. it is more consistent.

you can also see document.location === window.location returns true, which clarifies that both are same.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

When I tried to select the development provisioning profile in Code Signing Identity is would say "profile doesn't match any valid certificate". So when I followed the two step process below it worked:

1) Under "Code Signing Identity" for Development change to "Don't Code Sign".
2) Then Under "Code Signing Identity" for Development you will be able to select your provisioning profile for Development.

Drove me nuts, but stumbled upon the solution.

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

Non-invocable member cannot be used like a method?

I had the same issue and realized that removing the parentheses worked. Sometimes having someone else read your code can be useful if you have been the only one working on it for some time.

E.g.

  cmd.CommandType = CommandType.Text(); 

Replace: cmd.CommandType = CommandType.Text;

Android : How to set onClick event for Button in List item of ListView

I assume you have defined custom adapter for your ListView.

If this is the case then you can assign onClickListener for your button inside the custom adapter's getView() method.

RelativeLayout center vertical

use

 android:layout_centerVertical="true"

Text not wrapping in p tag

EASY

p{
    word-wrap: break-word;
}

How does one add keyboard languages and switch between them in Linux Mint 16?

Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout

Where is my m2 folder on Mac OS X Mavericks

On mac just run mvn clean install assuming maven has been installed and it will create .m2 automatically.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.

What does enctype='multipart/form-data' mean?

When you make a POST request, you have to encode the data that forms the body of the request in some way.

HTML forms provide three methods of encoding.

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain

Work was being done on adding application/json, but that has been abandoned.

(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)

The specifics of the formats don't matter to most developers. The important points are:

  • Never use text/plain.

When you are writing client-side code:

  • use multipart/form-data when your form includes any <input type="file"> elements
  • otherwise you can use multipart/form-data or application/x-www-form-urlencoded but application/x-www-form-urlencoded will be more efficient

When you are writing server-side code:

  • Use a prewritten form handling library

Most (such as Perl's CGI->param or the one exposed by PHP's $_POST superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.

Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).


If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.

application/x-www-form-urlencoded is more or less the same as a query string on the end of the URL.

multipart/form-data is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.

text/plain is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).

Git 'fatal: Unable to write new index file'

I had the same issue on a Mac. It seems to be caused by filesystem ACLs. Try chmod -RN /path/to/repo to clear the ACLs. After doing this I was able to commit changes. Using the trick to copy the index file, delete the original and move the copy back achieved the same result.

Count with IF condition in MySQL query

Use sum() in place of count()

Try below:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20 

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

Elevating process privilege programmatically?

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]

This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.

Set value of textarea in jQuery

I tried with .val() .text() .html() and had some bugs using jQuery to read or set value of a textarea... i endup using native js

$('#message').blur(function() {    
    if (this.value == '') { this.value = msg_greeting; }
});

ToggleButton in C# WinForms

How about this?

Assuming you have System.Windows.Forms referenced.

var cbtnToggler = new CheckBox();
cbtnToggler.Appearance = Appearance.Button;
cbtnToggler.TextAlign = ContentAlignment.MiddleCenter;
cbtnToggler.MinimumSize = new Size(75, 25); //To prevent shrinkage!

Hope this helps ;)

How to place div in top right hand corner of page

the style is:

<style type="text/css">
 .topcorner{
   position:absolute;
   top:0;
   right:0;
  }
</style>

hope it will work. Thanks

Using ping in c#

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation namespace contains a class called PingReply that has properties designed to translate the ICMP response and deliver useful information about the pinged server such as:

  • IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
  • IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
  • RoundtripTime (System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
  • PingOptions (System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.

The following is a simple example using WinForms to demonstrate how ping works in c#. By providing a valid IP address in textBox1 and clicking button1, we are creating an instance of the Ping class, a local variable PingReply, and a string to store the IP or URL address. We assign PingReply to the ping Send method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success status. Finally, we extract from PingReply the information we need to display for the user, which is described above.

    using System;
    using System.Net.NetworkInformation;
    using System.Windows.Forms;

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

            private void button1_Click(object sender, EventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s;
                s = textBox1.Text;
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                {
                    lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
                }
            }

            private void textBox1_Validated(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
                {
                    MessageBox.Show("Please use valid IP or web address!!");
                }
            }
        }
    }

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

Installing SetupTools on 64-bit Windows

You can find 64bit installers for a lot of libs here: http://www.lfd.uci.edu/~gohlke/pythonlibs/

How do I run two commands in one line in Windows CMD?

Yes there is. It's &.

&& will execute command 2 when command 1 is complete providing it didn't fail.

& will execute regardless.

How can I decrypt MySQL passwords

If a proper encryption method was used, it's not going to be possible to easily retrieve them.

Just reset them with new passwords.

Edit: The string looks like it is using PASSWORD():

UPDATE user SET password = PASSWORD("newpassword");

How do you add an ActionListener onto a JButton in Java

I don't know if this works but I made the variable names

public abstract class beep implements ActionListener {
    public static void main(String[] args) {
        JFrame f = new JFrame("beeper");
        JButton button = new JButton("Beep me");
        f.setVisible(true);
        f.setSize(300, 200);
        f.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Insert code here
            }
        });
    }
}

jQuery & CSS - Remove/Add display:none

jQuery provides you with:

$(".news").hide();
$(".news").show();

You can then easily show and hide the element(s).

Android Webview gives net::ERR_CACHE_MISS message

Android WebView fix ERR_CACHE_MISS error solution

you just need add one line code <uses-permission android:name="android.permission.INTERNET"/> in your app/src/main/AndroidManifest.xml file as below screenshots shows.

enter image description here

  1. before

enter image description here

  1. after

enter image description here

How to remove square brackets from list in Python?

if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Find number of decimal places in decimal value regardless of culture

string number = "123.456789"; // Convert to string
int length = number.Substring(number.IndexOf(".") + 1).Length;  // 6

How to use pip with Python 3.x alongside Python 2.x

In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:

pip install python2-module-name

pip3 install python3-module-name

That's all

Frame Buster Buster ... buster code needed

As of 2015, you should use CSP2's frame-ancestors directive for this. This is implemented via an HTTP response header.

e.g.

Content-Security-Policy: frame-ancestors 'none'

Of course, not many browsers support CSP2 yet so it is wise to include the old X-Frame-Options header:

X-Frame-Options: DENY

I would advise to include both anyway, otherwise your site would continue to be vulnerable to Clickjacking attacks in old browsers, and of course you would get undesirable framing even without malicious intent. Most browsers do update automatically these days, however you still tend to get corporate users being stuck on old versions of Internet Explorer for legacy application compatibility reasons.

How to convert Nonetype to int or string?

That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int or str, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.

offsetting an html anchor to adjust for fixed header

For the same issue, I used an easy solution : put a padding-top of 40px on each anchor.

clearInterval() not working

You're using clearInterval incorrectly.

This is the proper use:

Set the timer with

var_name = setInterval(fontChange, 500);

and then

clearInterval(var_name);

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

$("#images").load(location.href+" #images",function(){
    $.getScript("js/productHelper.js"); 
});

How to make fixed header table inside scrollable div?

use StickyTableHeaders.js for this.

Header was transparent . so try to add this css .

thead {
    border-top: none;
    border-bottom: none;
    background-color: #FFF;
}

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Git error: src refspec master does not match any error: failed to push some refs

It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.

To create a master branch:

git checkout -b master

And you can work off of that.

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

How do I use the Tensorboard callback of Keras?

You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback and then callback = LosswiseKerasCallback(tag='my fancy convnet 1') and you're good to go (see https://docs.losswise.com/#keras-plugin).

merge two object arrays with Angular 2 and TypeScript?

With angular 6 spread operator and concat not work. You can resolve it easy:

result.push(...data);

Difference between filter and filter_by in SQLAlchemy

filter_by uses keyword arguments, whereas filter allows pythonic filtering arguments like filter(User.name=="john")

VBA test if cell is in a range

Here is another option to see if a cell exists inside a range. In case you have issues with the Intersect solution as I did.

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr is a VBA function that checks if a string exists within another string.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

How to display loading message when an iFrame is loading?

I think that this code is going to help:

JS:

$('#foo').ready(function () {
    $('#loadingMessage').css('display', 'none');
});
$('#foo').load(function () {
    $('#loadingMessage').css('display', 'none');
});

HTML:

<iframe src="http://google.com/" id="foo"></iframe>
<div id="loadingMessage">Loading...</div>

CSS:

#loadingMessage {
    width: 100%;
    height: 100%;
    z-index: 1000;
    background: #ccc;
    top: 0px;
    left: 0px;
    position: absolute;
}

Wait until boolean value changes it state

You need a mechanism which avoids busy-waiting. The old wait/notify mechanism is fraught with pitfalls so prefer something from the java.util.concurrent library, for example the CountDownLatch:

public final CountDownLatch latch = new CountDownLatch(1);

public void run () {
  latch.await();
  ...
}

And at the other side call

yourRunnableObj.latch.countDown();

However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService to which you submit as a task the work which must be done when the condition is met.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

Breadth First Search is generally the best approach when the depth of the tree can vary, and you only need to search part of the tree for a solution. For example, finding the shortest path from a starting value to a final value is a good place to use BFS.

Depth First Search is commonly used when you need to search the entire tree. It's easier to implement (using recursion) than BFS, and requires less state: While BFS requires you store the entire 'frontier', DFS only requires you store the list of parent nodes of the current element.

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx (as noted already by @jewelsea above)

/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

Where does Git store files?

In the root directory of the project there is a hidden .git directory that contains configuration, the repository etc.

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

Can angularjs routes have optional parameter values?

Actually I think OZ_ may be somewhat correct.

If you have the route '/users/:userId' and navigate to '/users/' (note the trailing /), $routeParams in your controller should be an object containing userId: "" in 1.1.5. So no the paramater userId isn't completely ignored, but I think it's the best you're going to get.

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

try
{
   ...
}
catch (Exception e)
{
   if (e instanceof FooException)
     throw e;
}

Add item to Listview control

Simple one, just do like this..

ListViewItem lvi = new ListViewItem(pet.Name);
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);
    listView.Items.Add(lvi);

vbscript output to console

Create a .vbs with the following code, which will open your main .vbs:

Set objShell = WScript.CreateObject("WScript.shell") 
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""

Here is my main .vbs

Option Explicit
Dim i
for i = 1 To 5
     Wscript.Echo i
     Wscript.Sleep 5000
Next

Is it possible to start a shell session in a running container (without ssh)

Keep an eye on this pull request: https://github.com/docker/docker/pull/7409

Which implements the forthcoming docker exec <container_id> <command> utility. When this is available it should be possible to e.g. start and stop the ssh service inside a running container.

There is also nsinit to do this: "nsinit provides a handy way to access a shell inside a running container's namespace", but it looks difficult to get running. https://gist.github.com/ubergarm/ed42ebbea293350c30a6

Pandas: Looking up the list of sheets in an excel file

from openpyxl import load_workbook

sheets = load_workbook(excel_file, read_only=True).sheetnames

For a 5MB Excel file I'm working with, load_workbook without the read_only flag took 8.24s. With the read_only flag it only took 39.6 ms. If you still want to use an Excel library and not drop to an xml solution, that's much faster than the methods that parse the whole file.

jQuery: Best practice to populate drop down?

$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
                document.getElementById("select1").options[i+1] = new Option(sary[i]);
                document.getElementById("select1").options[i+1].value = sary[i];
            }
            });

Chrome desktop notification example

I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.

Probably on Opera, IE and Edge as well but I haven't tested it yet.

Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.

Get it on Bower

$ bower install js-notify

This is how it works:

notify('title', {
    body: 'Notification Text',
    icon: 'path/to/image.png',
    onclick: function(e) {}, // e -> Notification object
    onclose: function(e) {},
    ondenied: function(e) {}
  });

You have to set the title but the json object as the second argument is optional.

Two div blocks on same line

You can use a HTML table:

<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>   

How to scale a UIImageView proportionally?

This works fine for me Swift 2.x:

imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true;

Manually install Gradle and use it in Android Studio

I'm not sure why there are so many contorted descriptions of doing this. Perhaps because Android Studio (AS) is constantly changing/evolving? Nevertheless, the procedure is this simple.

Assuming you have already installed Gradle in a suitable directory, mean that you probably also defined an environment variable for GRADLE_HOME, if not define it now, and restart AS.

For my example: GRADLE_HOME=C:\Gradle\gradle-5.2.1

Then fire up AS and navigate to:
File > Settings > Build, Execution, Deployment > Gradle

Now, all you need to do is to select: (o) Use local gradle distribution. AS will then tell you it found your local Gradle paths:

enter image description here

Hit Apply and Ok and restart AS.

Now all the Gradle data can be found in your HOME directory, usually located here (in this case on Windows):

# tree -L 2 $USERPROFILE/.gradle/ | tail -n +2

+-- build-scan-data
¦   +-- 2.1
¦   +-- 2.2.1
+-- caches
¦   +-- 3.5
¦   +-- 5.2.1
¦   +-- jars-3
¦   +-- journal-1
¦   +-- modules-2
¦   +-- transforms-1
¦   +-- transforms-2
¦   +-- user-id.txt
¦   +-- user-id.txt.lock
+-- daemon
¦   +-- 3.5
¦   +-- 5.2.1
+-- native
¦   +-- 25
¦   +-- 28
¦   +-- jansi
+-- notifications
¦   +-- 5.2.1
+-- workers
+-- wrapper
    +-- dists

Tested on latest AS 3.3.2

What static analysis tools are available for C#?

Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).

It provides the following capabilities:

  • Software Architecture Visualization (inlcuding dependencies)
  • Enforcement of architectural rules e.g. layering, subsystems, calling rules
  • Clone Detection - highlighting copy and pasted (and modified code)
  • Dead Code Detection
  • Cycle Detection
  • Software Metrics
  • Code Style Checks

These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

How to catch and print the full exception traceback without halting/exiting the program?

python 3 solution

stacktrace_helper.py:

from linecache import getline
import sys
import traceback


def get_stack_trace():
    exc_type, exc_value, exc_tb = sys.exc_info()
    trace = traceback.format_stack()
    trace = list(filter(lambda x: ("\\lib\\" not in x and "/lib/" not in x and "stacktrace_helper.py" not in x), trace))
    ex_type = exc_type.__name__
    ex_line = exc_tb.tb_lineno
    ex_file = exc_tb.tb_frame.f_code.co_filename
    ex_message = str(exc_value)
    line_code = ""
    try:
        line_code = getline(ex_file, ex_line).strip()
    except:
        pass

    trace.insert(
        0, f'File "{ex_file}", line {ex_line}, line_code: {line_code} , ex: {ex_type} {ex_message}',
    )
    return trace


def get_stack_trace_str(msg: str = ""):
    trace = list(get_stack_trace())
    trace_str = "\n".join(list(map(str, trace)))
    trace_str = msg + "\n" + trace_str
    return trace_str

How to dynamically change a web page's title?

You'll have to re-serve the page with a new title in order for any crawlers to notice the change. Doing it via javascript will only benefit a human reader, crawlers are not going to execute that code.

'do...while' vs. 'while'

while loops check the condition before the loop, do...while loops check the condition after the loop. This is useful is you want to base the condition on side effects from the loop running or, like other posters said, if you want the loop to run at least once.

I understand where you're coming from, but the do-while is something that most use rarely, and I've never used myself. You're not doing it wrong.

You're not doing it wrong. That's like saying someone is doing it wrong because they've never used the byte primitive. It's just not that commonly used.

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

C# Enum - How to Compare Value

You should convert the string to an enumeration value before comparing.

Enum.TryParse("Retailer", out AccountType accountType);

Then

if (userProfile?.AccountType == accountType)
{
    //your code
}

How to center a (background) image within a div?

This works for me:

.network-connections-icon {
  background-image: url(url);
  background-size: 100%;
  width: 56px;
  height: 56px;
  margin: 0 auto;
}

Detect if page has finished loading

there are two ways to do this in jquery depending what you are looking for..

using jquery you can do

  • //this will wait for the text assets to be loaded before calling this (the dom.. css.. js)

    $(document).ready(function(){...});
    
  • //this will wait for all the images and text assets to finish loading before executing

    $(window).load(function(){...});
    

Custom Python list sorting

It's documented here.

The sort() method takes optional arguments for controlling the comparisons.

cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

Select distinct values from a large DataTable column

dt- your data table name

ColumnName- your columnname i.e id

DataView view = new DataView(dt);
DataTable distinctValues = new DataTable();
distinctValues = view.ToTable(true, ColumnName);

How to uncheck a radio button?

Use this

$("input[name='nameOfYourRadioButton']").attr("checked", false);

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value

Suppress/ print without b' prefix for bytes in Python 3

I am a little late but for Python 3.9.1 this worked for me and removed the -b prefix:

print(outputCode.decode())

Resetting a form in Angular 2 after submit

Now NgForm supports two methods: .reset() vs .resetForm() the latter also changes the submit state of the form to false reverting form and its controls to initial states.

How to create a Rectangle object in Java using g.fillRect method

You may try like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {
    g.drawRect (x, y, width, height);    //can use either of the two//
    g.fillRect (x, y, width, height);
    g.setColor(color);
  }

}

where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue

if you want to use rectangle object you could do it like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {    
    Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
    g.setColor(color);
  }
}       

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).

An example of a FIRST/FIRST conflict:

S -> Xb | Yc
X -> a 
Y -> a 

By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.

An example of a FIRST/FOLLOW conflict:

S -> AB 
A -> fe | epsilon 
B -> fg 

By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).

Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.

Check if a file is executable

Testing files, directories and symlinks

The solutions given here fail on either directories or symlinks (or both). On Linux, you can test files, directories and symlinks with:

if [[ -f "$file" && -x $(realpath "$file") ]]; then .... fi

On OS X, you should be able to install coreutils with homebrew and use grealpath.

Defining an isexec function

You can define a function for convenience:

isexec() {
    if [[ -f "$1" && -x $(realpath "$1") ]]; then
        true;
    else
        false;
    fi;
}

Or simply

isexec() { [[ -f "$1" && -x $(realpath "$1") ]]; }

Then you can test using:

if `isexec "$file"`; then ... fi

100% Min Height CSS layout

just share what i've been used, and works nicely

#content{
        height: auto;
        min-height:350px;
}

Is it possible to capture the stdout from the sh DSL command in the pipeline

Try this:

def get_git_sha(git_dir='') {
    dir(git_dir) {
        return sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
    }
}

node(BUILD_NODE) {
    ...
    repo_SHA = get_git_sha('src/FooBar.git')
    echo repo_SHA
    ...
}

Tested on:

  • Jenkins ver. 2.19.1
  • Pipeline 2.4

How to use sed to replace only the first occurrence in a file?

A possible solution here might be to tell the compiler to include the header without it being mentioned in the source files. IN GCC there are these options:

   -include file
       Process file as if "#include "file"" appeared as the first line of
       the primary source file.  However, the first directory searched for
       file is the preprocessor's working directory instead of the
       directory containing the main source file.  If not found there, it
       is searched for in the remainder of the "#include "..."" search
       chain as normal.

       If multiple -include options are given, the files are included in
       the order they appear on the command line.

   -imacros file
       Exactly like -include, except that any output produced by scanning
       file is thrown away.  Macros it defines remain defined.  This
       allows you to acquire all the macros from a header without also
       processing its declarations.

       All files specified by -imacros are processed before all files
       specified by -include.

Microsoft's compiler has the /FI (forced include) option.

This feature can be handy for some common header, like platform configuration. The Linux kernel's Makefile uses -include for this.

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

scp with port number specified

for use another port on scp command use capital P like this

scp -P port-number source-file/directory user@domain:/destination

ya ali

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.=

To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L

LPCWSTR a = L"TestWindow";

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

How to get a list of column names on Sqlite3 database?

Maybe you just want to print the table headers on the console. This is my code: (for each table)

    // ------------------ show header ----------------


    char sqlite_stmt_showHeader[1000];
    snprintf(sqlite_stmt_showHeader, 1000, "%s%s", "SELECT * FROM ", TABLE_NAME_STRING UTF8String]);

    sqlite3_stmt* statement_showHeader;
    sqlite3_prepare_v2(DATABASE, sqlite_stmt_showHeader, -1, &statement_showHeader, NULL);

    int headerColumnSize = sqlite3_column_count(statement_showHeader);

    NSString* headerRow = @"|";

    for (int j = 0; j < headerColumnSize; j++) {
        NSString* headerColumnContent = [[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_name(statement_showHeader, j)];
        headerRow = [[NSString alloc] initWithFormat:@"%@ %@ |", headerRow, headerColumnContent];
    }

    NSLog(@"%@", headerRow);


    sqlite3_finalize(statement_showHeader);

    // ---------------- show header end ---------------------

PowerShell Script to Find and Replace for all Files with a Specific Extension

PowerShell is a good choice ;) It is very easy to enumerate files in given directory, read them and process.

The script could look like this:

Get-ChildItem C:\Projects *.config -recurse |
    Foreach-Object {
        $c = ($_ | Get-Content) 
        $c = $c -replace '<add key="Environment" value="Dev"/>','<add key="Environment" value="Demo"/>'
        [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
    }

I split the code to more lines to be readable for you. Note that you could use Set-Content instead of [IO.File]::WriteAllText, but it adds new line at the end. With WriteAllText you can avoid it.

Otherwise the code could look like this: $c | Set-Content $_.FullName.

JAX-WS client : what's the correct path to access the local WSDL?

For those of you using Spring, you can simply reference any classpath-resource using the classpath-protocol. So in case of the wsdlLocation, this becomes:

<wsdlLocation>classpath:META-INF/webservice.wsdl</wsdlLocation>

Note that is not standard Java behavior. See also: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html

How to copy to clipboard using Access/VBA?

I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm

Which works nicely. :)

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

Check if certain value is contained in a dataframe column in pandas

You can use any:

print any(df.column == 07311954)
True       #true if it contains the number, false otherwise

If you rather want to see how many times '07311954' occurs in a column you can use:

df.column[df.column == 07311954].count()

How to flush output after each `echo` call?

Anti-virus software may also be interfering with output flushing. In my case, Kaspersky Anti-Virus 2013 was holding data chunks before sending it to the browser, even though I was using an accepted solution.

Duplicate AssemblyVersion Attribute

I had the same error and it was underlining the Assembly Vesrion and Assembly File Version so reading Luqi answer I just added them as comments and the error was solved

// AssemblyVersion is the CLR version. Change this only when making breaking    changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]

UIView bottom border?

Swift 4 extension with border width and color. Works great!

@IBDesignable
final class SideBorders: UIView {
@IBInspectable var topColor: UIColor = UIColor.clear
@IBInspectable var topWidth: CGFloat = 0

@IBInspectable var rightColor: UIColor = UIColor.clear
@IBInspectable var rightWidth: CGFloat = 0

@IBInspectable var bottomColor: UIColor = UIColor.clear
@IBInspectable var bottomWidth: CGFloat = 0

@IBInspectable var leftColor: UIColor = UIColor.clear
@IBInspectable var leftWidth: CGFloat = 0

override func draw(_ rect: CGRect) {
    let topBorder = CALayer()
    topBorder.backgroundColor = topColor.cgColor
    topBorder.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: topWidth)
    self.layer.addSublayer(topBorder)

    let rightBorder = CALayer()
    rightBorder.backgroundColor = rightColor.cgColor
    rightBorder.frame = CGRect(x: self.frame.size.width - rightWidth, y: 0, width: rightWidth, height: self.frame.size.height)
    self.layer.addSublayer(rightBorder)

    let bottomBorder = CALayer()
    bottomBorder.backgroundColor = bottomColor.cgColor
    bottomBorder.frame = CGRect(x: 0, y: self.frame.size.height - bottomWidth, width: self.frame.size.width, height: bottomWidth)
    self.layer.addSublayer(bottomBorder)

    let leftBorder = CALayer()
    leftBorder.backgroundColor = leftColor.cgColor
    leftBorder.frame = CGRect(x: 0, y: self.frame.size.height - leftWidth, width: self.frame.size.width, height: leftWidth)
    self.layer.addSublayer(leftBorder)
}

}

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

How to send email attachments?

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

msg = MIMEMultipart()
msg.attach(MIMEText(file("text.txt").read()))
msg.attach(MIMEImage(file("image.png").read()))

# to send
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

Adapted from here.

How to show empty data message in Datatables

This is a just a nice idea. that, you can Add class in body, and hide/show table while there is no data in table. This works perfect for me. You can design custom NO Record Found error message when there is no record in table, you can add class "no-record", and when there is 1 or more than one record, you can remove class and show datatable

Here is jQuery code.

$('#default_table').DataTable({

    // your stuff here

    "fnFooterCallback": function (nRow, aaData, iStart, iEnd, aiDisplay) {
        if (aiDisplay.length > 0) {
            $('body').removeClass('no-record');
        }
        else {
            $('body').addClass('no-record');
        }
    }
});

Here is CSS

.no-record #default_table{display:none;}

and here is Official link.

How to use the read command in Bash?

Do you need the pipe?

echo -ne "$MENU"
read NUMBER

How to remove padding around buttons in Android?

That's not padding, it's the shadow around the button in its background drawable. Create your own background and it will disappear.

Rebuild all indexes in a Database

Try the following script:

Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO

Also

I prefer(After a long search) to use the following script, it contains @fillfactor determines how much percentage of the space on each leaf-level page is filled with data.

DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80 
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO

for more info, check the following link:

https://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:

SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc

For more information, Check the following link:

http://www.schneider-electric.com/en/faqs/FA234246/

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

How to load URL in UIWebView in Swift?

import UIKit

class ViewController: UIViewController{

@IBOutlet weak var webView: UIWebView!



override func viewDidLoad() {
   super.viewDidLoad()
       //Func Gose Here 
      loadUrl()

   } 
 func loadUrl(){

   let url = URL(string: "Url which you want to load(www.google.com)")
   let requestObj = URLRequest(url: url! as URL)
   webView.load(requestObj)
 }

}

Convert a number range to another range, maintaining ratio

Short-cut/simplified proposal

 NewRange/OldRange = Handy multiplicand or HM
 Convert OldValue in OldRange to NewValue in NewRange = 
 (OldValue - OldMin x HM) + NewMin

wayne

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

Delete from two tables in one query

You can also use like this, to delete particular value when both the columns having 2 or many of same column name.

DELETE project , create_test  FROM project INNER JOIN create_test
WHERE project.project_name='Trail' and  create_test.project_name ='Trail' and project.uid= create_test.uid = '1';

Is there a way to detach matplotlib plots so that the computation can continue?

Well, I had great trouble figuring out the non-blocking commands... But finally, I managed to rework the "Cookbook/Matplotlib/Animations - Animating selected plot elements" example, so it works with threads (and passes data between threads either via global variables, or through a multiprocess Pipe) on Python 2.6.5 on Ubuntu 10.04.

The script can be found here: Animating_selected_plot_elements-thread.py - otherwise pasted below (with fewer comments) for reference:

import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
import pylab as p
import numpy as nx 
import time

import threading 



ax = p.subplot(111)
canvas = ax.figure.canvas

# for profiling
tstart = time.time()

# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)

# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)


# just a plain global var to pass data (from main, to plot update thread)
global mypass

# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()


# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
# parallel with gobject.idle_add(update_line)
def threadMainTest():
    global mypass
    global runthread
    global pipe1main

    print "tt"

    interncount = 1

    while runthread: 
        mypass += 1
        if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
            interncount *= 1.03
        pipe1main.send(interncount)
        time.sleep(0.01)
    return


# main plot / GUI update
def update_line(*args):
    global mypass
    global t0
    global runthread
    global pipe1upd

    if not runthread:
        return False 

    if pipe1upd.poll(): # check first if there is anything to receive
        myinterncount = pipe1upd.recv()

    update_line.cnt = mypass

    # restore the clean slate background
    canvas.restore_region(background)
    # update the data
    line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
    # just draw the animated artist
    ax.draw_artist(line)
    # just redraw the axes rectangle
    canvas.blit(ax.bbox)

    if update_line.cnt>=500:
        # print the timing info and quit
        print 'FPS:' , update_line.cnt/(time.time()-tstart)

        runthread=0
        t0.join(1)   
        print "exiting"
        sys.exit(0)

    return True



global runthread

update_line.cnt = 0
mypass = 0

runthread=1

gobject.idle_add(update_line)

global t0
t0 = threading.Thread(target=threadMainTest)
t0.start() 

# start the graphics update thread
p.show()

print "out" # will never print - show() blocks indefinitely! 

Hope this helps someone,
Cheers!

Thread pooling in C++11

Edit: This now requires C++17 and concepts. (As of 9/12/16, only g++ 6.0+ is sufficient.)

The template deduction is a lot more accurate because of it, though, so it's worth the effort of getting a newer compiler. I've not yet found a function that requires explicit template arguments.

It also now takes any appropriate callable object (and is still statically typesafe!!!).

It also now includes an optional green threading priority thread pool using the same API. This class is POSIX only, though. It uses the ucontext_t API for userspace task switching.


I created a simple library for this. An example of usage is given below. (I'm answering this because it was one of the things I found before I decided it was necessary to write it myself.)

bool is_prime(int n){
  // Determine if n is prime.
}

int main(){
  thread_pool pool(8); // 8 threads

  list<future<bool>> results;
  for(int n = 2;n < 10000;n++){
    // Submit a job to the pool.
    results.emplace_back(pool.async(is_prime, n));
  }

  int n = 2;
  for(auto i = results.begin();i != results.end();i++, n++){
    // i is an iterator pointing to a future representing the result of is_prime(n)
    cout << n << " ";
    bool prime = i->get(); // Wait for the task is_prime(n) to finish and get the result.
    if(prime)
      cout << "is prime";
    else
      cout << "is not prime";
    cout << endl;
  }  
}

You can pass async any function with any (or void) return value and any (or no) arguments and it will return a corresponding std::future. To get the result (or just wait until a task has completed) you call get() on the future.

Here's the github: https://github.com/Tyler-Hardin/thread_pool.

Best way in asp.net to force https for an entire site?

The IIS7 module will let you redirect.

    <rewrite>
        <rules>
            <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
                <match url="(.*)"/>
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$"/>
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>
            </rule>
        </rules>
    </rewrite>

How to read and write INI file with Python3?

contents in my backup_settings.ini file

[Settings]
year = 2020

python code for reading

import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year") 
print(year)

for writing or updating

from pathlib import Path
import configparser
myfile = Path('backup_settings.ini')  #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry 
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))

output

[Settings]
year = 2050
day = sunday

AngularJS view not updating on model change

Do not use $scope.$apply() angular already uses it and it can result in this error

$rootScope:inprog Action Already In Progress

if you use twice, use $timeout or interval

Removing multiple keys from a dictionary safely

Found a solution with pop and map

d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)

The output of this:

{'d': 'valueD'}

I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.

Update

The above code will throw an error if a key does not exist in the dict.

DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']

def remove_keys(key):
    try:
        DICTIONARY.pop(key, None)
    except:
        pass  # or do any action

list(map(remove_key, keys))
print(DICTIONARY)

output:

DICTIONARY = {'b': 'valueB', 'd': 'valueD'}

How to make button look like a link?

_x000D_
_x000D_
button {_x000D_
  background: none!important;_x000D_
  border: none;_x000D_
  padding: 0!important;_x000D_
  /*optional*/_x000D_
  font-family: arial, sans-serif;_x000D_
  /*input has OS specific font-family*/_x000D_
  color: #069;_x000D_
  text-decoration: underline;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<button> your button that looks like a link</button>
_x000D_
_x000D_
_x000D_

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

Sync data between Android App and webserver

@Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).

Here's a blog post about it: http://android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html

Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).

Also, if you wish to take a look at the 2015's code: https://github.com/google/iosched

Redirect to an external URL from controller action in Spring MVC

For external url you have to use "http://www.yahoo.com" as the redirect url.

This is explained in the redirect: prefix of Spring reference documentation.

redirect:/myapp/some/resource

will redirect relative to the current Servlet context, while a name such as

redirect:http://myhost.com/some/arbitrary/path

will redirect to an absolute URL

Why is the jquery script not working?

This may not be the answer you are looking for, but may help others whose jquery is not working properly, or working sometimes and not at other times.

This could be because your jquery has not yet loaded and you have started to interact with the page. Either put jquery on top in head (probably not a very great idea) or use a loader or spinner to stop the user from interacting with the page until the entire jquery has loaded.

Change the location of the ~ directory in a Windows install of Git Bash

Here you go: Here you go: Create a System Restore Point. Log on under an admin account. Delete the folder C:\SomeUser. Move the folder c:\Users\SomeUser so that it becomes c:\SomeUser. Open the registry editor. Navigate to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. Search for "ProfileImagePath" until you find the one that points at c:\Users\SomeUser. Modify it so that it points at c:\SomeUser. Use System Restore in case things go wrong.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Offering another potential solution to this error.

If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.

e.g.

https://example.com/api/etc

and not

https://123.4.5.6/api/etc

In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE.

Position absolute but relative to parent

If you don't give any position to parent then by default it takes static. If you want to understand that difference refer to this example

Example 1::

http://jsfiddle.net/Cr9KB/1/

   #mainall
{

    background-color:red;
    height:150px;
    overflow:scroll
}

Here parent class has no position so element is placed according to body.

Example 2::

http://jsfiddle.net/Cr9KB/2/

#mainall
{
    position:relative;
    background-color:red;
    height:150px;
    overflow:scroll
}

In this example parent has relative position hence element are positioned absolute inside relative parent.

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

Reading a text file and splitting it into single words in python

What you can do is use nltk to tokenize words and then store all of the words in a list, here's what I did. If you don't know nltk; it stands for natural language toolkit and is used to process natural language. Here's some resource if you wanna get started [http://www.nltk.org/book/]

import nltk 
from nltk.tokenize import word_tokenize 
file = open("abc.txt",newline='')
result = file.read()
words = word_tokenize(result)
for i in words:
       print(i)

The output will be this:

09807754
18
n
03
aristocrat
0
blue_blood
0
patrician

VBA copy cells value and format

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    call copValuesAndFormat(i,3,a,15)        
    call copValuesAndFormat(i,5,a,17) 
    call copValuesAndFormat(i,6,a,18) 
    call copValuesAndFormat(i,7,a,19) 
    call copValuesAndFormat(i,8,a,20) 
    call copValuesAndFormat(i,9,a,21) 
    a = a + 1
  End If
Next i
end sub

sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
  Worksheets(1).Cells(x1, y1).Copy
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub

(I do not have Excel in current location so please excuse bugs as not tested)

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

How to make padding:auto work in CSS?

The simplest supported solution is to either use margin

.element {
  display: block;
  margin: 0px auto;
}

Or use a second container around the element that has this margin applied. This will somewhat have the effect of padding: 0px auto if it did exist.

CSS

.element_wrapper {
  display: block;
  margin: 0px auto;
}
.element {
  background: blue;
}

HTML

<div class="element_wrapper">
  <div class="element">
    Hello world
  </div>
</div>

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

I have the similar problem and fixed it by temporarily disabling my antivirus(Kaspersky Free 18.0.0.405). This AV has HTTPS interception module that automatically self-sign all certificates it finds in HTTPS responses.

Wget from Cygwin does not know anything about AV root certificate, so when it finds that website's certificate was signed with non trust certificate it prints that error.

To fix this permanently without disabling AV you should copy the AV root certificate from Windows certificate store to /etc/pki/ca-trust/source/anchors as .pem file(base64 encoding) and run update-ca-trust

IntelliJ - Convert a Java project/module into a Maven project/module

I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:

  1. Annotation settings are changed for the modules
  2. Compiler output path is changed for the modules
  3. Resources settings are ignored totally and only taken from pom.xml
  4. Module dependencies are messed up and have to checked
  5. Language/Encoding settings are changed for the modules

All these points need review and adjusting but after this it works like charm.

Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
    <!-- Generic properties -->
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
    <!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
    <directory>${project.basedir}/target</directory>
    <outputDirectory>${project.build.directory}/classes</outputDirectory>
    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>

    <resources>
        <resource>
            <directory>${project.basedir}/src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <annotationProcessors/>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Edit 2019:

  • Added recursive resource scan
  • Added directory specification which might be important to avoid confusion of IDEA recarding the content root structure

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

Python datetime to string without microsecond component

If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

See the documentation of datetime.strftime() for an explanation of the % directives.

How to backup Sql Database Programmatically in C#

Works for me:

public class BackupService
{
    private readonly string _connectionString;
    private readonly string _backupFolderFullPath;
    private readonly string[] _systemDatabaseNames = { "master", "tempdb", "model", "msdb" };

    public BackupService(string connectionString, string backupFolderFullPath)
    {
        _connectionString = connectionString;
        _backupFolderFullPath = backupFolderFullPath;
    }

    public void BackupAllUserDatabases()
    {
        foreach (string databaseName in GetAllUserDatabases())
        {
            BackupDatabase(databaseName);
        }
    }

    public void BackupDatabase(string databaseName)
    {
        string filePath = BuildBackupPathWithFilename(databaseName);

        using (var connection = new SqlConnection(_connectionString))
        {
            var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", databaseName, filePath);

            using (var command = new SqlCommand(query, connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }

    private IEnumerable<string> GetAllUserDatabases()
    {
        var databases = new List<String>();

        DataTable databasesTable;

        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();

            databasesTable = connection.GetSchema("Databases");

            connection.Close();
        }

        foreach (DataRow row in databasesTable.Rows)
        {
            string databaseName = row["database_name"].ToString();

            if (_systemDatabaseNames.Contains(databaseName))
                continue;

            databases.Add(databaseName);
        }

        return databases;
    }

    private string BuildBackupPathWithFilename(string databaseName)
    {
        string filename = string.Format("{0}-{1}.bak", databaseName, DateTime.Now.ToString("yyyy-MM-dd"));

        return Path.Combine(_backupFolderFullPath, filename);
    }
}

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

Had the same problem in Ubuntu 14 using XAMPP. Here's what I did which worked..

  1. Stop mysql if its running in xampp
  2. vi /opt/lamp/phpmyadmin/config.inc.php (use sudo if you are not the su)
  3. replace

    $cfg['Servers'][1]['relation'] = 'pma__relation';
    $cfg['Servers'][1]['userconfig'] = 'pma__userconfig';
    $cfg['Servers'][1]['table_info'] = 'pma__table_info';
    ...
    

    to

    $cfg['Servers'][1]['pma__relation'] = 'pma__relation';
    $cfg['Servers'][1]['pma__userconfig'] = 'pma__userconfig';
    $cfg['Servers'][1]['pma__table_info'] = 'pma__table_info';
    ...
    

    basically add pma__ prefix to the left side similar to the right.

  4. Run mysql and access localhost/phpmyadmin and click on a db to check if it works.

Hope this helps.

Insert new item in array on any position in PHP

You may find this a little more intuitive. It only requires one function call to array_splice:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote

array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e

If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.

Force hide address bar in Chrome on Android

window.scrollTo(0,1);

this will help you but this javascript is may not work in all browsers

Can an Android App connect directly to an online mysql database

Look at this online backend.

Parse.com

They offer push notifications, social integration, data storage, and the ability to add rich custom logic to your app’s backend with Cloud Code.

How to check if a windows form is already open, and close it if it is?

I'm not sure that I understand the statement. Hope this helps. If you want to operate with only one instance of this form you should prevent Form.Dispose call on user close. In order to do this, you can handle child form's Closing event.

private void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Hide();
    e.Cancel = true;
}

And then you don't need to create new instances of frm. Just call Show method on the instance.

You can check Form.Visible property to check if the form open at the moment.

private ChildForm form = new ChildForm();

private void ReopenChildForm()
{
    if(form.Visible)
    {
        form.Hide();
    }
    //Update form information
    form.Show();
}

Actually, I still don't understand why don't you just update the data on the form.

How do I insert an image in an activity with android studio?

copy the image that you want to show in android app and paste in drawable folder. given below code

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image"
 />

HTML-parser on Node.js

Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

Combine two (or more) PDF's

Combining two byte[] using iTextSharp up to version 5.x:

internal static MemoryStream mergePdfs(byte[] pdf1, byte[] pdf2)
{
    MemoryStream outStream = new MemoryStream();
    using (Document document = new Document())
    using (PdfCopy copy = new PdfCopy(document, outStream))
    {
        document.Open();
        copy.AddDocument(new PdfReader(pdf1));
        copy.AddDocument(new PdfReader(pdf2));
    }
    return outStream;
}

Instead of the byte[]'s it's possible to pass also Stream's

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

IOException: The process cannot access the file 'file path' because it is being used by another process

My below code solve this issue, but i suggest First of all you need to understand what causing this issue and try the solution which you can find by changing code

I can give another way to solve this issue but better solution is to check your coding structure and try to analyse what makes this happen,if you do not find any solution then you can go with this code below

try{
Start:
///Put your file access code here


}catch (Exception ex)
 {
//by anyway you need to handle this error with below code
   if (ex.Message.StartsWith("The process cannot access the file"))
    {
         //Wait for 5 seconds to free that file and then start execution again
         Thread.Sleep(5000);
         goto Start;
    }
 }

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How to run a task when variable is undefined in ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword.

tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

What does -> mean in Python function definitions?

It's a function annotation.

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

I can't understand why this JAXB IllegalAnnotationException is thrown

JAXB (java.xml.bind)

This answer:

JDK 14

Spring Boot WebFlux 2.3.3.RELEASE

Lombok 1.18.12

Work for me >>>>> JDK 14

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.3</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>3.0.0-M4</version>
</dependency>

So Dependencies(jaxb-api, jaxb-impl, jaxb-runtime)

I try to test every version.

Body Request:

<?xml version="1.0" encoding="UTF-8"?>
<service generator="zend" version="1.0">
    <send>
        <message>OK</message>
        <status>success</status>
    </send>
</service> 

DTO:

import lombok.Getter;
import lombok.Setter;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

public class SmsSend {
    
    @Getter
    @Setter
    @XmlRootElement(name = "service")
    public static class ReplyMethodSend {
        private List<ReplyValue> send = new ArrayList<>();
    }

    @Getter
    @Setter
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class ReplyValue {
        private String message;
        private String status;
    }
}

Response:

{
    "send": [
        {
        "message": "OK",
        "status": "success"
        }
    ]
}

Have fun with programming ^__^

How to evaluate http response codes from bash/shell script?

Another variation:

       status=$(curl -sS  -I https://www.healthdata.gov/user/login  2> /dev/null | head -n 1 | cut -d' ' -f2)
status_w_desc=$(curl -sS  -I https://www.healthdata.gov/user/login  2> /dev/null | head -n 1 | cut -d' ' -f2-)

How do I grep recursively?

just the filenames can be useful too

grep -r -l "foo" .

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

You just have to put the <form ... > tag before the <table> tag and the </form> at the end.

Hopte it helps.

How to do a deep comparison between 2 objects with lodash?

Here's a concise solution:

_.differenceWith(a, b, _.isEqual);

Click in OK button inside an Alert (Selenium IDE)

For selenium, an alert is the one which raised using javascript e.g.

 javascript:alert();

There is one basic check to verify whether your alert is actually a javascript alert or just a div-based box for displaying some message. If its a javascript alert, you wont be able to see it on screen while running the selenium script.

If you are able to see it, then you need to get the locator of the ok button of the alert and use selenium.click(locator) to dismiss the alert. Can help you better if you can provide more context:

  1. IDE or RC?
  2. HTML code of the alert
  3. your selenium script.

Vamyip

How do I compare strings in GoLang?

The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

setTimeout / clearTimeout problems

Not sure if this violates some good practice coding rule but I usually come out with this one:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

This prevent the need to declare the timer out of the function.

EDIT: this also don't declare a new variable at each invocation, but always recycle the same.

Hope this helps.

What does \d+ mean in regular expression terms?

\d is called a character class and will match digits. It is equal to [0-9].

+ matches 1 or more occurrences of the character before.

So \d+ means match 1 or more digits.

iPhone UITextField - Change placeholder text color

in swift 3.X

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])

in swift 5

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])

struct in class

I declared class B inside class A, how do I access it?

Just because you declare your struct B inside class A does not mean that an instance of class A automatically has the properties of struct B as members, nor does it mean that it automatically has an instance of struct B as a member.

There is no true relation between the two classes (A and B), besides scoping.


struct A { 
  struct B { 
    int v;
  };  

  B inner_object;
};

int
main (int argc, char *argv[]) {
  A object;
    object.inner_object.v = 123;
}

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

Copy the DLL to C:\Windows\SysWoW64\
In an elevated command prompt: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

Copy the DLL to C:\Windows\System32\
In an elevated command prompt: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

I know it seems the wrong way round, but that's the way it works. See:

http://support.microsoft.com/kb/249873
Quote: "Note On a 64-bit version of a Windows operating system, there are two versions of the Regsv32.exe file:
The 64-bit version is %systemroot%\System32\regsvr32.exe.
The 32-bit version is %systemroot%\SysWoW64\regsvr32.exe.
"

Referring to a Column Alias in a WHERE Clause

Came here looking something similar to that, but with a CASE WHEN, and ended using the where like this: WHERE (CASE WHEN COLUMN1=COLUMN2 THEN '1' ELSE '0' END) = 0 maybe you could use DATEDIFF in the WHERE directly. Something like:

SELECT logcount, logUserID, maxlogtm
FROM statslogsummary
WHERE (DATEDIFF(day, maxlogtm, GETDATE())) > 120

Write / add data in JSON file using Node.js

Above example is also correct, but i provide simple example:

var fs = require("fs");
var sampleObject = {
    name: 'pankaj',
    member: 'stack',
    type: {
        x: 11,
        y: 22
    }
};

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log("File has been created");
});

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

Add data to JSONObject

The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.

What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!

I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.

So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;

//  create and initialize an object 
public static JSONObject buildObject( final SimpleEntry... entries ) { 
    JSONObject object = new JSONObject();
    for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
    return object;
}

//  nest a list of objects inside another                          
public static void putObjects( final JSONObject parentObject, final String key,
                               final JSONObject... objects ) { 
    List objectList = new ArrayList<JSONObject>();
    for( JSONObject o : objects ) objectList.add( o );
    parentObject.put( key, objectList );
}   

Implementation example:

JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
    buildObject( 
        new SimpleEntry( "child1Key1", "someValue" )
      , new SimpleEntry( "child1Key2", "someValue" ) 
    )
  , buildObject( 
        new SimpleEntry( "child2Key1", "someValue" )
      , new SimpleEntry( "child2Key2", "someValue" ) 
    )
);      

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub