Programs & Examples On #Robotlegs

Robotlegs is a tiny framework for building Actionscript 3 (Flash and/or Flex) applications

display: inline-block extra margin

The divs are treated as inline-elements. Just as a space or line-break between two spans would create a gap, it does between inline-blocks. You could either give them a negative margin or set word-spacing: -1; on the surrounding container.

Is it possible to cherry-pick a commit from another git repository?

Here's an example of the remote-fetch-merge.

cd /home/you/projectA
git remote add projectB /home/you/projectB
git fetch projectB

Then you can:

git cherry-pick <first_commit>..<last_commit>

or you could even merge the whole branch

git merge projectB/master

Does MS SQL Server's "between" include the range boundaries?

The BETWEEN operator is inclusive.

From Books Online:

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

DateTime Caveat

NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.

e.g. to get all values within June 2016 you'd need to run:

where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')

i.e.

where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'

datetime2 and datetimeoffset

Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:

where myDateTime >= '20160601' AND myDateTime < '20160701'

ValueError: max() arg is an empty sequence

I realized that I was iterating over a list of lists where some of them were empty. I fixed this by adding this preprocessing step:

tfidfLsNew = [x for x in tfidfLs if x != []]

the len() of the original was 3105, and the len() of the latter was 3101, implying that four of my lists were completely empty. After this preprocess my max() min() etc. were functioning again.

How to add days to the current date?

can try this

select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result

How do I use hexadecimal color strings in Flutter?

No need functions

For example to give color to a container using colorcode

Container (

color:Color(0xff000000)

)

Here the 0xff is the format followed by color code

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

How to avoid page refresh after button click event in asp.net

Page got refreshed when a trip to server is made, and server controls like Button has a property AutoPostback = true by default which means whenever they are clicked a trip to server will be made. Set AutoPostback = false for insert button, and this will do the trick for you.

Netbeans - Error: Could not find or load main class

try this it work out for me perfectly go to project and right click on your java file at the right corner, go to properties, go to run, go to browse, and then select Main class. now you can run your program again.

Writing an input integer into a cell

I've done this kind of thing with a form that contains a TextBox.

So if you wanted to put this in say cell H1, then use:

ActiveSheet.Range("H1").Value = txtBoxName.Text

How to call shell commands from Ruby

If you have a more complex case than the common case that can not be handled with ``, then check out Kernel.spawn(). This seems to be the most generic/full-featured provided by stock Ruby to execute external commands.

You can use it to:

  • create process groups (Windows).
  • redirect in, out, error to files/each-other.
  • set env vars, umask.
  • change the directory before executing a command.
  • set resource limits for CPU/data/etc.
  • Do everything that can be done with other options in other answers, but with more code.

The Ruby documentation has good enough examples:

env: hash
  name => val : set the environment variable
  name => nil : unset the environment variable
command...:
  commandline                 : command line string which is passed to the standard shell
  cmdname, arg1, ...          : command name and one or more arguments (no shell)
  [cmdname, argv0], arg1, ... : command name, argv[0] and zero or more arguments (no shell)
options: hash
  clearing environment variables:
    :unsetenv_others => true   : clear environment variables except specified by env
    :unsetenv_others => false  : dont clear (default)
  process group:
    :pgroup => true or 0 : make a new process group
    :pgroup => pgid      : join to specified process group
    :pgroup => nil       : dont change the process group (default)
  create new process group: Windows only
    :new_pgroup => true  : the new process is the root process of a new process group
    :new_pgroup => false : dont create a new process group (default)
  resource limit: resourcename is core, cpu, data, etc.  See Process.setrlimit.
    :rlimit_resourcename => limit
    :rlimit_resourcename => [cur_limit, max_limit]
  current directory:
    :chdir => str
  umask:
    :umask => int
  redirection:
    key:
      FD              : single file descriptor in child process
      [FD, FD, ...]   : multiple file descriptor in child process
    value:
      FD                        : redirect to the file descriptor in parent process
      string                    : redirect to file with open(string, "r" or "w")
      [string]                  : redirect to file with open(string, File::RDONLY)
      [string, open_mode]       : redirect to file with open(string, open_mode, 0644)
      [string, open_mode, perm] : redirect to file with open(string, open_mode, perm)
      [:child, FD]              : redirect to the redirected file descriptor
      :close                    : close the file descriptor in child process
    FD is one of follows
      :in     : the file descriptor 0 which is the standard input
      :out    : the file descriptor 1 which is the standard output
      :err    : the file descriptor 2 which is the standard error
      integer : the file descriptor of specified the integer
      io      : the file descriptor specified as io.fileno
  file descriptor inheritance: close non-redirected non-standard fds (3, 4, 5, ...) or not
    :close_others => false : inherit fds (default for system and exec)
    :close_others => true  : dont inherit (default for spawn and IO.popen)

Why are interface variables static and final by default?

Since interface doesn't have a direct object, the only way to access them is by using a class/interface and hence that is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess.

Hence if at all there is an interface variable, it will be implicitly static, final and obviously public!!!

PostgreSQL ERROR: canceling statement due to conflict with recovery

Running queries on hot-standby server is somewhat tricky — it can fail, because during querying some needed rows might be updated or deleted on primary. As a primary does not know that a query is started on secondary it thinks it can clean up (vacuum) old versions of its rows. Then secondary has to replay this cleanup, and has to forcibly cancel all queries which can use these rows.

Longer queries will be canceled more often.

You can work around this by starting a repeatable read transaction on primary which does a dummy query and then sits idle while a real query is run on secondary. Its presence will prevent vacuuming of old row versions on primary.

More on this subject and other workarounds are explained in Hot Standby — Handling Query Conflicts section in documentation.

Apache POI Excel - how to configure columns to be expanded?

Tip : To make Auto size work , the call to sheet.autoSizeColumn(columnNumber) should be made after populating the data into the excel.

Calling the method before populating the data, will have no effect.

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

Iterating through struct fieldnames in MATLAB

Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.

Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end

No tests found with test runner 'JUnit 4'

My problem was that declaration import org.junit.Test; has disappeared (or wasn't added?). After adding it, I had to remove another import declaration (Eclipse'll hint you which one) and everything began to work again.

What is the PostgreSQL equivalent for ISNULL()

Try:

SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name

How often should you use git-gc?

Recent versions of git run gc automatically when required, so you shouldn't have to do anything. See the Options section of man git-gc(1): "Some git commands run git gc --auto after performing operations that could create many loose objects."

Ignoring NaNs with str.contains

In addition to the above answers, I would say for columns having no single word name, you may use:-

df[df['Product ID'].str.contains("foo") == True]

Hope this helps.

How can I simulate a print statement in MySQL?

to take output in MySQL you can use if statement SYNTAX:

if(condition,if_true,if_false)

the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL

forcing web-site to show in landscape mode only

While I myself would be waiting here for an answer, I wonder if it can be done via CSS:

@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}

@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}

Converting unix time into date-time via excel

=A1/(24*60*60) + DATE(1970;1;1) should work with seconds.

=(A1/86400/1000)+25569 if your time is in milliseconds, so dividing by 1000 gives use the correct date

Don't forget to set the type to Date on your output cell. I tried it with this date: 1504865618099 which is equal to 8-09-17 10:13.

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

Bouncy Castle still requires jars installed as far as I can tell.

I did a little test and it seemed to confirm this:

http://www.bouncycastle.org/wiki/display/JA1/Frequently+Asked+Questions

Overlay with spinner

Here is simple overlay div without using any gif, This can be applied over another div.

<style>
.loader {
  position: relative;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 70px;
  height: 70px;
  left:50%;
  top:50%;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}
#overlay{
    position: absolute;
    top:0px;
    left:0px;
    width: 100%;
    height: 100%;
    background: black;
    opacity: .5;
}
.container{
    position:relative;
    height: 300px;
    width: 200px;
    border:1px solid
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<h2>How To Create A Loader</h2>

<div class="container">
  <h3>Overlay over this div</h3>
  <div id="overlay">
      <div class="loader"></div>
  </div>
<div>

typescript - cloning object

How about good old jQuery?! Here is deep clone:

var clone = $.extend(true, {}, sourceObject);

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

How to convert a 3D point into 2D perspective projection?

You can project 3D point in 2D using: Commons Math: The Apache Commons Mathematics Library with just two classes.

Example for Java Swing.

import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;


Plane planeX = new Plane(new Vector3D(1, 0, 0));
Plane planeY = new Plane(new Vector3D(0, 1, 0)); // Must be orthogonal plane of planeX

void drawPoint(Graphics2D g2, Vector3D v) {
    g2.drawLine(0, 0,
            (int) (world.unit * planeX.getOffset(v)),
            (int) (world.unit * planeY.getOffset(v)));
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    drawPoint(g2, new Vector3D(2, 1, 0));
    drawPoint(g2, new Vector3D(0, 2, 0));
    drawPoint(g2, new Vector3D(0, 0, 2));
    drawPoint(g2, new Vector3D(1, 1, 1));
}

Now you only needs update the planeX and planeY to change the perspective-projection, to get things like this:

enter image description hereenter image description here

Rename column SQL Server 2008

Run Query:

    SP_RENAME '[TableName].[ColumnName]','NewNameForColumn'

window.onload vs $(document).ready()

Document.ready (a jQuery event) will fire when all the elements are in place, and they can be referenced in the JavaScript code, but the content is not necessarily loaded. Document.ready executes when the HTML document is loaded.

$(document).ready(function() {

    // Code to be executed
    alert("Document is ready");
});

The window.load however will wait for the page to be fully loaded. This includes inner frames, images, etc.

$(window).load(function() {

    //Fires when the page is loaded completely
    alert("window is loaded");
});

How do I get the current date and time in PHP?

// Simply:
$date = date('Y-m-d H:i:s');

// Or:
$date = date('Y/m/d H:i:s');

// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';

/** 
 * This time is based on the default server time zone.
 * If you want the date in a different time zone,
 * say if you come from Nairobi, Kenya like I do, you can set
 * the time zone to Nairobi as shown below.
 */

date_default_timezone_set('Africa/Nairobi');

// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');

// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.

For a time-zone reference, see List of Supported Timezones.

making matplotlib scatter plots from dataframes in Python's pandas

Try passing columns of the DataFrame directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100

In [5]: df
Out[5]: 
       col1      col2  col3
0 -1.000075 -0.759910   100
1  0.510382  0.972615   200
2  1.872067 -0.731010   500
3  0.131612  1.075142  1000
4  1.497820  0.237024  1700

Vary scatter point size based on another column

plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)

enter image description here

Vary scatter point color based on another column

colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)

enter image description here

Scatter plot with legend

However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter once for each point type.

cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300') 
plt.legend()

enter image description here

Update

From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull method: df[df.col3.isnull()]

To split a list of points into many types, take a look at numpy select, which is a vectorized if-then-else implementation and accepts an optional default value. For example:

df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
                         [0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
    subset = df[df.subset == label]
    plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()

enter image description here

How do I force detach Screen from another SSH session?

Short answer

  1. Reattach without ejecting others: screen -x
  2. Get list of displays: ^A *, select the one to disconnect, press d


Explained answer

Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)

Note: PREFIX is usually ^A = ctrl+a

Note: the display may also be called:

  • "user front-end" (in at command manual in screen)
  • "client" (tmux vocabulary where this functionality is detach-client)
  • "terminal" (as we call the window in our user interface) /depending on

1. Reattach a session: screen -x

-x attach to a not detached screen session without detaching it

2. List displays of this session: PREFIX *

It is the default key binding for: PREFIX :displays. Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).

term-type   size         user interface           window       Perms
---------- ------- ---------- ----------------- ----------     -----
 screen     240x60         you@/dev/pts/2      nb  0(zsh)        rwx
 screen      78x40         you@/dev/pts/0      nb  0(zsh)        rwx

Using arrows ? ?, select the targeted display, press d If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.

Press ENTER to quit the listing.

Optionally: in order to make the content fit your screen, reflow: PREFIX F (uppercase F)

Excerpt from man page of screen:

displays

Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:

  • mouseclick Move to the selected line. Available when "mousetrack" is set to on.
  • space Refresh the list
  • d Detach that display
  • D Power detach that display
  • C-g, enter, or escape Exit the list

What is the difference between lower bound and tight bound?

The phrases minimum time and maximum time are a bit misleading here. When we talk about big O notations, it's not the actual time we are interested in, it is how the time increases when our input size gets bigger. And it's usually the average or worst case time we are talking about, not best case, which usually is not meaningful in solving our problems.

Using the array search in the accepted answer to the other question as an example. The time it takes to find a particular number in list of size n is n/2 * some_constant in average. If you treat it as a function f(n) = n/2*some_constant, it increases no faster than g(n) = n, in the sense as given by Charlie. Also, it increases no slower than g(n) either. Hence, g(n) is actually both an upper bound and a lower bound of f(n) in Big-O notation, so the complexity of linear search is exactly n, meaning that it is Theta(n).

In this regard, the explanation in the accepted answer to the other question is not entirely correct, which claims that O(n) is upper bound because the algorithm can run in constant time for some inputs (this is the best case I mentioned above, which is not really what we want to know about the running time).

C# send a simple SSH command

I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.

The original package website can be still found here, including the documentation (which currently isn't available on GitHub).

For your case the code would be something like this.

using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
    client.Connect();
    client.RunCommand("etc/init.d/networking restart");
    client.Disconnect();
}

Add column to dataframe with constant value

Summing up what the others have suggested, and adding a third way

You can:

where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.

'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).

All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).

SQL Server command line backup statement

Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files

echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>

:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>

:: set Database name to backup
set DATABASENAME=<<db name here>>

:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.

:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"

jQuery - getting custom attribute from selected option

You're pretty close:

var myTag = $(':selected', element).attr("myTag");

PHP cURL custom headers

Here is one basic function:

/**
 * 
 * @param string $url
 * @param string|array $post_fields
 * @param array $headers
 * @return type
 */
function cUrlGetData($url, $post_fields = null, $headers = null) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($post_fields && !empty($post_fields)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    }
    if ($headers && !empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    return $data;
}

Usage example:

$url = "http://www.myurl.com";
$post_fields = 'postvars=val1&postvars2=val2';
$headers = ['Content-Type' => 'application/x-www-form-urlencoded', 'charset' => 'utf-8'];
$dat = cUrlGetData($url, $post_fields, $headers);

How do I change the database name using MySQL?

Try:

RENAME database1 TO database2;

htmlentities() vs. htmlspecialchars()

Because:

  • Sometimes you're writing XML data, and you can't use HTML entities in a XML file.
  • Because htmlentities substitutes more characters than htmlspecialchars. This is unnecessary, makes the PHP script less efficient and the resulting HTML code less readable.

htmlentities is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8 and you're handling data with an encoding different from the page's.

Cast Double to Integer in Java

Memory efficient, as it will share the already created instance of Double.

Double.valueOf(Math.floor(54644546464/60*60*24*365)).intValue()

Serializing enums with Jackson

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

Difference between View and table in sql

A view helps us in get rid of utilizing database space all the time. If you create a table it is stored in database and holds some space throughout its existence. Instead view is utilized when a query runs hence saving the db space. And we cannot create big tables all the time joining different tables though we could but its depends how big the table is to save the space. So view just temporarily create a table with joining different table at the run time. Experts,Please correct me if I am wrong.

How can I check if given int exists in array?

You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.

also see this answer: C++ check if element exists in array

switch case statement error: case expressions must be constant expression

Solution can be done be this way:

  1. Just assign the value to Integer
  2. Make variable to final

Example:

public static final int cameraRequestCode = 999;

Hope this will help you.

How to remove empty cells in UITableView?

Swift 3 syntax:

tableView.tableFooterView = UIView(frame: .zero)

Swift syntax: < 2.0

tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

Swift 2.0 syntax:

tableView.tableFooterView = UIView(frame: CGRect.zero)

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

sqlalchemy filter multiple columns

A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.

search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()

Note: the %% are important to skip % formatting the query.

UITableViewCell Selected Background Color on Multiple Selection

You can also set cell's selectionStyle to.none in interface builder. The same solution as @AhmedLotfy provided, only from IB.

enter image description here

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Scanner vs. BufferedReader

The Main Differences:

  1. Scanner

  • A simple text scanner which can parse primitive types and strings using regular expressions.
  • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Example

 String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

prints the following output:

 1
 2
 red
 blue 

The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

 String input = "1 fish 2 fish red fish blue fish";

 Scanner s = new Scanner(input);
 s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
 MatchResult result = s.match();
 for (int i=1; i<=result.groupCount(); i++)
     System.out.println(result.group(i));
 s.close(); `


  1. BufferedReader:

    • Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

    • The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

Source:Link

How to use ADB to send touch events to device using sendevent command?

Android comes with an input command-line tool that can simulate miscellaneous input events. To simulate tapping, it's:

input tap x y

You can use the adb shell ( > 2.3.5) to run the command remotely:

adb shell input tap x y

How does one extract each folder name from a path?

There are a few ways that a file path can be represented. You should use the System.IO.Path class to get the separators for the OS, since it can vary between UNIX and Windows. Also, most (or all if I'm not mistaken) .NET libraries accept either a '\' or a '/' as a path separator, regardless of OS. For this reason, I'd use the Path class to split your paths. Try something like the following:

string originalPath = "\\server\\folderName1\\another\ name\\something\\another folder\\";
string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
                              Path.DirectorySeparatorChar);

This should work regardless of the number of folders or the names.

In C#, can a class inherit from another class and an interface?

Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.

.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.


In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:

public interface ITwo : IOne

The technical answer is that ITwo does inherit IOne for a few reasons:

  • Interfaces never have an implementation, so arguing that ITwo implements IOne is flat wrong
  • ITwo inherits IOne methods, if MethodOne() exists on IOne then it is also accesible from ITwo. i.e: ((ITwo)someObject).MethodOne()) is valid, even though ITwo does not explicitly contain a definition for MethodOne()
  • ...because the runtime says so! typeof(IOne).IsAssignableFrom(typeof(ITwo)) returns true

We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)

Is not an enclosing class Java

To achieve the requirement from the question, we can put classes into interface:

public interface Shapes {
    class AShape{
    }
    class ZShape{
    }
}

and then use as author tried before:

public class Test {
    public static void main(String[] args) {
        Shape s = new Shapes.ZShape();
    }
}

If we looking for the proper "logical" solution, should be used fabric design pattern

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

Single controller with multiple GET methods in ASP.NET Web API

The lazy/hurry alternative (Dotnet Core 2.2):

[HttpGet("method1-{item}")]
public string Method1(var item) { 
return "hello" + item;}

[HttpGet("method2-{item}")]
public string Method2(var item) { 
return "world" + item;}

Calling them :

localhost:5000/api/controllername/method1-42

"hello42"

localhost:5000/api/controllername/method2-99

"world99"

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

iOS Simulator to test website on Mac

I use this site mostly

Its good one

http://iphone4simulator.com/

Still its better preferred to test on real device..

Hope this info helps you..

Injecting $scope into an angular service function()

You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.

The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,

var students = $http.get(path).then(function (resp) {
  return resp.data;
}); // then() returns a promise object, not resp.data

There's a simple way to get around this and it's to supply a callback function.

.service('StudentService', [ '$http',
    function ($http) {
    // get some data via the $http
    var path = '/students';

    //save method create a new student if not already exists
    //else update the existing object
    this.save = function (student, doneCallback) {
      $http.post(
        path, 
        {
          params: {
            student: student
          }
        }
      )
      .then(function (resp) {
        doneCallback(resp.data); // when the async http call is done, execute the callback
      });  
    }
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
  $scope.saveUser = function (user) {
    StudentService.save(user, function (data) {
      $scope.message = data; // I'm assuming data is a string error returned from your REST API
    })
  }
}]);

The form:

<div class="form-message">{{message}}</div>

<div ng-controller="StudentSaveController">
  <form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" /><br />
    E-mail: <input type="email" ng-model="user.email" /><br />
    Gender: <input type="radio" ng-model="user.gender" value="male" />male
    <input type="radio" ng-model="user.gender" value="female" />female<br />
    <input type="button" ng-click="reset()" value="Reset" />
    <input type="submit" ng-click="saveUser(user)" value="Save" />
  </form>
</div>

This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Well, I had this problem and after seeing this post and particularly khmarbaise answer I noticed that M2_HOME was

D:\workspace\apache-maven-3.1.0-bin\apache-maven-3.1.0\bin

and then I chaged it to

D:\workspace\apache-maven-3.1.0-bin\apache-maven-3.1.0

I would like to mention that I use windows 7 (x64)

How do I show running processes in Oracle DB?

Keep in mind that there are processes on the database which may not currently support a session.

If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)

Is there a way to 'pretty' print MongoDB shell output to a file?

Put your query (e.g. db.someCollection.find().pretty()) to a javascript file, let's say query.js. Then run it in your operating system's shell using command:

mongo yourDb < query.js > outputFile

Query result will be in the file named 'outputFile'.

By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.

DBQuery.shellBatchSize = 100.

What is causing the error `string.split is not a function`?

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

Javascript string replace with regex to strip off illegal characters

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

Tools to generate database tables diagram with Postgresql?

PostgreSQL Autodoc has worked well for me. It is a simple command line tool. From the web page:

This is a utility which will run through PostgreSQL system tables and returns HTML, Dot, Dia and DocBook XML which describes the database.

Is there a bash command which counts files?

ls -1 log* | wc -l

Which means list one file per line and then pipe it to word count command with parameter switching to count lines.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

No Title Bar Android Theme

 this.requestWindowFeature(getWindow().FEATURE_NO_TITLE);

MySql Inner Join with WHERE clause

You are using two WHERE clauses but only one is allowed. Use it like this:

SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
  table1.f_com_id = '430'
  AND table1.f_status = 'Submitted'
  AND table2.f_type = 'InProcess'

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

WPF What is the correct way of using SVG files as icons in WPF

You can use the resulting xaml from the SVG as a drawing brush on a rectangle. Something like this:

<Rectangle>
   <Rectangle.Fill>
      --- insert the converted xaml's geometry here ---
   </Rectangle.Fill>
</Rectangle>

Selecting data frame rows based on partial string match in a column

I notice that you mention a function %like% in your current approach. I don't know if that's a reference to the %like% from "data.table", but if it is, you can definitely use it as follows.

Note that the object does not have to be a data.table (but also remember that subsetting approaches for data.frames and data.tables are not identical):

library(data.table)
mtcars[rownames(mtcars) %like% "Merc", ]
iris[iris$Species %like% "osa", ]

If that is what you had, then perhaps you had just mixed up row and column positions for subsetting data.


If you don't want to load a package, you can try using grep() to search for the string you're matching. Here's an example with the mtcars dataset, where we are matching all rows where the row names includes "Merc":

mtcars[grep("Merc", rownames(mtcars)), ]
             mpg cyl  disp  hp drat   wt qsec vs am gear carb
# Merc 240D   24.4   4 146.7  62 3.69 3.19 20.0  1  0    4    2
# Merc 230    22.8   4 140.8  95 3.92 3.15 22.9  1  0    4    2
# Merc 280    19.2   6 167.6 123 3.92 3.44 18.3  1  0    4    4
# Merc 280C   17.8   6 167.6 123 3.92 3.44 18.9  1  0    4    4
# Merc 450SE  16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
# Merc 450SL  17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
# Merc 450SLC 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3

And, another example, using the iris dataset searching for the string osa:

irisSubset <- iris[grep("osa", iris$Species), ]
head(irisSubset)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

For your problem try:

selectedRows <- conservedData[grep("hsa-", conservedData$miRNA), ]

"ssl module in Python is not available" when installing package with pip3

I tried A LOT of ways to solve this problem and none solved. I'm currently on Windows 10.

The only thing that worked was:

  • Uninstall Anaconda
  • Uninstall Python (i was using version 3.7.3)
  • Install Python again (remember to check the option to automatically add to PATH)

Then I've downloaded all the libs I needed using PIP... and worked!

Don't know why, or if the problem was somehow related to Anaconda.

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Count the number of all words in a string

I've found the following function and regex useful for word counts, especially in dealing with single vs. double hyphens, where the former generally should not count as a word break, eg, well-known, hi-fi; whereas double hyphen is a punctuation delimiter that is not bounded by white-space--such as for parenthetical remarks.

txt <- "Don't you think e-mail is one word--and not two!" #10 words
words <- function(txt) { 
length(attributes(gregexpr("(\\w|\\w\\-\\w|\\w\\'\\w)+",txt)[[1]])$match.length) 
}

words(txt) #10 words

Stringi is a useful package. But it over-counts words in this example due to hyphen.

stringi::stri_count_words(txt) #11 words

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

how to loop through each row of dataFrame in pyspark

You simply cannot. DataFrames, same as other distributed data structures, are not iterable and can be accessed using only dedicated higher order function and / or SQL methods.

You can of course collect

for row in df.rdd.collect():
    do_something(row)

or convert toLocalIterator

for row in df.rdd.toLocalIterator():
    do_something(row)

and iterate locally as shown above, but it beats all purpose of using Spark.

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

Create nice column output in python

I found this answer super-helpful and elegant, originally from here:

matrix = [["A", "B"], ["C", "D"]]

print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in matrix]))

Output

A   B
C   D

How do you load custom UITableViewCells from Xib files?

Took Shawn Craver's answer and cleaned it up a bit.

BBCell.h:

#import <UIKit/UIKit.h>

@interface BBCell : UITableViewCell {
}

+ (BBCell *)cellFromNibNamed:(NSString *)nibName;

@end

BBCell.m:

#import "BBCell.h"

@implementation BBCell

+ (BBCell *)cellFromNibNamed:(NSString *)nibName {
    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];
    NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
    BBCell *customCell = nil;
    NSObject* nibItem = nil;
    while ((nibItem = [nibEnumerator nextObject]) != nil) {
        if ([nibItem isKindOfClass:[BBCell class]]) {
            customCell = (BBCell *)nibItem;
            break; // we have a winner
        }
    }
    return customCell;
}

@end

I make all my UITableViewCell's subclasses of BBCell, and then replace the standard

cell = [[[BBDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BBDetailCell"] autorelease];

with:

cell = (BBDetailCell *)[BBDetailCell cellFromNibNamed:@"BBDetailCell"];

How do I push to GitHub under a different username?

If you have https://desktop.github.com/
then you can go to Preferences (or Options) -> Accounts
and then sign out and sign in.

Tesseract running error

tesseract  --tessdata-dir <tessdata-folder> <image-path> stdout --oem 2 -l <lng>

In my case, the mistakes that I've made or attempts that wasn't a success.

  • I cloned the github repo and copied files from there to
    • /usr/local/share/tessdata/
    • /usr/share/tesseract-ocr/tessdata/
    • /usr/share/tessdata/
  • Used TESSDATA_PREFIX with above paths
  • sudo apt-get install tesseract-ocr-eng

First 2 attempts did not worked because, the files from git clone did not worked for the reasons that I do not know. I am not sure why #3 attempt worked for me.

Finally,

  1. I downloaded the eng.traindata file using wget
  2. Copied it to some directory
  3. Used --tessdata-dir with directory name

Take away for me is to learn the tool well & make use of it, rather than relying on package manager installation & directories

Transposing a 1D NumPy array

As some of the comments above mentioned, the transpose of 1D arrays are 1D arrays, so one way to transpose a 1D array would be to convert the array to a matrix like so:

np.transpose(a.reshape(len(a), 1))

Integer to hex string in C++

#include <iostream> 
#include <sstream>  

int main()
{
unsigned int i = 4967295; // random number
std::string str1, str2;
unsigned int u1, u2;

std::stringstream ss;

Using void pointer:

// INT to HEX
ss << (void*)i;       // <- FULL hex address using void pointer
ss >> str1;          //     giving address value of one given in decimals.
ss.clear();         // <- Clear bits
// HEX to INT
ss << std::hex << str1;   // <- Capitals doesn't matter so no need to do extra here
ss >> u1;
ss.clear();

Adding 0x:

// INT to HEX with 0x
ss << "0x" << (void*)i;   // <- Same as above but adding 0x to beginning
ss >> str2;
ss.clear();
// HEX to INT with 0x
ss << std::hex << str2;   // <- 0x is also understood so need to do extra here
ss >> u2;
ss.clear();

Outputs:

std::cout << str1 << std::endl; // 004BCB7F
std::cout << u1 << std::endl;   // 4967295
std::cout << std::endl;
std::cout << str2 << std::endl; // 0x004BCB7F
std::cout << u2 << std::endl;   // 4967295


return 0;
}

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

How to get the filename without the extension in Java?

You can split it by "." and on index 0 is file name and on 1 is extension, but I would incline for the best solution with FileNameUtils from apache.commons-io like it was mentioned in the first article. It does not have to be removed, but sufficent is:

String fileName = FilenameUtils.getBaseName("test.xml");

String replacement in Objective-C

If you want multiple string replacement:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

Android Spinner: Get the selected item change event

The docs for the spinner-widget says

A spinner does not support item click events.

You should use setOnItemSelectedListener to handle your problem.

How to encrypt and decrypt file in Android?

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

Conceal provides easy Android APIs for performing fast encryption and authentication of data

What's the -practical- difference between a Bare and non-Bare repository?

A non-bare repository simply has a checked-out working tree. The working tree does not store any information about the state of the repository (branches, tags, etc.); rather, the working tree is just a representation of the actual files in the repo, which allows you to work on (edit, etc.) the files.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Kotlin:

var ver: String = packageManager.getPackageInfo(packageName, 0).versionName

Getting URL hash location, and using it in jQuery

Since jQuery 1.9, the :target selector will match the URL hash. So you could do:

$(":target").show(); // or $("ul:target").show();

Which would select the element with the ID matching the hash and show it.

How do I list all tables in all databases in SQL Server in a single result set?

Here's a tutorial providing a T-SQL script that will return the following fields for each table from each database located in a SQL Server Instance:

  1. ServerName
  2. DatabaseName
  3. SchemaName
  4. TableName
  5. ColumnName
  6. KeyType

https://tidbytez.com/2015/06/01/map-the-table-structure-of-a-sql-server-database/

/*
SCRIPT UPDATED
20180316
*/

USE [master]
GO

/*DROP TEMP TABLES IF THEY EXIST*/
IF OBJECT_ID('tempdb..#DatabaseList') IS NOT NULL
    DROP TABLE #DatabaseList;

IF OBJECT_ID('tempdb..#TableStructure') IS NOT NULL
    DROP TABLE #TableStructure;

IF OBJECT_ID('tempdb..#ErrorTable') IS NOT NULL
    DROP TABLE #ErrorTable;

IF OBJECT_ID('tempdb..#MappedServer') IS NOT NULL
    DROP TABLE #MappedServer;

DECLARE @ServerName AS SYSNAME

SET @ServerName = @@SERVERNAME

CREATE TABLE #DatabaseList (
    Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY
    ,ServerName SYSNAME
    ,DbName SYSNAME
    );

CREATE TABLE [#TableStructure] (
    [DbName] SYSNAME
    ,[SchemaName] SYSNAME
    ,[TableName] SYSNAME
    ,[ColumnName] SYSNAME
    ,[KeyType] CHAR(7)
    ) ON [PRIMARY];

/*THE ERROR TABLE WILL STORE THE DYNAMIC SQL THAT DID NOT WORK*/
CREATE TABLE [#ErrorTable] ([SqlCommand] VARCHAR(MAX)) ON [PRIMARY];

/*
A LIST OF DISTINCT DATABASE NAMES IS CREATED
THESE TWO COLUMNS ARE STORED IN THE #DatabaseList TEMP TABLE
THIS TABLE IS USED IN A FOR LOOP TO GET EACH DATABASE NAME
*/
INSERT INTO #DatabaseList (
    ServerName
    ,DbName
    )
SELECT @ServerName
    ,NAME AS DbName
FROM master.dbo.sysdatabases WITH (NOLOCK)
WHERE NAME <> 'tempdb'
ORDER BY NAME ASC

/*VARIABLES ARE DECLARED FOR USE IN THE FOLLOWING FOR LOOP*/
DECLARE @sqlCommand AS VARCHAR(MAX)
DECLARE @DbName AS SYSNAME
DECLARE @i AS INT
DECLARE @z AS INT

SET @i = 1
SET @z = (
        SELECT COUNT(*) + 1
        FROM #DatabaseList
        )

/*WHILE 1 IS LESS THAN THE NUMBER OF DATABASE NAMES IN #DatabaseList*/
WHILE @i < @z
BEGIN
    /*GET NEW DATABASE NAME*/
    SET @DbName = (
            SELECT [DbName]
            FROM #DatabaseList
            WHERE Id = @i
            )
    /*CREATE DYNAMIC SQL TO GET EACH TABLE NAME AND COLUMN NAME FROM EACH DATABASE*/
    SET @sqlCommand = 'USE [' + @DbName + '];' + '

INSERT INTO [#TableStructure]
SELECT DISTINCT' + '''' + @DbName + '''' + ' AS DbName
    ,SCHEMA_NAME(SCHEMA_ID) AS SchemaName
    ,T.NAME AS TableName    
    ,C.NAME AS ColumnName
    ,CASE 
        WHEN OBJECTPROPERTY(OBJECT_ID(iskcu.CONSTRAINT_NAME), ''IsPrimaryKey'') = 1 
            THEN ''Primary'' 
        WHEN OBJECTPROPERTY(OBJECT_ID(iskcu.CONSTRAINT_NAME), ''IsForeignKey'') = 1 
            THEN ''Foreign''
        ELSE NULL 
        END AS ''KeyType''
FROM SYS.TABLES AS t WITH (NOLOCK)
INNER JOIN SYS.COLUMNS C ON T.OBJECT_ID = C.OBJECT_ID
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS iskcu WITH (NOLOCK) 
ON SCHEMA_NAME(SCHEMA_ID) = iskcu.TABLE_SCHEMA 
    AND T.NAME = iskcu.TABLE_NAME
    AND C.NAME = iskcu.COLUMN_NAME
ORDER BY SchemaName ASC
    ,TableName ASC
    ,ColumnName ASC;
';

    /*ERROR HANDLING*/
    BEGIN TRY
        EXEC (@sqlCommand)
    END TRY

    BEGIN CATCH
        INSERT INTO #ErrorTable
        SELECT (@sqlCommand)
    END CATCH

    SET @i = @i + 1
END

/*
JOIN THE TEMP TABLES TOGETHER TO CREATE A MAPPED STRUCTURE OF THE SERVER
ADDITIONAL FIELDS ARE ADDED TO MAKE SELECTING TABLES AND FIELDS EASIER
*/
SELECT DISTINCT @@SERVERNAME AS ServerName
    ,DL.DbName
    ,TS.SchemaName
    ,TS.TableName
    ,TS.ColumnName
    ,TS.[KeyType]
    ,',' + QUOTENAME(TS.ColumnName) AS BracketedColumn
    ,',' + QUOTENAME(TS.TableName) + '.' + QUOTENAME(TS.ColumnName) AS BracketedTableAndColumn
    ,'SELECT * FROM ' + QUOTENAME(DL.DbName) + '.' + QUOTENAME(TS.SchemaName) + '.' + QUOTENAME(TS.TableName) + '--WHERE --GROUP BY --HAVING --ORDER BY' AS [SelectTable]
    ,'SELECT ' + QUOTENAME(TS.TableName) + '.' + QUOTENAME(TS.ColumnName) + ' FROM ' + QUOTENAME(DL.DbName) + '.' + QUOTENAME(TS.SchemaName) + '.' + QUOTENAME(TS.TableName) + '--WHERE --GROUP BY --HAVING --ORDER BY' AS [SelectColumn]
INTO #MappedServer
FROM [#DatabaseList] AS DL
INNER JOIN [#TableStructure] AS TS ON DL.DbName = TS.DbName
ORDER BY DL.DbName ASC
    ,TS.SchemaName ASC
    ,TS.TableName ASC
    ,TS.ColumnName ASC

/*
HOUSE KEEPING
*/
IF OBJECT_ID('tempdb..#DatabaseList') IS NOT NULL
    DROP TABLE #DatabaseList;

IF OBJECT_ID('tempdb..#TableStructure') IS NOT NULL
    DROP TABLE #TableStructure;

SELECT *
FROM #ErrorTable;

IF OBJECT_ID('tempdb..#ErrorTable') IS NOT NULL
    DROP TABLE #ErrorTable;

/*
THE DATA RETURNED CAN NOW BE EXPORTED TO EXCEL
USING A FILTERED SEARCH WILL NOW MAKE FINDING FIELDS A VERY EASY PROCESS
*/
SELECT ServerName
    ,DbName
    ,SchemaName
    ,TableName
    ,ColumnName
    ,KeyType
    ,BracketedColumn
    ,BracketedTableAndColumn
    ,SelectColumn
    ,SelectTable
FROM #MappedServer
ORDER BY DbName ASC
    ,SchemaName ASC
    ,TableName ASC
    ,ColumnName ASC;

What is the equivalent of bigint in C#?

if you are using bigint in your database table, you can use Long in C#

Best way to check if a drop down list contains a value?

That will return an item. Simply change to:

if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)
    ddlCustomerNumber.SelectedIndex = 0;

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

In SnackbarContentWrapper you need to change

<IconButton
          key="close"
          aria-label="Close"
          color="inherit"
          className={classes.close}
          onClick={onClose}
        >

to

<IconButton
          key="close"
          aria-label="Close"
          color="inherit"
          className={classes.close}
          onClick={() => onClose}
        >

so that it only fires the action when you click.

Instead, you could just curry the handleClose in SingInContainer to

const handleClose = () => (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

It's the same.

Search text in fields in every table of a MySQL database

This is the simplest query to retrive all Columns and Tables

SELECT * FROM information_schema.`COLUMNS` C WHERE TABLE_SCHEMA = 'YOUR_DATABASE'

All the tables or those with specific string in name could be searched via Search tab in phpMyAdmin.

Have Nice Query... \^.^/

Convert a SQL Server datetime to a shorter date format

For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)

How do I get countifs to select all non-blank cells in Excel?

I find that the best way to do this is to use SUMPRODUCT instead:

=SUMPRODUCT((A1:A10<>"")*1)

It's also pretty great if you want to throw in more criteria:

=SUMPRODUCT((A1:A10<>"")*(A1:A10>$B$1)*(A1:A10<=$B$2))

Open-Source Examples of well-designed Android Applications?

All of the applications delivered with Android (Calendar, Contacts, Email, etc) are all open-source, but not part of the SDK. The source for those projects is here: https://android.googlesource.com/ (look at /platform/packages/apps). I've referred to those sources several times when I've used an application on my phone and wanted to see how a particular feature was implemented.

encrypt and decrypt md5

As already stated, you cannot decrypt MD5 without attempting something like brute force hacking which is extremely resource intensive, not practical, and unethical.

However you could use something like this to encrypt / decrypt passwords/etc safely:

$input = "SmackFactory";

$encrypted = encryptIt( $input );
$decrypted = decryptIt( $encrypted );

echo $encrypted . '<br />' . $decrypted;

function encryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return( $qEncoded );
}

function decryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return( $qDecoded );
}

Using a encypted method with a salt would be even safer, but this would be a good next step past just using a MD5 hash.

Initialize a string variable in Python: "" or None?

For lists or dicts, the answer is more clear, according to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values use None as default parameter.

But also for strings, a (empty) string object is instanciated at runtime for the keyword parameter.

The cleanest way is probably:

def myfunc(self, my_string=None):
    self.my_string = my_string or "" # or a if-else-branch, ...

Hashmap holding different data types as values for instance Integer, String and Object

Do simply like below....

HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put(yourKey+"message","message");
yourHash.put(yourKey+"timestamp",timestamp);
yourHash.put(yourKey+"count ",count);
yourHash.put(yourKey+"version ",version);

typecast the value while getting back. For ex:

    int count = Integer.parseInt(yourHash.get(yourKey+"count"));
//or
int count = Integer.valueOf(yourHash.get(yourKey+"count"));
//or
int count = (Integer)yourHash.get(yourKey+"count"); //or (int)

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

How to view the stored procedure code in SQL Server Management Studio

exec sp_helptext 'your_sp_name' -- don't forget the quotes

In management studio by default results come in grid view. If you would like to see it in text view go to:

Query --> Results to --> Results to Text

or CTRL + T and then Execute.

Android Studio Run/Debug configuration error: Module not specified

I had the same issue after update on Android Studio 3.2.1 I had to re-import project, after that everything works

How to define Singleton in TypeScript

Add the following 6 lines to any class to make it "Singleton".

class MySingleton
{
    private constructor(){ /* ... */}
    private static _instance: MySingleton;
    public static getInstance(): MySingleton
    {
        return this._instance || (this._instance = new this());
    };
}

Test example:

var test = MySingleton.getInstance(); // will create the first instance
var test2 = MySingleton.getInstance(); // will return the first instance
alert(test === test2); // true

[Edit]: Use Alex answer if you prefer to get the instance through a property rather a method.

How to create a new database after initally installing oracle database 11g Express Edition?

If you wish to create a new schema in XE, you need to create an USER and assign its privileges. Follow these steps:

  • Open the SQL*Plus Command-line
SQL> connect sys as sysdba
  • Enter the password
SQL> CREATE USER myschema IDENTIFIED BY Hga&dshja;
SQL> ALTER USER myschema QUOTA unlimited ON SYSTEM;
SQL> GRANT CREATE SESSION, CONNECT, RESOURCE, DBA TO myschema;
SQL> GRANT ALL PRIVILEGES TO myschema;

Now you can connect via Oracle SQL Developer and create your tables.

JVM property -Dfile.encoding=UTF8 or UTF-8?

[INFO] BUILD SUCCESS
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
Anyway, it works for me:)

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

I added the jenkins user to root group and restarted the jenkins and it started working.

sudo usermod -a -G root jenkins
sudo service jenkins restart

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

How do I grep for all non-ASCII characters?

The easy way is to define a non-ASCII character... as a character that is not an ASCII character.

LC_ALL=C grep '[^ -~]' file.xml

Add a tab after the ^ if necessary.

Setting LC_COLLATE=C avoids nasty surprises about the meaning of character ranges in many locales. Setting LC_CTYPE=C is necessary to match single-byte characters — otherwise the command would miss invalid byte sequences in the current encoding. Setting LC_ALL=C avoids locale-dependent effects altogether.

Why cannot cast Integer to String in java?

Objects can be converted to a string using the toString() method:

String myString = myIntegerObject.toString();

There is no such rule about casting. For casting to work, the object must actually be of the type you're casting to.

Changing capitalization of filenames in Git

You can open the ".git" directory and then edit the "config" file. Under "[core]" set, set "ignorecase = true" and you are done ;)

Table 'mysql.user' doesn't exist:ERROR

'Error Code: 1046'. 

This error shows that the table does not exist may sometimes be caused by having selected a different database and running a query referring to another table. The results indicates 'No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar'. Will solve the issue and it worked for me very well.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")

This should be

compile("org.springframework.boot:spring-boot-starter-tomcat")

Javascript sleep/delay/wait function

You will have to use a setTimeout so I see your issue as

I have a script that is generated by PHP, and so am not able to put it into two different functions

What prevents you from generating two functions in your script?

function fizz() {
    var a;
    a = 'buzz';
    // sleep x desired
    a = 'complete';
}

Could be rewritten as

function foo() {
    var a; // variable raised so shared across functions below
    function bar() { // consider this to be start of fizz
        a = 'buzz';
        setTimeout(baz, x); // start wait
    } // code split here for timeout break
    function baz() { // after wait
        a = 'complete';
    } // end of fizz
    bar(); // start it
}

You'll notice that a inside baz starts as buzz when it is invoked and at the end of invocation, a inside foo will be "complete".

Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER seconds you echo a setTimeout, end the function and start a new function to pick up where you left off.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

How to change pivot table data source in Excel?

Be a bit wary of any solution that doesn't involve re-creating the PivotTable from scratch. It is possible for your pivot fields' option names to get out of sync with the values they present to the database.

For example, in one workbook I'm dealing with involving demographic data, if you try to select the "20-24" age band option, Excel actually presents you with the figures for ages 25-29. It doesn't tell you it's doing this, of course.

See below for a programmatic (VBA) approach to the problem that solves this issue among others. I think it's fairly complete/robust, but I don't use PivotTables much so would appreciate feedback.

Sub SwapSources()

strOldSource = "2010 Data"
strNewSource = "2009 Data"

Dim tmpArrOut

For Each wsh In ThisWorkbook.Worksheets
    For Each pvt In wsh.PivotTables
        tmpArrIn = pvt.SourceData
        ' row 1 of SourceData is the connection string.
        ' rows 2+ are the SQL code broken down into 255-byte chunks.
        ' we need to concatenate rows 2+, replace, and then split them up again

        strSource1 = tmpArrIn(LBound(tmpArrIn))
        strSource2 = ""
        For ii = LBound(tmpArrIn) + 1 To UBound(tmpArrIn)
            strSource2 = strSource2 & tmpArrIn(ii)
        Next ii

        strSource1 = Replace(strSource1, strOldSource, strNewSource)
        strSource2 = Replace(strSource2, strOldSource, strNewSource)

        ReDim tmpArrOut(1 To Int(Len(strSource2) / 255) + 2)
        tmpArrOut(LBound(tmpArrOut)) = strSource1
        For ii = LBound(tmpArrOut) + 1 To UBound(tmpArrOut)
            tmpArrOut(ii) = Mid(strSource2, 255 * (ii - 2) + 1, 255)
        Next ii

        ' if the replacement SQL is invalid, the PivotTable object will throw an error
        Err.Clear
        On Error Resume Next
            pvt.SourceData = tmpArrOut
        On Error GoTo 0
        If Err.Number <> 0 Then
            MsgBox "Problems changing SQL for table " & wsh.Name & "!" & pvt.Name
            pvt.SourceData = tmpArrIn ' revert
        ElseIf pvt.RefreshTable <> True Then
            MsgBox "Problems refreshing table " & wsh.Name & "!" & pvt.Name
        Else
            ' table is now refreshed
            ' need to ensure that the "display name" for each pivot option matches
            ' the actual value that will be fed to the database.  It is possible for
            ' these to get out of sync.
            For Each pvf In pvt.PivotFields
                'pvf.Name = pvf.SourceName
                If Not IsError(pvf.SourceName) Then ' a broken field may have no SourceName
                    mismatches = 0
                    For Each pvi In pvf.PivotItems
                        If pvi.Name <> pvi.SourceName Then
                            mismatches = mismatches + 1
                            pvi.Name = "_mismatch" & CStr(mismatches)
                        End If
                    Next pvi
                    If mismatches > 0 Then
                        For Each pvi In pvf.PivotItems
                            If pvi.Name <> pvi.SourceName Then
                                pvi.Name = pvi.SourceName
                            End If
                        Next
                    End If
                End If
            Next pvf
        End If
    Next pvt
Next wsh

End Sub

How can I configure Logback to log different levels for a logger to different destinations?

The simplest solution is to use ThresholdFilter on the appenders:

    <appender name="..." class="...">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>

Full example:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <target>System.err</target>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <root>
        <appender-ref ref="STDOUT" />
        <appender-ref ref="STDERR" />
    </root>
</configuration>

Update: As Mike pointed out in the comment, messages with ERROR level are printed here both to STDOUT and STDERR. Not sure what was the OP's intent, though. You can try Mike's answer if this is not what you wanted.

How to pass a type as a method parameter in Java

You could pass a Class<T> in.

private void foo(Class<?> cls) {
    if (cls == String.class) { ... }
    else if (cls == int.class) { ... }
}

private void bar() {
    foo(String.class);
}

Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo() and two concrete implementations implementing foo() and then just call foo() on the implementation you've at hand. Another way may be a Map<Class<?>, Action> which you could call by actions.get(cls). This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo().

How to navigate a few folders up?

Maybe you could use a function if you want to declare the number of levels and put it into a function?

private String GetParents(Int32 noOfLevels, String currentpath)
{
     String path = "";
     for(int i=0; i< noOfLevels; i++)
     {
         path += @"..\";
     }
     path += currentpath;
     return path;
}

And you could call it like this:

String path = this.GetParents(4, currentpath);

Illegal string offset Warning PHP

i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable

How do I test which class an object is in Objective-C?

You also can use

NSString *className = [[myObject class] description]; 

on any NSObject

Change project name on Android Studio

Here's what I did in Android Studio Beta (0.8.14)

  1. Changed the package name manually in the manifest file
  2. Navigated to build -> source -> r -> release and drilled down until I found R.java
  3. Selected the file and pressed F6 to rename
  4. Then from the Build menu selected Make Project
  5. Clicked the first error and pressed Shift+F6 on the package name and renamed which updated all my source files
  6. Selected my project name in Android Studio, right clicked -> Refactor -> Rename and changed the name there too.
  7. Next went to app -> build.gradle and updated my applicationId
  8. Navigate to .idea -> .name file and rename your Android Studio project in there too
  9. Just to clean up I deleted the old package folder inside build -> source -> r -> release

And vola, my package name has now changed and builds successfully.

How to secure phpMyAdmin

In newer versions of phpMyAdmin access permissions for user-names + ip-addresses can be set up inside the phpMyAdmin's config.inc.php file. This is a much better and more robust method of restricting access (over hard-coding URLs and IP addresses into Apache's httpd.conf).

Here is a full example of how to switch to white-listing all users (no one outside this list will be allowed access), and also how to restrict user root to the local system and network only.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
$cfg['Servers'][$i]['AllowDeny']['rules'] = array(
    'deny % from all', // deny everyone by default, then -

    'allow % from 127.0.0.1', // allow all local users
    'allow % from ::1',

    //'allow % from SERVER_ADDRESS', // allow all from server IP

    // allow user:root access from these locations (local network)
    'allow root from localhost',
    'allow root from 127.0.0.1',
    'allow root from 10.0.0.0/8',
    'allow root from 172.16.0.0/12',
    'allow root from 192.168.0.0/16',

    'allow root from ::1',

    // add more usernames and their IP (or IP ranges) here -    
    );

Source: How to Install and Secure phpMyAdmin on localhost for Windows

This gives you much more fine-grained access restrictions than Apache's URL permissions or an .htaccess file can provide, at the MySQL user name level.

Make sure that the user you are login in with, has its MySQL Host: field set to 127.0.0.1 or ::1, as phpMyAdmin and MySQL are on the same system.

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

How to change max_allowed_packet size

For anyone running MySQL on Amazon RDS service, this change is done via parameter groups. You need to create a new PG or use an existing one (other than the default, which is read-only).

You should search for the max_allowed_packet parameter, change its value, and then hit save.

Back in your MySQL instance, if you created a new PG, you should attach the PG to your instance (you may need a reboot). If you changed a PG that was already attached to your instance, changes will be applied without reboot, to all your instances that have that PG attached.

C - function inside struct

You can pass the struct pointer to function as function argument. It called pass by reference.

If you modify something inside that pointer, the others will be updated to. Try like this:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;
};

pno AddClient(client_t *client)
{
        /* this will change the original client value */
        client.password = "secret";
}

int main()
{
    client_t client;

    //code ..

    AddClient(&client);
}

SQL Joins Vs SQL Subqueries (Performance)?

Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:

I have a table with 50000 elements, the result i was looking for was 739 elements.

My query at first was this:

SELECT  p.id,
    p.fixedId,
    p.azienda_id,
    p.categoria_id,
    p.linea,
    p.tipo,
    p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
    SELECT MAX(p2.anno) 
    FROM prodotto p2 
    WHERE p2.fixedId = p.fixedId 
)

and it took 7.9s to execute.

My query at last is this:

SELECT  p.id,
    p.fixedId,
    p.azienda_id,
    p.categoria_id,
    p.linea,
    p.tipo,
    p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
    SELECT p2.fixedId, MAX(p2.anno)
    FROM prodotto p2
    WHERE p.azienda_id = p2.azienda_id
    GROUP BY p2.fixedId
)

and it took 0.0256s

Good SQL, good.

CSS checkbox input styling

Classes also work well, such as:

<style>
  form input .checkbox
  {
    /* your checkbox styling */
  }
</style>

<form>
  <input class="checkbox" type="checkbox" />
</form>

How can I bind a background color in WPF/XAML?

The Background property expects a Brush object, not a string. Change the type of the property to Brush and initialize it thus:

Background = new SolidColorBrush(Colors.Red);

Open a PDF using VBA in Excel

WOW... In appreciation, I add a bit of code that I use to find the path to ADOBE

Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _
    (ByVal lpFile As String, _
     ByVal lpDirectory As String, _
     ByVal lpResult As String) As Long

and call this to find the applicable program name

Public Function GetFileAssociation(ByVal sFilepath As String) As String
Dim i               As Long
Dim E               As String
    GetFileAssociation = "File not found!"
    If Dir(sFilepath) = vbNullString Or sFilepath = vbNullString Then Exit Function
    GetFileAssociation = "No association found!"
    E = String(260, Chr(0))
    i = FindExecutable(sFilepath, vbNullString, E)
    If i > 32 Then GetFileAssociation = Left(E, InStr(E, Chr(0)) - 1)
End Function

Thank you for your code, which isn't EXACTLY what I wanted, but can be adapted for me.

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

What's the difference between setWebViewClient vs. setWebChromeClient?

WebViewClient provides the following callback methods, with which you can interfere in how WebView makes a transition to the next content.

void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)

WebChromeClient provides the following callback methods, with which your Activity or Fragment can update the surroundings of WebView.

Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)

How do I prevent site scraping?

Your best option is unfortunately fairly manual: Look for traffic patterns that you believe are indicative of scraping and ban their IP addresses.

Since you're talking about a public site then making the site search-engine friendly will also make the site scraping-friendly. If a search-engine can crawl and scrape your site then an malicious scraper can as well. It's a fine-line to walk.

How to establish a connection pool in JDBC?

In the app server we use where I work (Oracle Application Server 10g, as I recall), pooling is handled by the app server. We retrieve a javax.sql.DataSource using a JNDI lookup with a javax.sql.InitialContext.

it's done something like this

try {     
   context = new InitialContext();
   jdbcURL = (DataSource) context.lookup("jdbc/CachedDS");
   System.out.println("Obtained Cached Data Source ");
}
catch(NamingException e)   
{  
    System.err.println("Error looking up Data Source from Factory: "+e.getMessage());
}

(We didn't write this code, it's copied from this documentation.)

How To Upload Files on GitHub

I didn't find the above answers sufficiently explicit, and it took me some time to figure it out for myself. The most useful page I found was: http://www.lockergnome.com/web/2011/12/13/how-to-use-github-to-contribute-to-open-source-projects/

I'm on a Unix box, using the command line. I expect this will all work on a Mac command line. (Mac or Window GUI looks to be available at desktop.github.com but I haven't tested this, and don't know how transferable this will be to the GUI.)

Step 1: Create a Github account Step 2: Create a new repository, typically with a README and LICENCE file created in the process. Step 3: Install "git" software. (Links in answers above and online help at github should suffice to do these steps, so I don't provide detailed instructions.) Step 4: Tell git who you are:

git config --global user.name "<NAME>"
git config --global user.email "<email>"

I think the e-mail must be one of the addresses you have associated with the github account. I used the same name as I used in github, but I think (not sure) that this is not required. Optionally you can add caching of credentials, so you don't need to type in your github account name and password so often. https://help.github.com/articles/caching-your-github-password-in-git/

Create and navigate to some top level working directory:

mkdir <working>
cd <working>

Import the nearly empty repository from github:

git clone https://github.com/<user>/<repository>

This might ask for credentials (if github repository is not 'public'.) Move to directory, and see what we've done:

cd <repository>
ls -a
git remote -v

(The 'ls' and 'git remote' commands are optional, they just show you stuff) Copy the 10000 files and millions of lines of code that you want to put in the repository:

cp -R <path>/src .
git status -s

(assuming everything you want is under a directory named "src".) (The second command again is optional and just shows you stuff)

Add all the files you just copied to git, and optionally admire the the results:

git add src
git status -s

Commit all the changes:

git commit -m "<commit comment>"

Push the changes

git push origin master

"Origin" is an alias for your github repository which was automatically set up by the "git clone" command. "master" is the branch you are pushing to. Go look at github in your browser and you should see all the files have been added.

Optionally remove the directory you did all this in, to reclaim disk space:

cd ..
rm -r <working>

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

Search for executable files using find command

So if you actually want to find executable file types (e.g. scripts, ELF binaries etc.. etc..) not merely files with execution permission then you probably want to do something more like this (where the current directory . can be replaced with whatever directory you want):

 gfind . -type f -exec bash -c '[[ $(file -b "'{}'") == *" executable "* ]] ' \; -print

Or for those of you who aren't using macports (linux users) or otherwise have gnu find installed as find you want:

 find . -type f -exec bash -c '[[ $(file -b "'{}'") == *" executable "* ]] ' \; -print

Though if you are on OS X it comes with a little utility hidden somewhere called is_exec that basically bundles up that little test for you so you can shorten the command line if you find it. But this way is more flexible as you can easily replace the == test with the =~ test and use it to check for more complex properties like executable plain text files or whatever other info your file command returns.


The exact rules for quotation here are pretty opaque so I just end up working it out by trial and error but I'd love to hear the right explanation.

Basic authentication for REST API using spring restTemplate

Reference Spring Boot's TestRestTemplate implementation as follows:

https://github.com/spring-projects/spring-boot/blob/v1.2.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/test/TestRestTemplate.java

Especially, see the addAuthentication() method as follows:

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}

Similarly, you can make your own RestTemplate easily

by inheritance like TestRestTemplate as follows:

https://github.com/izeye/samples-spring-boot-branches/blob/rest-and-actuator-with-security/src/main/java/samples/springboot/util/BasicAuthRestTemplate.java

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

We were getting this issue even after updating to the latest Adobe Reader version.

Two different methods solved this issue for us:

  • Using the free version of Foxit Reader application in place of Adobe Reader
  • But, since most of our clients use Adobe Reader, so instead of requiring users to use Foxit Reader, we started using window.open(url) to open the pdf instead of window.location.href = url. Adobe was losing the file handle on for some reason in different iframes when the pdf was opened using the window.location.href method.

gpg decryption fails with no secret key error

I was trying to use aws-vault which uses pass and gnugp2 (gpg2). I'm on Ubuntu 20.04 running in WSL2.

I tried all the solutions above, and eventually, I had to do one more thing -

$ rm ~/.gnupg/S.*                    # remove cache
$ gpg-connect-agent reloadagent /bye # restart gpg agent
$ export GPG_TTY=$(tty)              # prompt for password
# ^ This last line should be added to your ~/.bashrc file

The source of this solution is from some blog-post in Japanese, luckily there's Google Translate :)

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

how to instanceof List<MyType>?

You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List

What is difference between Lightsail and EC2?

Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/

enter image description here

Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/

Amazon EC2 vs Amazon Lightsail (comparison on point )

  • Web Performances
  • Plans
  • Features and Usability enter image description here

Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail

MySQL add days to a date

SET date = DATE_ADD( fieldname, INTERVAL 2 DAY )

How can I extract audio from video with ffmpeg?

Seems like you're extracting audio from a video file & downmixing to stereo channel.
To just extract audio (without re-encoding):

ffmpeg.exe -i in.mp4 -vn -c:a copy out.m4a

To extract audio & downmix to stereo (without re-encoding):

ffmpeg.exe -i in.mp4 -vn -c:a copy -ac 2 out.m4a

To generate an mp3 file, you'd re-encode audio:

ffmpeg.exe -i in.mp4 -vn -ac 2 out.mp3

How do I remove all .pyc files from a project?

Further, people usually want to remove all *.pyc, *.pyo files and __pycache__ directories recursively in the current directory.

Command:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

Combine two tables that have no common fields

Joining Non-Related Tables

enter image description here

Demo SQL Script

IF OBJECT_ID('Tempdb..#T1') IS NOT NULL  DROP TABLE #T1;

CREATE TABLE #T1 (T1_Name VARCHAR(75));

INSERT INTO #T1 (T1_Name) VALUES ('Animal'),('Bat'),('Cat'),('Duet');

SELECT * FROM #T1;

IF OBJECT_ID('Tempdb..#T2') IS NOT NULL  DROP TABLE #T2;

CREATE TABLE #T2 (T2_Class VARCHAR(10));

INSERT INTO #T2 (T2_Class) VALUES ('Z'),('T'),('H'); 

SELECT * FROM #T2;

To Join Non-Related Tables , we are going to introduce one common joining column of Serial Numbers like below.

SQL Script

SELECT T1.T1_Name,ISNULL(T2.T2_Class,'') AS T2_Class FROM
( SELECT T1_Name,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T1) T1
LEFT JOIN
( SELECT T2_Class,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T2) T2
ON t1.S_NO=T2.S_NO;

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

MySQL skip first 10 results

There is an OFFSET as well that should do the trick:

SELECT column FROM table
LIMIT 10 OFFSET 10

How to vertically center content with variable height within a div?

This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.

It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table method because table elements don’t obey the max-height property.

_x000D_
_x000D_
.block {_x000D_
  height: 300px;_x000D_
  text-align: center;_x000D_
  background: #c0c0c0;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.block::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -0.25em; /* Adjusts for spacing */_x000D_
_x000D_
  /* For visualization _x000D_
  background: #808080; width: 5px;_x000D_
  */_x000D_
}_x000D_
_x000D_
.centered {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  width: 300px;_x000D_
  padding: 10px 15px;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  background: #f5f5f5;_x000D_
}
_x000D_
<div class="block">_x000D_
    <div class="centered">_x000D_
        <h1>Some text</h1>_x000D_
        <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
           shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
           towards that ship a while ago?"</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python Requests and persistent sessions

Save only required cookies and reuse them.

import os
import pickle
from urllib.parse import urljoin, urlparse

login = '[email protected]'
password = 'secret'
# Assuming two cookies are used for persistent login.
# (Find it by tracing the login process)
persistentCookieNames = ['sessionId', 'profileId']
URL = 'http://example.com'
urlData = urlparse(URL)
cookieFile = urlData.netloc + '.cookie'
signinUrl = urljoin(URL, "/signin")
with requests.Session() as session:
    try:
        with open(cookieFile, 'rb') as f:
            print("Loading cookies...")
            session.cookies.update(pickle.load(f))
    except Exception:
        # If could not load cookies from file, get the new ones by login in
        print("Login in...")
        post = session.post(
            signinUrl,
            data={
                'email': login,
                'password': password,
            }
        )
        try:
            with open(cookieFile, 'wb') as f:
                jar = requests.cookies.RequestsCookieJar()
                for cookie in session.cookies:
                    if cookie.name in persistentCookieNames:
                        jar.set_cookie(cookie)
                pickle.dump(jar, f)
        except Exception as e:
            os.remove(cookieFile)
            raise(e)
    MyPage = urljoin(URL, "/mypage")
    page = session.get(MyPage)

Cannot ping AWS EC2 instance

When pinging two systems, by default SSH is enabled (if you have connected via putty or terminal.) To allow ping, I added the security group for each of the instance (inbound).

enter image description here

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Best practice for using assert?

Both the use of assert and the raising of exceptions are about communication.

  • Assertions are statements about the correctness of code addressed at developers: An assertion in the code informs readers of the code about conditions that have to be fulfilled for the code being correct. An assertion that fails at run-time informs developers that there is a defect in the code that needs fixing.

  • Exceptions are indications about non-typical situations that can occur at run-time but can not be resolved by the code at hand, addressed at the calling code to be handled there. The occurence of an exception does not indicate that there is a bug in the code.

Best practice

Therefore, if you consider the occurence of a specific situation at run-time as a bug that you would like to inform the developers about ("Hi developer, this condition indicates that there is a bug somewhere, please fix the code.") then go for an assertion. If the assertion checks input arguments of your code, you should typically add to the documentation that your code has "undefined behaviour" when the input arguments violate that conditions.

If instead the occurrence of that very situation is not an indication of a bug in your eyes, but instead a (maybe rare but) possible situation that you think should rather be handled by the client code, raise an exception. The situations when which exception is raised should be part of the documentation of the respective code.

Is there a performance [...] issue with using assert

The evaluation of assertions takes some time. They can be eliminated at compile time, though. This has some consequences, however, see below.

Is there a [...] code maintenance issue with using assert

Normally assertions improve the maintainability of the code, since they improve readability by making assumptions explicit and during run-time regularly verifying these assumptions. This will also help catching regressions. There is one issue, however, that needs to be kept in mind: Expressions used in assertions should have no side-effects. As mentioned above, assertions can be eliminated at compile time - which means that also the potential side-effects would disappear. This can - unintendedly - change the behaviour of the code.

Clearing coverage highlighting in Eclipse

Close the IDE and open it again. This works if you did not use any code coverage tools and have just clicked the basic "Coverage" icon in the IDE.

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

Set type for function parameters?

Use typeof or instanceof:

const assert = require('assert');

function myFunction(Date myDate, String myString)
{
    assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
    assert( myDate instanceof Date,         'Error message about incorrect arg type');
}

In what cases do I use malloc and/or new?

Always use new in C++. If you need a block of untyped memory, you can use operator new directly:

void *p = operator new(size);
   ...
operator delete(p);

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Open a file with Notepad in C#

You need System.Diagnostics.Process.Start().

The simplest example:

Process.Start("notepad.exe", fileName);

More Generic Approach:

Process.Start(fileName);

The second approach is probably a better practice as this will cause the windows Shell to open up your file with it's associated editor. Additionally, if the file specified does not have an association, it'll use the Open With... dialog from windows.

Note to those in the comments, thankyou for your input. My quick n' dirty answer was slightly off, i've updated the answer to reflect the correct way.

How to fix "containing working copy admin area is missing" in SVN?

First of all checkout the project into your system in a folder. Then remove the .svn folder from conflict project and copy the .svn folder from new checkout folder and paste into your working copy folder. Then problem is solved.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

Go through this and remove corresponding cache files in selected db then after you can drop your database

First find Your MySQL Data Directory Containing Your selected DB

Linux

  • Open up MySQL's configuration file: less /etc/my.cnf
  • Search for the term "datadir": /datadir

  • If it exists, it will highlight a line that reads: datadir = [path]

  • You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.

  • If that line does not exist, then MySQL will default to: /var/lib/mysql.

Windows 1. Open up MySQL's configuration file into Notepad: my.ini

The my.ini will be located in the MySQL program folder, which would be wherever it got installed. If you did not install MySQL, then use the Windows "search" feature to look for my.ini. You could also manually search for it by browsing to [drive]:\Program Files\MySQL\MySQL Server 5.5.

  1. Do a search in Notepad to find the term "datadir".

  2. If it exists, it will highlight a line that reads: datadir = [path]

  3. You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.

  4. If that line does not exist, then you'll probably find it under [drive]:\ProgramData\MySQL\MySQL Server 5.5\data.

NOTE: The "ProgramData" folder may be hidden. You may have to type the explicit path into Windows Explore

Axios Delete request with body and headers?

axios.delete is passed a url and an optional configuration.

axios.delete(url[, config])

The fields available to the configuration can include the headers.

This makes it so that the API call can be written as:

const headers = {
  'Authorization': 'Bearer paperboy'
}
const data = {
  foo: 'bar'
}

axios.delete('https://foo.svc/resource', {headers, data})

Get class name of object as string in Swift

In my case String(describing: self) returned something like:

< My_project.ExampleViewController: 0x10b2bb2b0>

But I'd like to have something like getSimpleName on Android.

So I've created a little extension:

extension UIViewController {

    func getSimpleClassName() -> String {
        let describing = String(describing: self)
        if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
            let afterDotIndex = describing.index(after: dotIndex)
            if(afterDotIndex < commaIndex) {
                return String(describing[afterDotIndex ..< commaIndex])
            }
        }
        return describing
    }

}

And now it returns:

ExampleViewController

Extending NSObject instead of UIViewController should also work. Function above is also fail-safe :)

Align labels in form next to input

I use something similar to this:

<div class="form-element">
  <label for="foo">Long Label</label>
  <input type="text" name="foo" id="foo" />
</div>

Style:

.form-element label {
    display: inline-block;
    width: 150px;
}

Entity Framework Core add unique constraint code-first

None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.

In the instance below I want to ensure the OutletRef field is unique:

public class ApplicationDbContext : IdentityDbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Outlet>()
                .HasIndex(o => new { o.OutletRef });
        }
    }

This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.

Are static class variables possible in Python?

One special thing to note about static properties & instance properties, shown in the example below:

class my_cls:
  my_prop = 0

#static property
print my_cls.my_prop  #--> 0

#assign value to static property
my_cls.my_prop = 1 
print my_cls.my_prop  #--> 1

#access static property thru' instance
my_inst = my_cls()
print my_inst.my_prop #--> 1

#instance property is different from static property 
#after being assigned a value
my_inst.my_prop = 2
print my_cls.my_prop  #--> 1
print my_inst.my_prop #--> 2

This means before assigning the value to instance property, if we try to access the property thru' instance, the static value is used. Each property declared in python class always has a static slot in memory.

Install Windows Service created in Visual Studio

You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".

It won't install right out of the box... you need to create the installer class first.

Some reference on service installer:

How to: Add Installers to Your Service Application

Quite old... but this is what I am talking about:

Windows Services in C#: Adding the Installer (part 3)

By doing this, a ProjectInstaller.cs will be automaticaly created. Then you can double click this, enter the designer, and configure the components:

  • serviceInstaller1 has the properties of the service itself: Description, DisplayName, ServiceName and StartType are the most important.

  • serviceProcessInstaller1 has this important property: Account that is the account in which the service will run.

For example:

this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

Try this..Add this in your page

<style>
textarea
{
width:100%;
}
</style>

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

SQL Server IN vs. EXISTS Performance

To optimize the EXISTS, be very literal; something just has to be there, but you don't actually need any data returned from the correlated sub-query. You're just evaluating a Boolean condition.

So:

WHERE EXISTS (SELECT TOP 1 1 FROM Base WHERE bx.BoxID = Base.BoxID AND [Rank] = 2)

Because the correlated sub-query is RBAR, the first result hit makes the condition true, and it is processed no further.

How do I center align horizontal <UL> menu?

This works for me. If I haven't misconstrued your question, you might give it a try.

_x000D_
_x000D_
    div#centerDiv {_x000D_
        width: 100%;_x000D_
        text-align: center;_x000D_
        border: 1px solid red;_x000D_
    }_x000D_
    ul.centerUL {_x000D_
        margin: 2px auto;_x000D_
        line-height: 1.4;_x000D_
        padding-left: 0;_x000D_
    }_x000D_
    .centerUL li {_x000D_
        display: inline;_x000D_
        text-align: center;_x000D_
    }
_x000D_
<div id="centerDiv">_x000D_
    <ul class="centerUL">_x000D_
        <li><a href="http://www.amazon.com">Amazon 1</a>&nbsp;&nbsp;</li>_x000D_
        <li><a href="http://www.amazon.com">Amazon 2</a>&nbsp;&nbsp;</li>_x000D_
        <li><a href="http://www.amazon.com">Amazon 3</a></li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Better way to right align text in HTML Table

You could use the nth-child pseudo-selector. For example:

table.align-right-3rd-column td:nth-child(3)
{
  text-align: right;
}

Then in your table do:

<table class="align-right-3rd-column">
  <tr>
    <td></td><td></td><td></td>
    ...
  </tr>
</table>

Edit:

Unfortunately, this only works in Firefox 3.5. However, if your table only has 3 columns, you could use the sibling selector, which has much better browser support. Here's what the style sheet would look like:

table.align-right-3rd-column td + td + td
{
  text-align: right;
}

This will match any column preceded by two other columns.

Executing multiple commands from a Windows cmd script

Note that you don't need semicolons in batch files. And the reason why you need to use call is that mvn itself is a batch file and batch files need to call each other with call, otherwise control does not return to the caller.

Can I apply multiple background colors with CSS3?

Yes its possible! and you can use as many colors and images as you desire, here is the right way:

_x000D_
_x000D_
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image:  _x000D_
/* 1) An image              */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient              */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position        */ 0 0, _x000D_
/* 2) Gradient position     */ 0 100px,_x000D_
/* 3) Color position        */ 0 130px;_x000D_
_x000D_
background-size:  _x000D_
/* 1) Image size            */ 640px 100px,_x000D_
/* 2) Gradient size         */ 100% 30px, _x000D_
/* 3) Color size            */ 100% 30px;_x000D_
}
_x000D_
_x000D_
_x000D_

super() in Java

As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.

This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .

If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.

Here is an example of this:

class A {
    A() {
    System.out.println("Constructor A");
    }
}

class B extends A{

    public B() {
    System.out.println("Constructor B");
    }
}

class C extends B{ 

    public C() {
    System.out.println("Constructor C");
    }

    public static void main(String[] args) {
    C c1 = new C();
    }
} 

The above would output:

Constructor A
Constructor B
Constructor C

Python string prints as [u'String']

Do you really mean u'String'?

In any event, can't you just do str(string) to get a string rather than a unicode-string? (This should be different for Python 3, for which all strings are unicode.)

How can I get the assembly file version

UPDATE: As mentioned by Richard Grimes in my cited post, @Iain and @Dmitry Lobanov, my answer is right in theory but wrong in practice.

As I should have remembered from countless books, etc., while one sets these properties using the [assembly: XXXAttribute], they get highjacked by the compiler and placed into the VERSIONINFO resource.

For the above reason, you need to use the approach in @Xiaofu's answer as the attributes are stripped after the signal has been extracted from them.


public static string GetProductVersion()
{
  var attribute = (AssemblyVersionAttribute)Assembly
    .GetExecutingAssembly()
    .GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
    .Single();
   return attribute.InformationalVersion;
}

(From http://bytes.com/groups/net/420417-assemblyversionattribute - as noted there, if you're looking for a different attribute, substitute that into the above)

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

How to find the Number of CPU Cores via .NET/C#?

There are many answers here already, but some have heavy upvotes and are incorrect.

The .NET Environment.ProcessorCount WILL return incorrect values and can fail critically if your system WMI is configured incorrectly.

If you want a RELIABLE way to count the cores, the only way is Win32 API.

Here is a C++ snippet:

#include <Windows.h>
#include <vector>

int num_physical_cores()
{
    static int num_cores = []
    {
        DWORD bytes = 0;
        GetLogicalProcessorInformation(nullptr, &bytes);
        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> coreInfo(bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
        GetLogicalProcessorInformation(coreInfo.data(), &bytes);

        int cores = 0;
        for (auto& info : coreInfo)
        {
            if (info.Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }();
    return num_cores;
}

And since this is a .NET C# Question, here's the ported version:

[StructLayout(LayoutKind.Sequential)]
struct CACHE_DESCRIPTOR
{
    public byte Level;
    public byte Associativity;
    public ushort LineSize;
    public uint Size;
    public uint Type;
}

[StructLayout(LayoutKind.Explicit)]
struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
{
    [FieldOffset(0)] public byte ProcessorCore;
    [FieldOffset(0)] public uint NumaNode;
    [FieldOffset(0)] public CACHE_DESCRIPTOR Cache;
    [FieldOffset(0)] private UInt64 Reserved1;
    [FieldOffset(8)] private UInt64 Reserved2;
}

public enum LOGICAL_PROCESSOR_RELATIONSHIP
{
    RelationProcessorCore,
    RelationNumaNode,
    RelationCache,
    RelationProcessorPackage,
    RelationGroup,
    RelationAll = 0xffff
}

struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
{
    public UIntPtr ProcessorMask;
    public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
    public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
}

[DllImport("kernel32.dll")]
static extern unsafe bool GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer, out int bufferSize);

static unsafe int GetProcessorCoreCount()
{
    GetLogicalProcessorInformation(null, out int bufferSize);
    int numEntries = bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    var coreInfo = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[numEntries];

    fixed (SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pCoreInfo = coreInfo)
    {
        GetLogicalProcessorInformation(pCoreInfo, out bufferSize);
        int cores = 0;
        for (int i = 0; i < numEntries; ++i)
        {
            ref SYSTEM_LOGICAL_PROCESSOR_INFORMATION info = ref pCoreInfo[i];
            if (info.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }
}

public static readonly int NumPhysicalCores = GetProcessorCoreCount();

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)

print(result)

Output:

                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

Adding a guideline to the editor in Visual Studio

For those who use Visual Assist, vertical guidelines can be enabled from Display section in Visual Assist's options:

enter image description here

Android Studio - Unable to find valid certification path to requested target

jcenter() equals to https://bintray.com/bintray/jcenter

You need import jcenter's cerficate into your java keystore.

Steps:

  1. Visit jcenter using your browser and export the certificate as .crt file. (lock icon on the left of Firefox address bar, or Chrome developer tool secuity tab)
  2. Download this tool and run it.
  3. Select "Open an existing KeyStore" button to open JDKPATH/jre/lib/security/cacerts, the password is "changeit"
  4. Use the "Import Trusted Certificate" button to import the .crt file, then save and exist

If you are behind proxy, in gradle.properties, besides setting

systemProp.http.proxyHost and systemProp.http.proxyPort

also set

systemProp.https.proxyHost and systemProp.https.proxyPort

By now it should be fine.

Can I bind an array to an IN() condition?

As I know there is no any possibility to bind an array into PDO statement.

But exists 2 common solutions:

  1. Use Positional Placeholders (?,?,?,?) or Named Placeholders (:id1, :id2, :id3)

    $whereIn = implode(',', array_fill(0, count($ids), '?'));

  2. Quote array earlier

    $whereIn = array_map(array($db, 'quote'), $ids);

Both options are good and safe. I prefer second one because it's shorter and I can var_dump parameters if I need it. Using placeholders you must bind values and in the end your SQL code will be the same.

$sql = "SELECT * FROM table WHERE id IN ($whereIn)";

And the last and important for me is avoiding error "number of bound variables does not match number of tokens"

Doctrine it's great example of using positional placeholders, only because it has internal control over incoming parameters.

Can't accept license agreement Android SDK Platform 24

For me I was Building the Ionic using "ionic build android" command and I was getting the same problem! The solution was simply

  • To install the required sdk
  • Run the same command in CMD must be as administrater

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub