Programs & Examples On #Flops

FLOPS (FLoating point Operations Per Second): a unit of measurement used to quantify the performance of the implementation of a numerical algorithm.

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

anaconda - path environment variable in windows

To export the exact set of paths used by Anaconda, use the command echo %PATH% in Anaconda Prompt. This is needed to avoid problems with certain libraries such as SSL.

Reference: https://stackoverflow.com/a/54240362/663028

Maven2 property that indicates the parent directory

Try setting a property in each pom to find the main project directory.

In the parent:

<properties>
    <main.basedir>${project.basedir}</main.basedir>
</properties>

In the children:

<properties>
    <main.basedir>${project.parent.basedir}</main.basedir>
</properties>

In the grandchildren:

<properties>
    <main.basedir>${project.parent.parent.basedir}</main.basedir>
</properties>

How to run JUnit test cases from the command line

If your project is Maven-based you can run all test-methods from test-class CustomTest which belongs to module 'my-module' using next command:

mvn clean test -pl :my-module -Dtest=CustomTest

Or run only 1 test-method myMethod from test-class CustomTest using next command:

mvn clean test -pl :my-module -Dtest=CustomTest#myMethod

For this ability you need Maven Surefire Plugin v.2.7.3+ and Junit 4. More details is here: http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html

How to implement static class member functions in *.cpp file?

The #include directive literally means "copy all the data in that file to this spot." So when you include the header file, it's textually within the code file, and everything in it will be there, give or take the effect of other directives or macro replacements, when the code file (now called the compilation unit or translation unit) is handed off from the preprocessor module to the compiler module.

Which means the declaration and definition of your static member function were really in the same file all along...

What is the best way to test for an empty string with jquery-out-of-the-box?

Try executing this in your browser console or in a node.js repl.

var string = ' ';
string ? true : false;
//-> true

string = '';
string ? true : false;
//-> false

Therefore, a simple branching construct will suffice for the test.

if(string) {
    // string is not empty
}

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

Add System.IO.Compression.ZipFile as nuget reference it is working

How to check empty object in angular 2 template using *ngIf

From the above answeres, following did not work or less preferable:

  • (previous_info | json) != '{}' works only for {} empty case, not for null or undefined case
  • Object.getOwnPropertyNames(previous_info).length also did not work, as Object is not accessible in the template
  • I would not like to create a dedicated variable this.objectLength = Object.keys(this.previous_info).length !=0;
  • I would not like to create a dedicated function

    isEmptyObject(obj) {
       return (obj && (Object.keys(obj).length === 0));
    }
    

Solution: keyvalue pipe along with ?. (safe navigation operator); and it seems simple.

It works well when previous_info = null or previous_info = undefined or previous_info = {} and treats as falsy value.

<div  *ngIf="(previous_info | keyvalue)?.length">

keyvalue - Transforms Object or Map into an array of key value pairs.

?. - The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined

DEMO: demo with angular 9, though it works for previous versions as well

Java array reflection: isArray vs. instanceof

In most cases, you should use the instanceof operator to test whether an object is an array.

Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[] or an int[]. You'd want to guard your casts with instanceof:

if (obj instanceof Integer[]) {
    Integer[] array = (Integer[]) obj;
    /* Use the boxed array */
} else if (obj instanceof int[]) {
    int[] array = (int[]) obj;
    /* Use the primitive array */
} else ...

At the JVM level, the instanceof operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.

In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray() method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.

There are two special cases: null references and references to primitive arrays.

A null reference will cause instanceof to result false, while the isArray throws a NullPointerException.

Applied to a primitive array, the instanceof yields false unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray() will return true for any component type.

How to re-enable right click so that I can inspect HTML elements in Chrome?

Open inspect mode before navigating to the page. It worked.hehe

How to write :hover condition for a:before and a:after?

Write a:hover::before instead of a::before:hover: example.

What is a unix command for deleting the first N characters of a line?

You can use cut:

cut -c N- file.txt > new_file.txt

-c: characters

file.txt: input file

new_file.txt: output file

N-: Characters from N to end to be cut and output to the new file.

Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.

This will perform the operation to each line of the input file.

Remove local git tags that are no longer on the remote repository

How about this - drop all local tags and then re-fetch? Considering your repo might contain submodules:

git submodule foreach --recursive  'git tag | xargs git tag -d'
(alternatively, "for i in `find .git  -type d -name '*tags*'`; do rm -f $i/*;  done")
git fetch -t
git submodule foreach --recursive git fetch -t

PHP "pretty print" json_encode

Here's a function to pretty up your json: pretty_json

How to hide columns in HTML table?

You can also hide a column using the col element https://developer.mozilla.org/en/docs/Web/HTML/Element/col

To hide the second column in a table:

<table>
  <col />
  <col style="visibility:collapse"/>
  <tr><td>visible</td><td>hidden</td></tr>
  <tr><td>visible</td><td>hidden</td></tr>

Known issues: this won't work in Google Chrome. Please vote for the bug at https://bugs.chromium.org/p/chromium/issues/detail?id=174167

Executing an EXE file using a PowerShell script

It looks like you're specifying both the EXE and its first argument in a single string e.g; '"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode'. This won't work. In general you invoke a native command that has a space in its path like so:

& "c:\some path with spaces\foo.exe" <arguments go here>

That is & expects to be followed by a string that identifies a command: cmdlet, function, native exe relative or absolute path.

Once you get just this working:

& "c:\some path with spaces\foo.exe"

Start working on quoting of the arguments as necessary. Although it looks like your arguments should be just fine (no spaces, no other special characters interpreted by PowerShell).

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

import android packages cannot be resolved

try this in eclipse: Window - Preferences - Android - SDK Location and setup SDK path

Add resources, config files to your jar using gradle

I came across this post searching how to add an extra directory for resources. I found a solution that may be useful to someone. Here is my final configuration to get that:

sourceSets {
    main {
        resources {
            srcDirs "src/main/resources", "src/main/configs"
        }
    }
}

Quadratic and cubic regression in Excel

You need to use an undocumented trick with Excel's LINEST function:

=LINEST(known_y's, [known_x's], [const], [stats])

Background

A regular linear regression is calculated (with your data) as:

=LINEST(B2:B21,A2:A21)

which returns a single value, the linear slope (m) according to the formula:

enter image description here

which for your data:

enter image description here

is:

enter image description here

Undocumented trick Number 1

You can also use Excel to calculate a regression with a formula that uses an exponent for x different from 1, e.g. x1.2:

enter image description here

using the formula:

=LINEST(B2:B21, A2:A21^1.2)

which for you data:

enter image description here

is:

enter image description here

You're not limited to one exponent

Excel's LINEST function can also calculate multiple regressions, with different exponents on x at the same time, e.g.:

=LINEST(B2:B21,A2:A21^{1,2})

Note: if locale is set to European (decimal symbol ","), then comma should be replaced by semicolon and backslash, i.e. =LINEST(B2:B21;A2:A21^{1\2})

Now Excel will calculate regressions using both x1 and x2 at the same time:

enter image description here

How to actually do it

The impossibly tricky part there's no obvious way to see the other regression values. In order to do that you need to:

  • select the cell that contains your formula:

    enter image description here

  • extend the selection the left 2 spaces (you need the select to be at least 3 cells wide):

    enter image description here

  • press F2

  • press Ctrl+Shift+Enter

    enter image description here

You will now see your 3 regression constants:

  y = -0.01777539x^2 + 6.864151123x + -591.3531443

Bonus Chatter

I had a function that I wanted to perform a regression using some exponent:

y = m×xk + b

But I didn't know the exponent. So I changed the LINEST function to use a cell reference instead:

=LINEST(B2:B21,A2:A21^F3, true, true)

With Excel then outputting full stats (the 4th paramter to LINEST):

enter image description here

I tell the Solver to maximize R2:

enter image description here

And it can figure out the best exponent. Which for you data:

enter image description here

is:

enter image description here

ModuleNotFoundError: What does it mean __main__ is not a package?

Just use the name of the main folder which the .py file is in.

from problem_set_02.p_02_paying_debt_off_in_a_year import compute_balance_after

Expanding tuples into arguments

myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.

PHP Unset Session Variable

unset is a function, not an operator. Use it like unset($_SESSION['key']); to unset that session key. You can, however, use session_destroy(); as well. (Make sure to start the session with session_start(); as well)

How to vertically align into the center of the content of a div with defined width/height?

I have researched this a little and from what I have found you have four options:

Version 1: Parent div with display as table-cell

If you do not mind using the display:table-cell on your parent div, you can use of the following options:

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:table-cell;
    vertical-align:middle;
}?

Live DEMO


Version 2: Parent div with display block and content display table-cell

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:block;
}

.content {
    height: 100px;
    width: 100px;
    display:table-cell;
    vertical-align:middle;    
}?

Live DEMO


Version 3: Parent div floating and content div as display table-cell

.area{
    background: red;
    margin:10px;
    text-align: center;
    display:block;
    float: left;
}

.content {
    display:table-cell;
    vertical-align:middle;
    height: 100px;
    width: 100px;
}?

Live DEMO


Version 4: Parent div position relative with content position absolute

The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.

.area{
    position:relative; 
    display:block;
    height:100px;
    width:100px;
    border:1px solid black;
    background:red;
    margin:10px;
}

.content { 
    position:absolute;
    top:50%; 
    height:50%; 
    width:100px;
    margin-top:-25%;
    text-align:center;
}?

Live DEMO

How to show an empty view with a RecyclerView?

On your adapter's getItemViewType check if the adapter has 0 elements and return a different viewType if so.

Then on your onCreateViewHolder check if the viewType is the one you returned earlier and inflate a diferent view. In this case a layout file with that TextView

EDIT

If this is still not working then you might want to set the size of the view programatically like this:

Point size = new Point();
((WindowManager)itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(size);

And then when you inflate your view call:

inflatedView.getLayoutParams().height = size.y;
inflatedView.getLayoutParams().width = size.x;

How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

Word wrap for a label in Windows Forms

If you are entering text into the label beforehand, you can do this.

  1. In the designer, Right-Click on the label and click Properties.
  2. In Properties, search for text tab.
  3. Click in the tab and click on the arrow button next to it.
  4. A box will popup on top of it.
  5. You can press enter in the popup box to add lines and type as in notepad! (PRESS ENTER WHERE YOU WANT TO WRAP THE LABEL TEXT)

Binding arrow keys in JS/jQuery

With coffee & Jquery

  $(document).on 'keydown', (e) ->
    switch e.which
      when 37 then console.log('left key')
      when 38 then console.log('up key')
      when 39 then console.log('right key')
      when 40 then console.log('down key')
    e.preventDefault()

How to Populate a DataTable from a Stored Procedure

Use the SqlDataAdapter, this would simplify everything.

//Your code to this point
DataTable dt = new DataTable();

using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
  using(var da = new SqlDataAdapter(cmd))
  {
      da.Fill(dt):
  }
}

and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had this error and the other fixes didn't help me, but changing the CPU type the emulator used did get it working.

Create a new emulator and try using mips or arm for the cpu selection

Redirect using AngularJS

Check your routing method:

if your routing state is like this

 .state('app.register', {
    url: '/register',
    views: {
      'menuContent': {
        templateUrl: 'templates/register.html',
      }
    }
  }) 

then you should use

$location.path("/app/register");

Using Keras & Tensorflow with AMD GPU

One can use AMD GPU via the PlaidML Keras backend.

Fastest: PlaidML is often 10x faster (or more) than popular platforms (like TensorFlow CPU) because it supports all GPUs, independent of make and model. PlaidML accelerates deep learning on AMD, Intel, NVIDIA, ARM, and embedded GPUs.

Easiest: PlaidML is simple to install and supports multiple frontends (Keras and ONNX currently)

Free: PlaidML is completely open source and doesn't rely on any vendor libraries with proprietary and restrictive licenses.

For most platforms, getting started with accelerated deep learning is as easy as running a few commands (assuming you have Python (v2 or v3) installed):

virtualenv plaidml
source plaidml/bin/activate
pip install plaidml-keras plaidbench

Choose which accelerator you'd like to use (many computers, especially laptops, have multiple):

plaidml-setup

Next, try benchmarking MobileNet inference performance:

plaidbench keras mobilenet

Or, try training MobileNet:

plaidbench --batch-size 16 keras --train mobilenet

To use it with keras set

os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"

For more information

https://github.com/plaidml/plaidml

https://github.com/rstudio/keras/issues/205#issuecomment-348336284

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

Show/hide widgets in Flutter programmatically

Invisible: The widget takes physical space on the screen but not visible to user.

Gone: The widget doesn't take any physical space and is completely gone.


Invisible example

Visibility(
  child: Text("Invisible"),
  maintainSize: true, 
  maintainAnimation: true,
  maintainState: true,
  visible: false, 
),

Gone example

Visibility(
  child: Text("Gone"),
  visible: false,
),

Alternatively, you can use if condition for both invisible and gone.

Column(
  children: <Widget>[
    if (show) Text("This can be visible/not depending on condition"),
    Text("This is always visible"),
  ],
) 

How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

How to count days between two dates in PHP?

If you want to know the number of days (if any), the number of hours (if any), minutues (if any) and seconds, you can do the following:

$previousTimeStamp = strtotime("2011/07/01 21:12:34");
$lastTimeStamp = strtotime("2013/09/17 12:34:11");

$menos=$lastTimeStamp-$previousTimeStamp;

$mins=$menos/60;
if($mins<1){
$showing= $menos . " seconds ago";
}
else{
$minsfinal=floor($mins);
$secondsfinal=$menos-($minsfinal*60);
$hours=$minsfinal/60;
if($hours<1){
$showing= $minsfinal . " minutes and " . $secondsfinal. " seconds ago";

}
else{
$hoursfinal=floor($hours);
$minssuperfinal=$minsfinal-($hoursfinal*60);
$days=$hoursfinal/24;
if($days<1){
$showing= $hoursfinal . "hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";

}
else{
$daysfinal=floor($days);
$hourssuperfinal=$hoursfinal-($daysfinal*24);
$showing= $daysfinal. "days, " .$hourssuperfinal . " hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";
}}}

echo $showing;

You could use the same logic if you want to add months and years.

JavaScript string with new line - but not using \n

I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.

The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).

Angular 5 ngHide ngShow [hidden] not working

Your [hidden] will work but you need to check the css:

<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden" />

And the css:

[hidden] {
  display: none !important;
}

That should work as you want.

How to calculate the CPU usage of a process by PID in Linux from C?

I wrote two little C function based on cafs answer to calculate the user+kernel cpu usage of of an process: https://github.com/fho/code_snippets/blob/master/c/getusage.c

pow (x,y) in Java

^ is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You're using the wrong post parameters:

    var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
                      ^^^^-$_POST['name']
                                       ^^^^--$_POST['name']
                                      etc....

The javascript/html IDs are irrelevant to the actual POST, especially when you're building your own data string and don't use those same IDs.

Query to get the names of all tables in SQL Server 2008 Database

To get the fields info too, you can use the following:

SELECT TABLE_SCHEMA, TABLE_NAME, 
       COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema") 
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION

Order discrete x scale by frequency/value

Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

When running as root, sudo doesn't ask for a password.

Java: Sending Multiple Parameters to Method

Suppose you have void method that prints many objects;

public static void print( Object... values){
   for(Object c : values){
      System.out.println(c);
   }
}

Above example I used vararge as an argument that accepts values from 0 to N.

From comments: What if 2 strings and 5 integers ??

Answer:

print("string1","string2",1,2,3,4,5);

How do I escape ampersands in batch files?

You can enclose it in quotes, if you supply a dummy first argument.

Note that you need to supply a dummy first argument in this case, as start will treat the first argument as a title for the new console windows, if it is quoted. So the following should work (and does here):

start "" "http://www.google.com/search?client=opera&rls=en&q=escape+ampersand&sourceid=opera&ie=utf-8&oe=utf-8"

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Try writting the lambda with the same conditions as the delegate. like this:

  List<AnalysisObject> analysisObjects = 
    analysisObjectRepository.FindAll().Where(
    (x => 
       (x.ID == packageId)
    || (x.Parent != null && x.Parent.ID == packageId)
    || (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
    ).ToList();

No plot window in matplotlib

If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.

Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.

H.264 file size for 1 hr of HD video

Around 4gb/hr is quite common.

Vertical Align text in a Label

_x000D_
_x000D_
label {_x000D_
        padding: 10px 0;_x000D_
        position: relative;_x000D_
    }
_x000D_
_x000D_
_x000D_

Add some padding-top and padding-bottom instead of height.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Let's go in reverse order:

  • Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch statement. You know that an error has occurred and therefore you're logging an error.

  • Log.w: Use this when you suspect something shady is going on. You may not be completely in full on error mode, but maybe you recovered from some unexpected behavior. Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind of like a "hey, this happened, and it's weird, we should look into it."

  • Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.

  • Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so you can log the exact flow of your program, use this. If you want to keep a log of variable values, use this.

  • Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason you've decided to log every little thing in a particular part of your app, use the Log.v tag.

And as a bonus...

  • Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those catch blocks where you're catching errors that you never should get...yeah, if you wanna log them use Log.wtf

How to pass arguments to Shell Script through docker run

Another option...

To make this works

docker run -d --rm $IMG_NAME "bash:command1&&command2&&command3"

in dockerfile

ENTRYPOINT ["/entrypoint.sh"]

in entrypoint.sh

#!/bin/sh

entrypoint_params=$1
printf "==>[entrypoint.sh] %s\n" "entry_point_param is $entrypoint_params"

PARAM1=$(echo $entrypoint_params | cut -d':' -f1) # output is 1 must be 'bash' it     will be tested    
PARAM2=$(echo $entrypoint_params | cut -d':' -f2) # the real command separated by     &&

printf "==>[entrypoint.sh] %s\n" "PARAM1=$PARAM1"
printf "==>[entrypoint.sh] %s\n" "PARAM2=$PARAM2"

if [ "$PARAM1" = "bash" ];
then
    printf "==>[entrypoint.sh] %s\n" "about to running $PARAM2 command"
    echo $PARAM2 | tr '&&' '\n' | while read cmd; do
        $cmd
    done    
fi

Find the number of downloads for a particular app in apple appstore

Updated answer now that xyo.net has been bought and shut down.

appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!

Outdated answer:

Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!

xyo.net

Check if a time is between two times (time DataType)

select *
from MyTable
where CAST(Created as time) not between '07:00' and '22:59:59 997'

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

How can I remove an entry in global configuration with git config?

You can check all the config settings using

git config --global --list

You can remove the setting for example username

git config --global --unset user.name

You can edit the configuration or remove the config setting manually by hand using:

git config --global --edit 

Convert Pandas column containing NaNs to dtype `int`

The lack of NaN rep in integer columns is a pandas "gotcha".

The usual workaround is to simply use floats.

WCF Service , how to increase the timeout?

The best way is to change any setting you want in your code.

Check out the below example:

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}

Inputting a default image in case the src attribute of an html <img> is not valid?

I don't think it is possible using just HTML. However using javascript this should be doable. Bassicly we loop over each image, test if it is complete and if it's naturalWidth is zero then that means that it not found. Here is the code:

fixBrokenImages = function( url ){
    var img = document.getElementsByTagName('img');
    var i=0, l=img.length;
    for(;i<l;i++){
        var t = img[i];
        if(t.naturalWidth === 0){
            //this image is broken
            t.src = url;
        }
    }
}

Use it like this:

 window.onload = function() {
    fixBrokenImages('example.com/image.png');
 }

Tested in Chrome and Firefox

"Parser Error Message: Could not load type" in Global.asax

I encountered this error message and eventually discovered that the error message was misleading. In my case there appears to have been a routing issue in IIS which caused the global.asax from another site on the web server to be read thus generating the error.

In IIS, my site was bound to http:*80:webservices.local and contained an application called MyAPI. I received the dreaded message when calling the MyAPI application using the web server's ip address.

In order to successfully call my application I had to add a host file entry for webservices.local on all of the machines that called the MyAPI application. Then all of my requests had to be prefixed with http://webservices.local/MyAPI/ in order to route correctly.

How do I create a new branch?

In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.

Passing data between view controllers

I prefer to make it without delegates and segues. It can be done with custom init or by setting optional values.

1. Custom init

class ViewControllerA: UIViewController {
  func openViewControllerB() {
    let viewController = ViewControllerB(string: "Blabla", completionClosure: { success in
      print(success)
    })
    navigationController?.pushViewController(animated: true)
  }
}

class ViewControllerB: UIViewController {
  private let completionClosure: ((Bool) -> Void)
  init(string: String, completionClosure: ((Bool) -> Void)) {
    self.completionClosure = completionClosure
    super.init(nibName: nil, bundle: nil)
    title = string
  }

  func finishWork() {
    completionClosure()
  }
}

2. Optional vars

class ViewControllerA: UIViewController {
  func openViewControllerB() {
    let viewController = ViewControllerB()
    viewController.string = "Blabla"
    viewController.completionClosure = { success in
      print(success)
    }
    navigationController?.pushViewController(animated: true)
  }
}

class ViewControllerB: UIViewController {
  var string: String? {
    didSet {
      title = string
    }
  }
  var completionClosure: ((Bool) -> Void)?

  func finishWork() {
    completionClosure?()
  }
}

How to write a file with C in Linux?

First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE* sourceFile;
    FILE* destFile;
    char buf[50];
    int numBytes;

    if(argc!=3)
    {
        printf("Usage: fcopy source destination\n");
        return 1;
    }

    sourceFile = fopen(argv[1], "rb");
    destFile = fopen(argv[2], "wb");

    if(sourceFile==NULL)
    {
        printf("Could not open source file\n");
        return 2;
    }
    if(destFile==NULL)
    {
        printf("Could not open destination file\n");
        return 3;
    }

    while(numBytes=fread(buf, 1, 50, sourceFile))
    {
        fwrite(buf, 1, numBytes, destFile);
    }

    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

EDIT: The glibc reference has this to say:

In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).

If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

Post an object as data using Jquery Ajax

[object Object] This means somewhere the object is being converted to a string.

Converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product + ''); 

Not converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product);

How can I disable a tab inside a TabControl?

You could register the "Selecting" event and cancel the navigation to the tab page:

private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPage == tabPage2)
        e.Cancel = true;
}

Another idea is to put all the controls on the tabpage in a Panel control and disable the panel! Smiley

You could also remove the tabpage from the tabControl1.TabPages collection. That would hide the tabpage.

Credits go to littleguru @ Channel 9.

How to clear a notification in Android

Actually as answered before starting with API Level 18 you can cancel Notifications posted by other apps differet than your own using NotificationListenerService but that approach will no longer work on Lollipop, here is the way to remove notifications covering also Lillipop API.

if (Build.VERSION.SDK_INT < 21) {
    cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
else {
    cancelNotification(sbn.getKey());
}

T-SQL CASE Clause: How to specify WHEN NULL

Use the CONCAT function available in SQL Server 2012 onward.

SELECT CONCAT([FirstName], ' , ' , [LastName]) FROM YOURTABLE

How can I update my ADT in Eclipse?

I had the same problem where there's no files under Generated Java files, BuildConfig and R.java were missing. The automatic build option is not generating.
In Eclipse under Project, uncheck Build Automatically. Then under Project select Build Project. You may need to fix the projec

How to convert float to int with Java

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

How do you migrate an IIS 7 site to another server?

In my case, the files were already copied, I found the easiest way to follow the steps in this guide: https://www.ryadel.com/en/exporting-importing-app-pools-and-websites-configuration-between-multiple-iis-instances/

I exported AppPools/Websites, copied the xml files to the destination server and Imported AppPools then Websites. Worked very well. This is also another excellent option for this question.

How can I create directory tree in C++/Linux?

Here is my example of code (it works for both Windows and Linux):

#include <iostream>
#include <string>
#include <sys/stat.h> // stat
#include <errno.h>    // errno, ENOENT, EEXIST
#if defined(_WIN32)
#include <direct.h>   // _mkdir
#endif

bool isDirExist(const std::string& path)
{
#if defined(_WIN32)
    struct _stat info;
    if (_stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & _S_IFDIR) != 0;
#else 
    struct stat info;
    if (stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & S_IFDIR) != 0;
#endif
}

bool makePath(const std::string& path)
{
#if defined(_WIN32)
    int ret = _mkdir(path.c_str());
#else
    mode_t mode = 0755;
    int ret = mkdir(path.c_str(), mode);
#endif
    if (ret == 0)
        return true;

    switch (errno)
    {
    case ENOENT:
        // parent didn't exist, try to create it
        {
            int pos = path.find_last_of('/');
            if (pos == std::string::npos)
#if defined(_WIN32)
                pos = path.find_last_of('\\');
            if (pos == std::string::npos)
#endif
                return false;
            if (!makePath( path.substr(0, pos) ))
                return false;
        }
        // now, try to create again
#if defined(_WIN32)
        return 0 == _mkdir(path.c_str());
#else 
        return 0 == mkdir(path.c_str(), mode);
#endif

    case EEXIST:
        // done!
        return isDirExist(path);

    default:
        return false;
    }
}

int main(int argc, char* ARGV[])
{
    for (int i=1; i<argc; i++)
    {
        std::cout << "creating " << ARGV[i] << " ... " << (makePath(ARGV[i]) ? "OK" : "failed") << std::endl;
    }
    return 0;
}

Usage:

$ makePath 1/2 folderA/folderB/folderC
creating 1/2 ... OK
creating folderA/folderB/folderC ... OK

SmartGit Installation and Usage on Ubuntu

Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

Using app.config in .Net Core

I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.

Breaking this down to a simple answer for .Net core 3.1:

  • add/ensure nuget package: System.Configuration.ConfigurationManager to project
  • add your app.config(xml) to project.

If it is a MSTest project:

  • rename file in project to testhost.dll.config

    OR

  • Use post-build command provided by DeepSpace101

How to identify and switch to the frame in selenium webdriver when frame does not have id

Make sure you switch to default content before switching to frame:

driver.switchTo().defaultContent();
driver.switchTo().frame(x);

x can be the frame number or you can do a driver.findlement and use any of the options you have available eg: driver.findElementByName("Name").

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

What is meant by immutable?

Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed

Consider bellow example,

class Testimmutablestring{  
  public static void main(String args[]){  
    String s="Future";  
    s.concat(" World");//concat() method appends the string at the end  
    System.out.println(s);//will print Future because strings are immutable objects  
  }  
 }  

Let's get idea considering bellow diagram,

enter image description here

In this diagram, you can see new object created as "Future World". But not change "Future".Because String is immutable. s, still refer to "Future". If you need to call "Future World",

String s="Future";  
s=s.concat(" World");  
System.out.println(s);//print Future World

Why are string objects immutable in java?

Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "Future".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Insert Update trigger how to determine if insert or update

DECLARE @ActionType CHAR(6);
SELECT  @ActionType = COALESCE(CASE WHEN EXISTS(SELECT * FROM INSERTED)
                                     AND EXISTS(SELECT * FROM DELETED)  THEN 'UPDATE' END,
                               CASE WHEN EXISTS(SELECT * FROM DELETED)  THEN 'DELETE' END,
                               CASE WHEN EXISTS(SELECT * FROM INSERTED) THEN 'INSERT' END);
PRINT   @ActionType;

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Finding local maxima/minima with Numpy in a 1D numpy array

If you are looking for all entries in the 1d array a smaller than their neighbors, you can try

numpy.r_[True, a[1:] < a[:-1]] & numpy.r_[a[:-1] < a[1:], True]

You could also smooth your array before this step using numpy.convolve().

I don't think there is a dedicated function for this.

Path to Powershell.exe (v 2.0)

I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version (Determine installed PowerShell version) shows it's 2.0.

Another option is type $PSVersionTable at the command prompt. If you are running v2.0, the output will be:

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

If you're running version 1.0, the variable doesn't exist and there will be no output.

Localization PowerShell version 1.0, 2.0, 3.0, 4.0:

  • 64 bits version: C:\Windows\System32\WindowsPowerShell\v1.0\
  • 32 bits version: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

How to get everything after last slash in a URL?

extracted_url = url[url.rfind("/")+1:];

Print commit message of a given commit in git

It's not "plumbing", but it'll do exactly what you want:

$ git log --format=%B -n 1 <commit>

If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list:

$ git rev-list --format=%B --max-count=1 <commit>

Although rev-list will also print out the commit sha (on the first line) in addition to the commit message.

Detecting IE11 using CSS Capability/Feature Detection

You can use js and add a class in html to maintain the standard of conditional comments:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

Or use a lib like bowser:

https://github.com/ded/bowser

Or modernizr for feature detection:

http://modernizr.com/

Copy data from another Workbook through VBA

There's very little reason not to open multiple workbooks in Excel. Key lines of code are:

Application.EnableEvents = False
Application.ScreenUpdating = False

...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...

Application.DisplayAlerts = False
Application.Calculation = xlManual

...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming

If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format

Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data

An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
     If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With

FName = VBA.Dir(InputFolder)

Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop

Hopefully some of the above will be of use

ipython notebook clear cell output in code

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

Open a Web Page in a Windows Batch FIle

When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com

Also you cannot have http:// in the url.

How to set up datasource with Spring for HikariCP?

This last error is caused by the library SLF4J not being found. HikariCP has two dependencies: slf4j and javassist. BTW, HikariDataSource does have a default constructor and does not need HikariConfig, see this link. So that was never the problem.

Stop jQuery .load response from being cached

Sasha is good idea, i use a mix.

I create a function

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

And invoke for diferents parts of my page for example on init:

Init: function (actionUrl1, actionUrl2, actionUrl3) {

var ExampleJS= {

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

gcc-arm-linux-gnueabi command not found

You have installed a toolchain which was compiled for i686 on a box which is running an x86_64 userland.

Use an i686 VM.

What is the meaning of "$" sign in JavaScript

From another answer:

A little history

Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:

var $ = document.getElementById; //freedom from document.getElementById!

When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.

jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)

How to crop an image using PIL?

An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)

How to fix java.net.SocketException: Broken pipe?

The cause is that the remote peer closes its socket (crash for example), so if you try to write data to him for example, you will get this. to solve that, protect read/write to socket operations between (try catch), then manage the lose connection case into the catch (renew connection, stop program, ...etc):

 try {
      /* your code */
 } catch (SocketException e) {
      e.printStackTrace();
      /* insert your failure processings here */
 }

UL list style not applying

  • Have you tried following the rule with !important?
  • Which stylesheet does FireBug show having last control over the element?
  • Is this live somewhere to be viewed by others?

Update

I'm fairly confident that providing code-examples would help you receive a solution must faster. If you can upload an example of this issue somewhere, or provide the markup so we can test it on our localhosts, you'll have a better chance of getting some valuable input.

The problem with questions is that they lead others to believe the person asking the question has sufficient knowledge to ask the question. In programming that isn't always the case. There may have been something you missed, or accidentally jipped. Without others having eyes on your code, they have to assume you missed nothing, and overlooked nothing.

Converting a vector<int> to string

template<typename T>
string str(T begin, T end)
{
    stringstream ss;
    bool first = true;
    for (; begin != end; begin++)
    {
        if (!first)
            ss << ", ";
        ss << *begin;
        first = false;
    }
    return ss.str();
}

This is the str function that can make integers turn into a string and not into a char for what the integer represents. Also works for doubles.

Using relative URL in CSS file, what location is it relative to?

According to W3:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

Therefore, in answer to your question, it will be relative to /stylesheets/.

If you think about this, this makes sense, since the CSS file could be added to pages in different directories, so standardising it to the CSS file means that the URLs will work wherever the stylesheets are linked.

Eclipse "Invalid Project Description" when creating new project from existing source

If you wish to open a new project from an existing source code in the following way:

File -> Import -> General -> Existing Project into Workspace

you still have the message "Invalid Project Description". I solve it just by going in

File -> Switch Workspace

and choosing one of the recent workspaces.

How do I create a MongoDB dump of my database?

to export

mongodump -d <database name> <backup-folder>

to import

mongorestore -d <database name> <backup-folder>

How can I remove the outline around hyperlinks images?

Any image that has a link will have a border around the image to help indicate it is a link with older browsers. Adding border="0" to your IMG HTML tag will prevent that picture from having a border around the image.

However, adding border="0" to every image would not only be time consuming it will also increase the file size and download time. If you don't want any of your images to have a border, create a CSS rule or CSS file that has the below code in it.

img { border-style: none; }

Java constructor/method with optional parameters?

You can use varargs for optional parameters:

public class Booyah {
    public static void main(String[] args) {
        woohoo(1);
        woohoo(2, 3);
    }
    static void woohoo(int required, Integer... optional) {
        Integer lala;
        if (optional.length == 1) {
            lala = optional[0];
        } else {
            lala = 2;
        }
        System.out.println(required + lala);
    }
}

Also it's important to note the use of Integer over int. Integer is a wrapper around the primitive int, which allows one to make comparisons with null as necessary.

How to save all console output to file in R?

If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:

File: test.sh

#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"

test1=$(echo "This is a test")

echo "Here is some R code:"

Rscript --slave --no-save --no-restore - "$test1" <<EOF
  ## R code
  cat("\nHello World, this is R\n")
  args <- commandArgs(TRUE)
  bash_message<-args[1]
  cat("\nThis is a message from bash:\n")
  cat("\n",paste0(bash_message),"\n")
EOF

# end of script 

Then when you run the script with both stderr and stdout piped to a log file:

$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:

Hello World, this is R

This is a message from bash:

 This is a test

Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.

How to resolve "Could not find schema information for the element/attribute <xxx>"?

Have you tried copying the schema file to the XML Schema Caching folder for VS? You can find the location of that folder by looking at VS Tools/Options/Test Editor/XML/Miscellaneous. Unfortunately, i don't know where's the schema file for the MS Enterprise Library 4.0.

Update: After installing MS Enterprise Library, it seems there's no .xsd file. However, there's a tool for editing the configuration - EntLibConfig.exe, which you can use to edit the configuration files. Also, if you add the proper config sections to your config file, VS should be able to parse the config file properly. (EntLibConfig will add these for you, or you can add them yourself). Here's an example for the loggingConfiguration section:

<configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>

You also need to add a reference to the appropriate assembly in your project.

How to use Boost in Visual Studio 2010

A minimalist example to get you started in Visual Studio:

1.Download and unzip Boost from here.

2.Create a Visual Studio empty project, using an example boost library that does not require separate compilation:

#include <iostream>
#include <boost/format.hpp>

using namespace std;  
using namespace boost;  

int main()  
{  
    unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };  

    cout << format("%02X-%02X-%02X-%02X-%02X")  
            % arr[0]  
            % arr[1]  
            % arr[2]  
            % arr[3]  
            % arr[4]  
         << endl;  
}  

3.In your Visual Studio project properties set the Additional Include Directories:

Project Properties

For a very simple example:

How to Install the Boost Libraries in Visual Studio

If you don't want to use the entire boost library, just a subset:

Using a subset of the boost libraries in Windows

If you specifically want to now about the libraries that require compilation:

How to use the Boost compiled libraries in Windows

Command-line Unix ASCII-based charting / plotting tool

While gnuplot is powerful, it's also really irritating when you just want to pipe in a bunch of points and get a graph.

Thankfully, someone created eplot (easy plot), which handles all the nonsense for you.

It doesn't seem to have an option to force terminal graphs; I patched it like so:

--- eplot.orig  2012-10-12 17:07:35.000000000 -0700
+++ eplot       2012-10-12 17:09:06.000000000 -0700
@@ -377,6 +377,7 @@
                # ---- print the options
                com="echo '\n"+getStyleString+@oc["MiscOptions"]
                com=com+"set multiplot;\n" if doMultiPlot
+               com=com+"set terminal dumb;\n"
                com=com+"plot "+@oc["Range"]+comString+"\n'| gnuplot -persist"
                printAndRun(com)
                # ---- convert to PDF

An example of use:

[$]> git shortlog -s -n | awk '{print $1}' | eplot 2> /dev/null


  3500 ++-------+-------+--------+--------+-------+--------+-------+-------++
       +        +       +        "/tmp/eplot20121012-19078-fw3txm-0" ****** +       *                                                                    |  3000 +*                                                                  ++       |*                                                                   |       | *                                                                  |  2500 ++*                                                                 ++       | *                                                                  |
       |  *                                                                 |
  2000 ++ *                                                                ++
       |  **                                                                |
  1500 ++   ****                                                           ++
       |        *                                                           |
       |         **                                                         |
  1000 ++          *                                                       ++
       |            *                                                       |
       |            *                                                       |
   500 ++            ***                                                   ++
       |                **************                                      |
       +        +       +        +    **********  +        +       +        +
     0 ++-------+-------+--------+--------+-----***************************++
       0        5       10       15       20      25       30      35       40

Include another HTML file in a HTML file

Most of the solutions works but they have issue with jquery:

The issue is following code $(document).ready(function () { alert($("#includedContent").text()); } alerts nothing instead of alerting included content.

I write the below code, in my solution you can access to included content in $(document).ready function:

(The key is loading included content synchronously).

index.htm:

<html>
    <head>
        <script src="jquery.js"></script>

        <script>
            (function ($) {
                $.include = function (url) {
                    $.ajax({
                        url: url,
                        async: false,
                        success: function (result) {
                            document.write(result);
                        }
                    });
                };
            }(jQuery));
        </script>

        <script>
            $(document).ready(function () {
                alert($("#test").text());
            });
        </script>
    </head>

    <body>
        <script>$.include("include.inc");</script>
    </body>

</html>

include.inc:

<div id="test">
    There is no issue between this solution and jquery.
</div>

jquery include plugin on github

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Run this command :

    sudo chown -R yourUser /home/yourUser/.composer

Autoplay an audio with HTML5 embed tag while the player is invisible

For future reference to people who find this page later you can use:

<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>
</audio>

Center a button in a Linear layout

Did you try this?

  <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:background="#303030"
>
    <RelativeLayout
    android:id="@+id/widget42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    >
    <ImageButton
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="map"
    android:src="@drawable/outbox_pressed"
    android:background="@null"
    android:layout_toRightOf="@+id/location"
    />
    <ImageButton
    android:id="@+id/location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="location"
    android:src="@drawable/inbox_pressed"
    android:background="@null"
    />
    </RelativeLayout>
    <ImageButton
    android:id="@+id/home"
    android:src="@drawable/button_back"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:orientation="horizontal"
android:background="#252525"
>
    <EditText
    android:id="@+id/searchfield"
    android:layout_width="fill_parent"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:background="@drawable/customshape"
    />
    <ImageButton
    android:id="@+id/search_button"
    android:src="@drawable/search_press"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    />
</LinearLayout>
<com.google.android.maps.MapView
    android:id="@+id/mapview" 
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:clickable="true"
    android:apiKey="apikey" />

</TableLayout>

Char array in a struct - incompatible assignment?

use strncpy to make sure you have no buffer overflow.

char name[]= "whatever_you_want";
strncpy( sara.first, name, sizeof(sara.first)-1 );
sara.first[sizeof(sara.first)-1] = 0;

System.BadImageFormatException: Could not load file or assembly

My cause was different I referenced a web service then I got this message.

Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.

hope this helps!

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

How do I update a Mongo document after inserting it?

I will use collection.save(the_changed_dict) this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.:

save(to_save[, manipulate=True[, safe=False[, **kwargs]]])

Save a document in this collection.

If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

Debug JavaScript in Eclipse

MyEclipse (eclipse based, subscription required) and Webclipse (an eclipse plug-in, currently free), from my company, Genuitec, have newly engineered (as of 2015) JavaScript debugging built in:

enter image description here

You can debug both generic web applications and Node.js files.

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

XML Schema (XSD) validation tool?

I tend to use xsd from Microsoft to help generate the xsd from a .NET file. I also parse out sections of the xml using xmlstarlet. The final free tool that would be of use to you is altovaxml, which is available at this URL: http://www.altova.com/download_components.html .

This allows me to scan all the xml files picking up which xsd to use by parsing the xml.

# Function:
#    verifyschemas - Will validate all xml files in a configuration directory against the schemas in the passed in directory
# Parameters:
#    The directory where the schema *.xsd files are located.  Must be using dos pathing like: VerifySchemas "c:\\XMLSchemas\\"
# Requirements:
#    Must be in the directory where the configuration files are located
#
verifyschemas()
{
    for FILENAME in $(find . -name '*.xml' -print0 | xargs -0)
    do
        local SchemaFile=$1$(getconfignamefromxml $FILENAME).xsd
        altovaxml /validate $FILENAME /schema $SchemaFile > ~/temp.txt 2> /dev/null
        if [ $? -ne 0 ]; then
            printf "Failed to verify: "
            cat ~/temp.txt | tail -1 | tr -d '\r'
            printf "    - $FILENAME with $SchemaFile\n"
        fi
    done
}

To generate the xml I use: xsd DOTNET.dll /type:CFGCLASS & rename schema0.xsd CFGCLASS.xsd

To get the xsd name I use: xmlstarlet sel -t -m /XXX/* -v local-name() $1 | sed 's/ $//'

This allows me to pickup the correct XSD using an element tag within the xml file.

The net result is that I can call a bash function to scan all the XML files and verify them. Even if they are in multiple subdirectories.

JavaScript blob filename without link

The only way I'm aware of is the trick used by FileSaver.js:

  1. Create a hidden <a> tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the filename.
  4. Click on the <a> tag.

Here is a simplified example (jsfiddle):

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
        var json = JSON.stringify(data),
            blob = new Blob([json], {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);

I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.

Notes

  • Older browsers don't support the "download" attribute, since it's part of HTML5.
  • Some file formats are considered insecure by the browser and the download fails. Saving JSON files with txt extension works for me.

Creating a generic method in C#

What if you specified the default value to return, instead of using default(T)?

public static T GetQueryString<T>(string key, T defaultValue) {...}

It makes calling it easier too:

var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified

The downside being you need magic values to denote invalid/missing querystring values.

Parenthesis/Brackets Matching using Stack algorithm

Actually, there is no need to check any cases "manually". You can just run the following algorithm:

  1. Iterate over the given sequence. Start with an empty stack.

  2. If the current char is an opening bracket, just push it to the stack.

  3. If it's a closing bracket, check that the stack is not empty and the top element of the step is an appropriate opening bracket(that it is, matches this one). If it is not, report an error. Otherwise, pop the top element from the stack.

  4. In the end, the sequence is correct iff the stack is empty.

Why is it correct? Here is a sketch of a proof: if this algorithm reported that the sequence is corrected, it had found a matching pair of all brackets. Thus, the sequence is indeed correct by definition. If it has reported an error:

  1. If the stack was not empty in the end, the balance of opening and closing brackets is not zero. Thus, it is not a correct sequence.

  2. If the stack was empty when we had to pop an element, the balance is off again.

  3. If there was a wrong element on top of the stack, a pair of "wrong" brackets should match each other. It means that the sequence is not correct.

I have shown that:

  • If the algorithm has reported that the sequence is correct, it is correct.

  • If the algorithm has reported that the sequence is not correct, it is incorrect(note that I do not use the fact that there are no other cases except those that are mentioned in your question).

This two points imply that this algorithm works for all possible inputs.

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

How to add AUTO_INCREMENT to an existing column?

I had existing data in the first column and they were 0's. First I made the first column nullable. Then I set the data for the column to null. Then I set the column as an index. Then I made it a primary key with auto incrementing turned on. This is where I used another persons answer above:

ALTER TABLE `table_name` CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;

This Added numbers to all the rows of this table starting at one. If I ran the above code first it wasn't working because all the values were 0's. And making it an index was also required before making it auto incrementing. Next I made the column a primary key.

How to get the nth occurrence in a string?

Shorter way and I think easier, without creating unnecessary strings.

const findNthOccurence = (string, nth, char) => {
  let index = 0
  for (let i = 0; i < nth; i += 1) {
    if (index !== -1) index = string.indexOf(char, index + 1)
  }
  return index
}

Python Brute Force algorithm

Simple solution using the itertools and string modules

# modules to easily set characters and iterate over them
import itertools, string 

# character limit so you don't run out of ram
maxChar = int(input('Character limit for password: '))  

# file to save output to, so you can look over the output without using so much ram
output_file = open('insert filepath here', 'a+') 

# this is the part that actually iterates over the valid characters, and stops at the 
# character limit.
x = list(map(''.join, itertools.permutations(string.ascii_lowercase, maxChar))) 

# writes the output of the above line to a file 
output_file.write(str(x)) 

# saves the output to the file and closes it to preserve ram
output_file.close() 

I piped the output to a file to save ram, and used the input function so you can set the character limit to something like "hiiworld". Below is the same script but with a more fluid character set using letters, numbers, symbols, and spaces.

import itertools, string

maxChar = int(input('Character limit for password: '))
output_file = open('insert filepath here', 'a+')

x = list(map(''.join, itertools.permutations(string.printable, maxChar)))
x.write(str(x))
x.close()

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

use this code solve the problem:

string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Uploadfile\\" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, (int)fs.Length);
fs.Close();
Response.ContentType = "application/x-unknown/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName;+ "\"");
try
{
    if (bt != null)
    {
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
        stream1.Write(bt, 0, bt.Length);
        Response.BinaryWrite(bt);
        //Response.OutputStream.Write(bt, 0, (int)stream1.Length);
        Response.Flush();
        // Response.End();
    }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
    throw ex;
}
finally
{
    Response.End();
}

Descending order by date filter in AngularJs

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.filter("toArray", function () {_x000D_
    return function (obj) {_x000D_
        var result = [];_x000D_
        angular.forEach(obj, function (val, key) {_x000D_
            result.push(val);_x000D_
        });_x000D_
        return result;_x000D_
    };_x000D_
});_x000D_
_x000D_
_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
_x000D_
  $scope.logData = [_x000D_
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
          ]; _x000D_
        _x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
_x000D_
  <h4>Descending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
  <br>_x000D_
  _x000D_
  _x000D_
  <h4>Ascending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Password Protect a SQLite DB. Is it possible?

Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

For me the resource folder was getting excluded on a maven update/build. I went to Build Path>Source and found that src/main/resources have "Excluded **". I removed that entry (Clicked on Excluded **>Remove>Apply and Close).

Then it worked fine.

enter image description here

Separating class code into a header and cpp file

Basically a modified syntax of function declaration/definitions:

a2dd.h

class A2DD
{
private:
  int gx;
  int gy;

public:
  A2DD(int x,int y);

  int getSum();
};

a2dd.cpp

A2DD::A2DD(int x,int y)
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

How could I convert data from string to long in c#

You won't be able to convert it directly to long because of the decimal point i think you should convert it into decimal and then convert it into long something like this:

String strValue[i] = "1100.25";
long l1 = Convert.ToInt64(Convert.ToDecimal(strValue));

hope this helps!

Pandas column of lists, create a row for each list element

Very late answer but I want to add this:

A fast solution using vanilla Python that also takes care of the sample_num column in OP's example. On my own large dataset with over 10 million rows and a result with 28 million rows this only takes about 38 seconds. The accepted solution completely breaks down with that amount of data and leads to a memory error on my system that has 128GB of RAM.

df = df.reset_index(drop=True)
lstcol = df.lstcol.values
lstcollist = []
indexlist = []
countlist = []
for ii in range(len(lstcol)):
    lstcollist.extend(lstcol[ii])
    indexlist.extend([ii]*len(lstcol[ii]))
    countlist.extend([jj for jj in range(len(lstcol[ii]))])
df = pd.merge(df.drop("lstcol",axis=1),pd.DataFrame({"lstcol":lstcollist,"lstcol_num":countlist},
index=indexlist),left_index=True,right_index=True).reset_index(drop=True)

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

How to write a multidimensional array to a text file?

Use JSON module for multidimensional arrays, e.g.

import json
with open(filename, 'w') as f:
   json.dump(myndarray.tolist(), f)

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

The error "Directory 'blah/.svn' containing working copy admin area is missing" occurred when I attempted to add the directory to the repository, but did not have enough filesystem privileges to do so. The directory was not already in the repository, but it was claiming to be under version control after the failed add.

Checking out a copy of the parent directory to another location, and replacing the .svn folder in the parent dir of the working copy allowed me to add and commit the new directory successfully (after fixing the file permissions, of course).

MySQL: Set user variable from result of query

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

  1. Using keyword 'SET'.

Example :-

mysql >  SET @a = 1;
  1. Without using keyword 'SET' and using ':='.

Example:-

mysql > @a:=1;
  1. By using 'SELECT' statement.

Example:-

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1.

@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

Running Selenium Webdriver with a proxy in Python

Try setting up sock5 proxy too. I was facing the same problem and it is solved by using the socks proxy

def install_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("network.proxy.https",PROXY_HOST)
        fp.set_preference("network.proxy.https_port",int(PROXY_PORT))
        fp.set_preference("network.proxy.ssl",PROXY_HOST)
        fp.set_preference("network.proxy.ssl_port",int(PROXY_PORT))  
        fp.set_preference("network.proxy.ftp",PROXY_HOST)
        fp.set_preference("network.proxy.ftp_port",int(PROXY_PORT))   
        fp.set_preference("network.proxy.socks",PROXY_HOST)
        fp.set_preference("network.proxy.socks_port",int(PROXY_PORT))   
        fp.set_preference("general.useragent.override","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call install_proxy ( ip , port ) from your program.

JSON datetime between Python and JavaScript

Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json module. This needs Python >= 2.6 since the %f format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.

Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.

I.e. this works:

date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}

And this too:

>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]

But this doesn't work as expected:

>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']

Here's the code:

__all__ = ['dumps', 'loads']

import datetime

try:
    import json
except ImportError:
    import simplejson as json

class JSONDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

def datetime_decoder(d):
    if isinstance(d, list):
        pairs = enumerate(d)
    elif isinstance(d, dict):
        pairs = d.items()
    result = []
    for k,v in pairs:
        if isinstance(v, basestring):
            try:
                # The %f format code is only supported in Python >= 2.6.
                # For Python <= 2.5 strip off microseconds
                # v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
                #     '%Y-%m-%dT%H:%M:%S')
                v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                try:
                    v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                except ValueError:
                    pass
        elif isinstance(v, (dict, list)):
            v = datetime_decoder(v)
        result.append((k, v))
    if isinstance(d, list):
        return [x[1] for x in result]
    elif isinstance(d, dict):
        return dict(result)

def dumps(obj):
    return json.dumps(obj, cls=JSONDateTimeEncoder)

def loads(obj):
    return json.loads(obj, object_hook=datetime_decoder)

if __name__ == '__main__':
    mytimestamp = datetime.datetime.utcnow()
    mydate = datetime.date.today()
    data = dict(
        foo = 42,
        bar = [mytimestamp, mydate],
        date = mydate,
        timestamp = mytimestamp,
        struct = dict(
            date2 = mydate,
            timestamp2 = mytimestamp
        )
    )

    print repr(data)
    jsonstring = dumps(data)
    print jsonstring
    print repr(loads(jsonstring))

How to detect escape key press with pure JS or jQuery?

Pure JS

you can attach a listener to keyUp event for the document.

Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.

 document.addEventListener('keydown', (event) => {
        
        if (event.key === 'Escape') {
         //if esc key was not pressed in combination with ctrl or alt or shift
            const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
            if (isNotCombinedKey) {
                console.log('Escape key was pressed with out any group keys')
              
            }
        }
    });

Adding headers when using httpClient.GetAsync

Following the greenhoorn's answer, you can use "Extensions" like this:

  public static class HttpClientExtensions
    {
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
        {
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;
        }
    }

And use:

string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")

NSRange to Range<String.Index>

In Swift 2.0 assuming func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {:

var oldString = textfield.text!
let newRange = oldString.startIndex.advancedBy(range.location)..<oldString.startIndex.advancedBy(range.location + range.length)
let newString = oldString.stringByReplacingCharactersInRange(newRange, withString: string)

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

git recover deleted file where no commit was made after the delete

I had the same problem and none of the answers here I tried worked for me either. I am using Intellij and I had checked out a new branch git checkout -b minimalExample to create a "minimal example" on the new branch of some issue by deleting a bunch of files and modifying a bunch of others in the project. Unfortunately, even though I didn't commit any of the changes on the new "minimal example" branch, when I checked out my "original" branch again all of the changes and deletions from the "minimal example" branch had happened in the "original" branch too (or so it appeared). According to git status the deleted files were just gone from both branches.

Fortunately, even though Intellij had warned me "deleting these files may not be fully recoverable", I was able to restore them (on the minimal example branch from which they had actually been deleted) by right-clicking on the project and selecting Local History > Show History (and then Restore on the most recent history item I wanted). After Intellij restored the files in the "minimal example" branch, I pushed the branch to origin. Then I switched back to my "original" local branch and ran git pull origin minimalExample to get them back in the "original" branch too.

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

I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format

SELECT date
FROM blog 
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC 

Add content to a new open window

in parent.html:

<script type="text/javascript">
    $(document).ready(function () {
        var output = "data";
        var OpenWindow = window.open("child.html", "mywin", '');
        OpenWindow.dataFromParent = output; // dataFromParent is a variable in child.html
        OpenWindow.init();
    });
</script>

in child.html:

<script type="text/javascript">
    var dataFromParent;    
    function init() {
        document.write(dataFromParent);
    }
</script>

How to commit and rollback transaction in sql server?

As per http://msdn.microsoft.com/en-us/library/ms188790.aspx

@@ERROR: Returns the error number for the last Transact-SQL statement executed.

You will have to check after each statement in order to perform the rollback and return.

Commit can be at the end.

HTH

Space between border and content? / Border distance from content?

Its possible using pseudo element (after).
I have added to the original code a

position:relative
and some margin.
Here is the modified JSFiddle: http://jsfiddle.net/r4UAp/86/

#content{
  width: 100px;
  min-height: 100px;
  margin: 20px auto;
  border-style: ridge;
  border-color: #567498;
  border-spacing:10px;
  position:relative;
  background:#000;
}
#content:after {
  content: '';
  position: absolute;
  top: -15px;
  left: -15px;
  right: -15px;
  bottom: -15px;
  border: red 2px solid;
}

Android - How to download a file from a webserver

Starting from api level 11 or Honeycomb doing network operations on main thread is forbidden. Use thread or asynctask. For more info visit https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

In Python, can I call the main() of an imported module?

It depends. If the main code is protected by an if as in:

if __name__ == '__main__':
    ...main code...

then no, you can't make Python execute that because you can't influence the automatic variable __name__.

But when all the code is in a function, then might be able to. Try

import myModule

myModule.main()

This works even when the module protects itself with a __all__.

from myModule import * might not make main visible to you, so you really need to import the module itself.

Nginx: Job for nginx.service failed because the control process exited

In my case, it's because of apache server is running somehow. So I stop apache then restart nginx. Work like a charm!

sudo /etc/init.d/apache2 stop
sudo systemctl restart nginx

Hidden features of Windows batch files

The equivalent of the bash (and other shells)

echo -n Hello # or
echo Hello\\c

which outputs "Hello" without a trailing newline. A cmd hack to do this:

<nul set /p any-variable-name=Hello

set /p is a way to prompt the user for input. It emits the given string and then waits, (on the same line, i.e., no CRLF), for the user to type a response.

<nul simply pipes an empty response to the set /p command, so the net result is the emitted prompt string. (The variable used remains unchanged due to the empty reponse.)

Problems are: It's not possible to output a leading equal sign, and on Vista leading whitespace characters are removed, but not on XP.

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

If you want to test if an object is strictly or extends a Hash, use:

value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true

But to make value of Ruby's duck typing, you could do something like:

value = {}
value.respond_to?(:[]) #=> true

It is useful when you only want to access some value using the value[:key] syntax.

Please note that Array.new["key"] will raise a TypeError.

Python conversion from binary string to hexadecimal

bstr = '0000 0100 1000 1101'.replace(' ', '')
hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))

How to Convert Boolean to String

Why just don't do like this?:

if ($res) {
    $converted_res = "true";
}
else {
    $converted_res = "false";
}

How to remove index.php from URLs?

This may be old, but I may as well write what I've learned down. So anyway I did it this way.

---------->

Before you start, make sure the Apache rewrites module is enabled and then follow the steps below.

1) Log-in to your Magento administration area then go to System > Configuration > Web.

2) Navigate to the Unsecure and Secure tabs. Make sure the Unsecured and Secure - Base Url options have your domain name within it, and do not leave the forward slash off at the end of the URL. Example: http://www.yourdomain.co.uk/

3) While still on the Web page, navigate to Search Engine Optimisation tab and select YES underneath the Use Web Server Rewrites option.

4) Navigate to the Secure tab again (if not already on it) and select Yes on the Use Secure URLs in Front-End option.

5) Now go to the root of your Magento website folder and use this code for your .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Save the .htaccess and replace the original file. (PLEASE MAKE SURE TO BACKUP YOUR ORIGINAL .htaccess FILE BEFORE MESSING WITH IT!!!)

6) Now go to System > Cache Management and select all fields and make sure the Actions dropdown is set on Refresh, then submit. (This will of-course refresh the Cache.)

---------->

If this did not work please follow these extra steps.

7) Go to System > Configuration > web again. This time look for the Current Configuration Scope and select your website from the dropdown menu. (This is of course, it is set to Default Config)

8) Make sure the Unsecure and Secure fields contain the same domain as the previous Default Config file.

9) Navigate to the Search Engines Optimisation tab and select Yes underneath the Use Web Server Rewrites section.

10) Once the URLs are the same, and the rewrite is enabled save that page, then go back and make sure they are all checked as default, then save again if needed.

11) Repeat step 6.

Now your index.php problem should be fixed and all should be well!!!

I hope this helps, and good luck.

Nth max salary in Oracle

Refer following query for getting nth highest salary. By this way you get nth highest salary. If you want get nth lowest salary only you need to replace DESC by ASC in the query. for getting highest salary of employee.

Python ImportError: No module named wx

Just open your terminal and run this command thats for windows users pip install -U wxPython

for Ubuntu user you can use this

pip install -U \
-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
wxPython

C# equivalent to Java's charAt()?

please try to make it as a character

string str = "Tigger";
//then str[0] will return 'T' not "T"

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

X close button only using css

_x000D_
_x000D_
<div style="width: 10px; height: 10px; position: relative; display: flex; justify-content: center;">
   <div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(45deg); border-radius: 2px;"></div>
   <div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(-45deg); border-radius: 2px;"></div>
</div>
_x000D_
_x000D_
_x000D_

How to set a:link height/width with css?

From the definition of height:

Applies to: all elements but non-replaced inline elements, table columns, and column groups

An a element is, by default an inline element (and it is non-replaced).

You need to change the display (directly with the display property or indirectly, e.g. with float).

Why should you use strncpy instead of strcpy?

That depends on our requirement. For windows users

We use strncpy whenever we don't want to copy entire string or we want to copy only n number of characters. But strcpy copies the entire string including terminating null character.

These links will help you more to know about strcpy and strncpy and where we can use.

about strcpy

about strncpy

What should I set JAVA_HOME environment variable on macOS X 10.6?

As other answers note, the correct way to find the Java home directory is to use /usr/libexec/java_home.

The official documentation for this is in Apple's Technical Q&A QA1170: Important Java Directories on OS X: https://developer.apple.com/library/mac/qa/qa1170/_index.html

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

How to validate array in Laravel?

The recommended way to write validation and authorization logic is to put that logic in separate request classes. This way your controller code will remain clean.

You can create a request class by executing php artisan make:request SomeRequest.

In each request class's rules() method define your validation rules:

//SomeRequest.php
public function rules()
{
   return [
    "name"    => [
          'required',
          'array', // input must be an array
          'min:3'  // there must be three members in the array
    ],
    "name.*"  => [
          'required',
          'string',   // input must be of type string
          'distinct', // members of the array must be unique
          'min:3'     // each string must have min 3 chars
    ]
  ];
}

In your controller write your route function like this:

// SomeController.php
public function store(SomeRequest $request) 
{
  // Request is already validated before reaching this point.
  // Your controller logic goes here.
}

public function update(SomeRequest $request)
{
  // It isn't uncommon for the same validation to be required
  // in multiple places in the same controller. A request class
  // can be beneficial in this way.
}

Each request class comes with pre- and post-validation hooks/methods which can be customized based on business logic and special cases in order to modify the normal behavior of request class.

You may create parent request classes for similar types of requests (e.g. web and api) requests and then encapsulate some common request logic in these parent classes.

LINQ Join with Multiple Conditions in On Clause

You can't do it like that. The join clause (and the Join() extension method) supports only equijoins. That's also the reason, why it uses equals and not ==. And even if you could do something like that, it wouldn't work, because join is an inner join, not outer join.

Set Radiobuttonlist Selected from Codebehind

The best option, in my opinion, is to use the Value property for the ListItem, which is available in the RadioButtonList.

I must remark that ListItem does NOT have an ID property.

So, in your case, to select the second element (option2) that would be:

// SelectedValue expects a string
radio1.SelectedValue = "1"; 

Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.

// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1; 

Google Maps API: open url by clicking on marker

url isn't an object on the Marker class. But there's nothing stopping you adding that as a property to that class. I'm guessing whatever example you were looking at did that too. Do you want a different URL for each marker? What happens when you do:

for (var i = 0; i < locations.length; i++) 
{
    var flag = new google.maps.MarkerImage('markers/' + (i + 1) + '.png',
      new google.maps.Size(17, 19),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 19));
    var place = locations[i];
    var myLatLng = new google.maps.LatLng(place[1], place[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: flag,
        shape: shape,
        title: place[0],
        zIndex: place[3],
        url: "/your/url/"
    });

    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
}

How to create an empty array in Swift?

You could use

var firstNames: [String] = []

PHP - Get array value with a numeric index

$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum

How do I copy a hash in Ruby?

Since Ruby has a million ways to do it, here's another way using Enumerable:

h0 = {  "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1 = h0.inject({}) do |new, (name, value)| 
    new[name] = value;
    new 
end

Measuring code execution time

If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime Property which you can get under System.Diagnostics namespace.

TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);

Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above

Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.

Setting table column width

Don't use the border attribute, use CSS for all your styling needs.

<table style="border:1px; width:100%;">
    <tr>
            <th style="width:15%;">From</th>
            <th style="width:70%;">Subject</th>
            <th style="width:15%;">Date</th>
    </tr>
... rest of the table code...
</table>

But embedding CSS like that is poor practice - one should use CSS classes instead, and put the CSS rules in an external CSS file.

What is the error "Every derived table must have its own alias" in MySQL?

I think it's asking you to do this:

SELECT ID
FROM (SELECT ID,
             msisdn 
      FROM (SELECT * FROM TT2) as myalias
     ) as anotheralias;

But why would you write this query in the first place?

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

How to get started with Windows 7 gadgets

Here's an excellent article by Scott Allen: Developing Gadgets for the Windows Sidebar

This site, Windows 7/Vista Sidebar Gadgets, has links to many gadget resources.

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

Why an interface can not implement another interface?

Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.

GitLab remote: HTTP Basic: Access denied and fatal Authentication

There are two ways I got around this problem:

  1. I added my username to the front of the remote URL (https://username@gitRepoURL)

    • Not always the best solution; where I work, even though we're slowly moving towards using GIT, we have our applications on a network drive, so if I do this, only I can push changes even if someone else worked on a feature.
  2. I can't run git config --system --unset credential.helper from GIT Bash, so I had to open up an Admin Command Prompt and run it there (this assumes you installed GIT such that it can run from both GIT Bash and the Command Prompt). From Bash, I get a "could not lock config file" error.

How does the "position: sticky;" property work?

One of the most common mistakes when going about the position sticky is:

  1. Browser not supporting it
  2. Not including any top bottom right left properties. Bare in mind that the Browser won't know how to handle that properly if you don't give it enough information. It will be just be statically positioned without it.

I have written about that and more insides on this article. Just putting a reference so I don't repeat myself too much.

'str' object has no attribute 'decode'. Python 3 error?

I'm not familiar with the library, but if your problem is that you don't want a byte array, one easy way is to specify an encoding type straight in a cast:

>>> my_byte_str
b'Hello World'

>>> str(my_byte_str, 'utf-8')
'Hello World'

Use JSTL forEach loop's varStatus as an ID

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1

Why did my Git repo enter a detached HEAD state?

I reproduced this just now by accident:

  1. lists the remote branches

    git branch -r
          origin/Feature/f1234
          origin/master
    
  2. I want to checkout one locally, so I cut paste:

    git checkout origin/Feature/f1234
    
  3. Presto! Detached HEAD state

    You are in 'detached HEAD' state. [...])
    

Solution #1:

Do not include origin/ at the front of my branch spec when checking it out:

git checkout Feature/f1234

Solution #2:

Add -b parameter which creates a local branch from the remote

git checkout -b origin/Feature/f1234 or

git checkout -b Feature/f1234 it will fall back to origin automatically

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

JUnit: how to avoid "no runnable methods" in test utils classes

To prevent JUnit from instantiating your test base class just make it

public abstract class MyTestBaseClass { ... whatever... }

(@Ignore reports it as ignored which I reserve for temporarily ignored tests.)

Can we call the function written in one JavaScript in another JS file?

As long as both are referenced by the web page, yes.

You simply call the functions as if they are in the same JS file.

Copy files without overwrite

This is what has worked for me. I use this to "add" files over to the other drive, with no overwrites.

Batch file: robocopy-missingfiles.bat

@echo off
echo Copying 
echo      "%1"
echo   to "%2"
echo.
echo Press Cntr+C to abort
Pause
echo.
@echo on
robocopy %1 %2 /Xo /XN /XC /J /SL /S /MT:8 /R:1 /W:1 /V /DCOPY:DAT /ETA /COPY:DATO /FFT /A-:SH /XD $RECYCLE.BIN "System Volume Information"

Example:

robocopy-missingfiles.bat f:\Working-folder\ E:\Backup-folder\

Do test before implementation.

How can I compare strings in C using a `switch` statement?

There is no way to do this in C. There are a lot of different approaches. Typically the simplest is to define a set of constants that represent your strings and do a look up by string on to get the constant:

#define BADKEY -1
#define A1 1
#define A2 2
#define B1 3
#define B2 4

typedef struct { char *key; int val; } t_symstruct;

static t_symstruct lookuptable[] = {
    { "A1", A1 }, { "A2", A2 }, { "B1", B1 }, { "B2", B2 }
};

#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))

int keyfromstring(char *key)
{
    int i;
    for (i=0; i < NKEYS; i++) {
        t_symstruct *sym = lookuptable[i];
        if (strcmp(sym->key, key) == 0)
            return sym->val;
    }
    return BADKEY;
}

/* ... */
switch (keyfromstring(somestring)) {
case A1: /* ... */ break;
case A2: /* ... */ break;
case B1: /* ... */ break;
case B2: /* ... */ break;
case BADKEY: /* handle failed lookup */
}

There are, of course, more efficient ways to do this. If you keep your keys sorted, you can use a binary search. You could use a hashtable too. These things change your performance at the expense of maintenance.

Where does Chrome store cookies?

On Windows the path is:

C:\Users\<current_user>\AppData\Local\Google\Chrome\User Data\<Profile 1>\Cookies(Type:File)

Chrome doesn't store each cookies in separate text file. It stores all of the cookies together in a single file in the profile folder. That file is not readable.

What is the best way to access redux store outside a react component?

Found a solution. So I import the store in my api util and subscribe to it there. And in that listener function I set the axios' global defaults with my newly fetched token.

This is what my new api.js looks like:

// tooling modules
import axios from 'axios'

// store
import store from '../store'
store.subscribe(listener)

function select(state) {
  return state.auth.tokens.authentication_token
}

function listener() {
  let token = select(store.getState())
  axios.defaults.headers.common['Authorization'] = token;
}

// configuration
const api = axios.create({
  baseURL: 'http://localhost:5001/api/v1',
  headers: {
    'Content-Type': 'application/json',
  }
})

export default api

Maybe it can be further improved, cause currently it seems a bit inelegant. What I could do later is add a middleware to my store and set the token then and there.

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

how to insert date and time in oracle?

Just use TO_DATE() function to convert string to DATE.

For Example:

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'Vishnu', TO_DATE('1994/12/16 12:00:00', 'yyyy/mm/dd hh:mi:ss'));

What's the algorithm to calculate aspect ratio?

This algorithm in Python gets you part of the way there.


Tell me what happens if the windows is a funny size.

Maybe what you should have is a list of all acceptable ratios (to the 3rd party component). Then, find the closest match to your window and return that ratio from the list.