Programs & Examples On #Markerclusterer

This JavaScript library creates and manages per-zoom-level clusters for large amounts of markers on a Google Map. It may be superseded and/or deprecated by MarkerClustererPlus.

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

GCC -fPIC option

The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.


There are two commonly used methods for dealing with this problem:

1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.

2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.


The name "position-independent code" actually implies following:

  • The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.

  • The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.

  • All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.


This so-called symbol interposition is intended to mimic the behavior of static libraries.

A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.

p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.

You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf

How to make java delay for a few seconds?

 new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    if (getActivity() != null)
                        getActivity().runOnUiThread(() -> tvCovidAlert.startAnimation(animBounce));
                }
            }, DELAY_TIME_MILI_SECONDS);

jQuery get values of checked checkboxes into array

Do not use "each". It is used for operations and changes in the same element. Use "map" to extract data from the element body and using it somewhere else.

C++ - unable to start correctly (0xc0150002)

I agree with Brandrew, the problem is most likely caused by some missing dlls that can't be found neither on the system path nor in the folder where the executable is. Try putting the following DLLs nearby the executable:

  • the Visual Studio C++ runtime (in VS2008, they could be found at places like C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86.) Include all 3 of the DLL files as well as the manifest file.
  • the four OpenCV dlls (cv210.dll, cvaux210.dll, cxcore210.dll and highgui210.dll, or the ones your OpenCV version has)
  • if that still doesn't work, try the debug VS runtime (executables compiled for "Debug" use a different set of dlls, named something like msvcrt9d.dll, important part is the "d")

Alternatively, try loading the executable into Dependency Walker ( http://www.dependencywalker.com/ ), it should point out the missing dlls for you.

How do I make XAML DataGridColumns fill the entire DataGrid?

As noted, the ColumnWidth="*" worked perfectly well for a DataGrid in XAML.

I used it in this context:

<DataGrid ColumnWidth="*" ItemsSource="{Binding AllFolders, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you're recompiling a disassembled APK with APK tool:

Just Set Memory Allocation a little bigger

set switch -Xmx1024mto -Xmx2048m

java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"

you're good to go.. :)

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrapping the existing formula in IFERROR will not achieve:

the average of cells that contain non-zero, non-blank values.

I suggest trying:

=if(ArrayFormula(isnumber(K23:M23)),AVERAGEIF(K23:M23,"<>0"),"")

System.Timers.Timer vs System.Threading.Timer

One important difference not mentioned above which might catch you out is that System.Timers.Timer silently swallows exceptions, whereas System.Threading.Timer doesn't.

For example:

var timer = new System.Timers.Timer { AutoReset = false };
timer.Elapsed += (sender, args) =>
{
    var z = 0;
    var i = 1 / z;
};
timer.Start();

vs

var timer = new System.Threading.Timer(x =>
{
    var z = 0;
    var i = 1 / z;
}, null, 0, Timeout.Infinite);

How do you access the element HTML from within an Angular attribute directive?

Base on @Mark answer, I add the constructor to directive and it work with me.

I share a sample to whom concern.

constructor(private el: ElementRef, private renderer: Renderer) {
}

TS file

@Directive({ selector: '[accordion]' })
export class AccordionDirective {

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener('click', ['$event']) onClick($event) {
    console.info($event);

    this.el.nativeElement.classList.toggle('is-open');

    var content = this.el.nativeElement.nextElementSibling;
    if (content.style.maxHeight) {
      // accordion is currently open, so close it
      content.style.maxHeight = null;
    } else {
      // accordion is currently closed, so open it
      content.style.maxHeight = content.scrollHeight + "px";

    }
  }
}

HTML

<button accordion class="accordion">Accordian #1</button>
    <div class="accordion-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
        ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
      </p>     
    </div>

Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

If you have 32-bit Windows, this method is not working without following settings.

  1. Run prompt cmd.exe (important : Run As Administrator)
  2. type bcdedit.exe and run
  3. Look at the "increaseuserva" params and there is no then write following statement
  4. bcdedit /set increaseuserva 3072
  5. and again step 2 and check params

We added this settings and this block started.

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

More info - command increaseuserva: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set

SQL: capitalize first letter only

Create the below function

Alter FUNCTION InitialCap(@String VARCHAR(8000))
                  RETURNS VARCHAR(8000)
                 AS
 BEGIN 

                   DECLARE @Position INT;

SELECT @String   = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
                    @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);

                    WHILE @Position > 0
                    SELECT @String   = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
                    @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);

                     RETURN @String;
  END ;

Then call it like

select dbo.InitialCap(columnname) from yourtable

How to hide html source & disable right click and text copy?

There is no full proof way.

But here is some strategy that can be employed to hide source code using "window.history.pushState()" and adding oncontextmenu="return false" in body tag as attribute like <body oncontextmenu="return false"> to disable right click too along with modifying view-source content using "history.pushState()".

Detail here - http://freelancer.usercv.com/blog/28/hide-website-source-code-in-view-source-using-stupid-one-line-chinese-hack-code

Select records from NOW() -1 Day

You're almost there: it's NOW() - INTERVAL 1 DAY

.bashrc at ssh login

If ayman's solution doesn't work, try naming your file .profile instead of .bash_profile. That worked for me.

How do I keep CSS floats in one line?

When user reduces window size horizontally and this causes floats to stack vertically, remove the floats and on the second div (that was a float) use margin-top: -123px (your value) and margin-left: 444px (your value) to position the divs as they appeared with floats. When done this way, when the window narrows, the right-side div stays in place and disappears when page is too narrow to include it. ... which (to me) is better than having the right-side div "jump" down below the left-side div when the browser window is narrowed by the user.

Missing styles. Is the correct theme chosen for this layout?

I got this error after overriding action bar style like this. Also i lost action bar in preview.

<style name="general_app_theme" parent="@style/Theme.AppCompat">
    <!-- for API level 11 -->
    <item name="android:actionBarStyle">@style/action_bar_style</item>

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/action_bar_style</item>

</style>

<style name="action_bar_style" parent="@style/Widget.AppCompat.ActionBar">
    <!-- for API level 11 -->
    <item name="android:height">@dimen/action_bar_height</item>
    <item name="android:background">@color/action_bar_color</item>
    <item name="android:displayOptions">showTitle</item>

    <!-- Support library compatibility -->
    <item name="displayOptions">showTitle</item>
</style>

So, problem is overriding theme by my custom. this is the reason, why I've changed AppCompat (from "Project Themes") to general_app_theme (from "Manifest Themes"). Now I have no this error and action bar in preview come back.

Scala vs. Groovy vs. Clojure

Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.

If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.

How do I set an absolute include path in PHP?

There is nothing in include/require that prohibits you from using absolute an path. so your example

include('/includes/header.php'); 

should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)

This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.

This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.

as for the '.' syntax:

/home/username/public_html <- absolute path  
public_html <- relative path  
./public_html <- same as the path above  
../username/public_html <- another relative path  

However, I usually use a slightly different option:

require_once(__DIR__ . '/Factories/ViewFactory.php');

With this edition, you specify an absolute path, relative to the file that contains the require_once() statement.

What is Join() in jQuery?

That's not a jQuery function - it's the regular Array.join function.

It converts an array to a string, putting the argument between each element.

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

AngularJS ngClass conditional

Using ng-class inside ng-repeat

<table>
    <tbody>
            <tr ng-repeat="task in todos"
                ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
              'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
                <td>{{$index + 1}}</td>
                <td>{{task.name}}</td>
                <td>{{task.date|date:'yyyy-MM-dd'}}</td>
                <td>{{task.status}}</td>
            </tr>
    </tbody>
</table>

For each status in task.status a different class is used for the row.

The name 'InitializeComponent' does not exist in the current context

I encountered this while renaming a usercontrol. The way I fixed it was to comment out InitializeComponent, verify that all the names were correct (xaml and code behind), build the project, uncomment InitializeComponent, then build again. It sounds like there may be a couple causes/solutions for this issue, but this way did it for me.

Postgresql 9.2 pg_dump version mismatch

If you're using Heroku's Postgres.app the pg_dump (along with all the other binaries) is in /Applications/Postgres.app/Contents/MacOS/bin/

so in that case it's

ln -s /Applications/Postgres.app/Contents/MacOS/bin/pg_dump /usr/local/bin/pg_dump

or

ln -s /Applications/Postgres.app/Contents/MacOS/bin/* /usr/local/bin/.

to just grab them all

How to uncheck a radio button?

You wouldn't need the each function

$("input:radio").attr("checked", false);

Or

$("input:radio").removeAttr("checked");

The same should also apply to your textbox:

$('#frm input[type="text"]').val("");

But you could improve this

$('#frm input:text').val("");

Checking whether the pip is installed?

In CMD, type:

pip freeze

And it will show you a list of all the modules installed including the version number.

Output:

aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0

Selecting default item from Combobox C#

this is the correct form:

comboBox1.Text = comboBox1.Items[0].ToString();

U r welcome

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Explanation of JSONB introduced by PostgreSQL

JSONB is a "better" version of JSON.

Let's look at an example:

SELECT '{"c":0,   "a":2,"a":1}'::json, '{"c":0,   "a":2,"a":1}'::jsonb;
          json          |        jsonb 
------------------------+--------------------- 
 {"c":0,   "a":2,"a":1} | {"a": 1, "c": 0} 
(1 row)
  1. JSON stores white space, they is why we can see spaces when key "a" is stored, while JSONB does not.
  2. JSON stores all the values of key. This is the reason you can see multiple values (2 and 1) against the key "a" , while JSONB only "stores" the last value.
  3. JSON maintains the order in which elements are inserted, while JSONB maintains the "sorted" order.
  4. JSONB objects are stored as decompressed binary as opposed to "raw data" in JSON , where no reparsing of data is required during retrieval.
  5. JSONB also supports indexing, which can be a significant advantage.

In general, one should prefer JSONB , unless there are specialized needs, such as legacy assumptions about ordering of object keys.

Filezilla FTP Server Fails to Retrieve Directory Listing

If you're using VestaCP, you might want to allow ports 12000-12100 TCP on your Linux Firewall.

You can do this in VestaCP settings.

Pure CSS collapse/expand div

Using <summary> and <details>

Using <summary> and <details> elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.

_x000D_
_x000D_
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
  color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
  outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
  <summary>Summary, caption, or legend for the content</summary>_x000D_
  Content goes here._x000D_
</details>
_x000D_
_x000D_
_x000D_

See also how to style the <details> element (HTML5 Doctor) (little bit tricky).

Pure CSS3

The :target selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.

_x000D_
_x000D_
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
  display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
  display: block;_x000D_
}
_x000D_
<div>_x000D_
  <a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
  <a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
  <a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
  <a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to properly set Column Width upon creating Excel file? (Column properties)

This link explains how to apply a cell style to a range of cells: http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx

See this snippet:

Microsoft.Office.Tools.Excel.NamedRange rangeStyles =
this.Controls.AddNamedRange(this.Range["A1"], "rangeStyles");

rangeStyles.Value2 = "'Style Test";
rangeStyles.Style = "NewStyle";
rangeStyles.Columns.AutoFit();

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

python exception message capturing

Use str(ex) to print execption

try:
   #your code
except ex:
   print(str(ex))

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

Add two numbers and display result in textbox with Javascript

It should be document.getElementById("txtresult").value= result;

You are setting the value of the textbox to the result. The id="txtresult" is not an HTML element.

Adding a module (Specifically pymorph) to Spyder (Python IDE)

You can add the Standard Installation location to the PYTHONPATH manager. This way you don't need to add a specific path for each module. Only to update module names.

On Unix this location is usually:

/usr/local/lib/pythonX.Y/site-packages

On Windows:

C:\PythonXY\Lib\site-packages

See the modules install Documentation.

How to read pickle file?

There is a read_pickle function as part of pandas 0.22+

import pandas as pd

object = pd.read_pickle(r'filepath')

PHP max_input_vars

Reference on PHP net:

http://php.net/manual/en/info.configuration.php#ini.max-input-vars

Please note, you cannot set this directive in run-time with function ini_set(name, newValue), e.g.

ini_set('max_input_vars', 3000);

It will not work.

As explained in documentation, this directive may only be set per directory scope, which means via .htaccess file, httpd.conf or .user.ini (since PHP 5.3).

See http://php.net/manual/en/configuration.changes.modes.php

Adding the directive into php.ini or placing following lines into .htaccess will work:

php_value max_input_vars 3000
php_value suhosin.get.max_vars 3000
php_value suhosin.post.max_vars 3000
php_value suhosin.request.max_vars 3000

How to resize a VirtualBox vmdk file

I was able to resize the vmdk by cloning it and then modifying and resizing.

vboxmanage clonehd "virtualdisk.vmdk" "new-virtualdisk.vdi" --format vdi
vboxmanage modifyhd "new-virtualdisk.vdi" --resize 30720

Bootstrap 4 - Inline List?

Inline

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>


<ul class="list-inline">
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
_x000D_
_x000D_
_x000D_

and learn more about https://getbootstrap.com/docs/4.0/content/typography/#inline

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

How do I install package.json dependencies in the current directory using npm

Running:

npm install

from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).

You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.

To prevent this, just create a symlink to the relocated node_modules from your app dir:

ln -s ../node_modules node_modules

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

In this case, one of the easiest and best approach is to first cast it to list and then use where or select.

result = result.ToList().where(p => date >= p.DOB);

How to replace multiple strings in a file using PowerShell

Assuming you can only have one 'something1' or 'something2', etc. per line, you can use a lookup table:

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line -replace $_.Key, $_.Value
            break
        }
    }
} | Set-Content -Path $destination_file

If you can have more than one of those, just remove the break in the if statement.

Full-screen responsive background image

One hint about the "background-size: cover" solution, you have to put it after "background" definition, otherwise it won't work, for example this won't work:

html, body {
    height: 100%;
    background-size: cover;
    background:url("http://i.imgur.com/aZO5Kolb.jpg") no-repeat center center fixed;
}

http://jsfiddle.net/8XUjP/58/

How to return rows from left table not found in right table?

If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:

  1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.
  2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).
  3. Next comes the third type of joins, Outer Joins:

    In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.

    The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.

Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

How to add empty spaces into MD markdown readme on GitHub?

I'm surprised no one mentioned the HTML entities &ensp; and &emsp; which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than &nbsp;.

  1. no space
  2.  &nbsp;
  3. &ensp;
  4. &emsp;

Along with <space> and &thinsp;, these are the five entities HTML provides for horizontal white space.

Note that except for &nbsp;, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With &nbsp; it would wrap to a new line as a block even if the text before &nbsp; could fit on the previous line.

Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John&nbsp;Doe), addresses or references (see eq.&nbsp;5), breaking as a block is usually undesired.

Bash: If/Else statement in one line

You can make full use of the && and || operators like this:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0

For excluding grep itself, you could also do something like:

ps aux | grep some_proces | grep -vw grep > /tmp/test.txt && echo 1 || echo 0

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

IF OBJECT_ID (N't1', N'U') IS NOT NULL 
drop table t1

create table t1 (f1 int)


    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)


SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

SELECT 
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

Switch case with conditions

Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.

Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.

$('.next').click(function(){
        var imageToSlide = $('#imageSprite'); // Get id of image

        switch(true) {
            case (imageToSlide.hasClass('pos1')):
                imageToSlide.removeClass('pos1').addClass('pos2');
                break;
            case (imageToSlide.hasClass('pos2')):
                imageToSlide.removeClass('pos2').addClass('pos3');
                break;
            case (imageToSlide.hasClass('pos3')):
                imageToSlide.removeClass('pos3').addClass('pos4');
                break;
            case (imageToSlide.hasClass('pos4')):
                imageToSlide.removeClass('pos4').addClass('pos1');
        }
    }); ` 

Best way to simulate "group by" from bash?

I'd have done it like this:

perl -e 'while (<>) {chop; $h{$_}++;} for $k (keys %h) {print "$k $h{$k}\n";}' ip_addresses

but uniq might work for you.

How do I raise the same Exception with a custom message in Python?

This code template should allow you to raise an exception with a custom message.

try:
     raise ValueError
except ValueError as err:
    raise type(err)("my message")

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

Simpler way to create dictionary of separate variables?

As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects.

However, here's one way to try and do it:

 >>> a = 1
 >>> for k, v in list(locals().iteritems()):
         if v is a:
             a_as_str = k
 >>> a_as_str
 a
 >>> type(a_as_str)
 'str'

What is the difference between AF_INET and PF_INET in socket programming?

I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.

/* Protocol families, same as address families. */
...
#define PF_INET     AF_INET

Exporting functions from a DLL with dllexport

I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport) to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does

Warning :-Presenting view controllers on detached view controllers is discouraged

One of the solution to this is if you have childviewcontroller So you simply presentviewcontroller on its parent by given

[self.parentViewController presentViewController:viewController animated:YES completion:nil];

And for dismiss use the same dismissview controller.

[self dismissViewControllerAnimated:YES completion:nil];

This is perfect solution works for me.

Curl to return http status code along with the response

This command

 curl http://localhost -w ", %{http_code}"

will get the comma separated body and status; you can split them to get them out.

You can change the delimiter as you like.

HAX kernel module is not installed

First you need to turn on virtualization on your machine. To do that, restart your machine. Press F2. Goto BIOS. Make Virtualization Enabled. Press F10. Start windows. Now, goto Extras folder of Android installation folder and find intel-haxm-android.exe. Run it. Start Android Studio. Now, it should allow you to run your program using emulator.

Check if object value exists within a Javascript array of objects and if not add a new object to array

It's rather trivial to check for existing username:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:

function addUser(username) {
  if (userExists(username)) {
    return false; 
  }
  arr.push({ id: arr.length + 1, username: username });
  return true;
}

addUser('fred'); // false
addUser('bred'); // true, user `bred` added

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

What is the 'override' keyword in C++ used for?

Wikipedia says:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

In detail, when you have an object foo that has a void hello() function:

class foo {
    virtual void hello(); // Code : printf("Hello!");
}

A child of foo, will also have a hello() function:

class bar : foo {
    // no functions in here but yet, you can call
    // bar.hello()
}

However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override

class bar : foo {
    virtual void hello() override; // Code : printf("Hello Bar!");
}

Calculate time difference in Windows batch file

Aacini's latest code showcases an awesome variable substitution method.
It's a shame it's not Regional format proof - it fails on so many levels.
Here's a short fix that keeps the substitution+math method intact:

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%" & rem AveYo: fix single digit hour

set /P "=Any process here..."

set "endTime=%time: =0%" & rem AveYo: fix single digit hour

rem Aveyo: Regional format fix with just one aditional line
for /f "tokens=1-3 delims=0123456789" %%i in ("%endTime%") do set "COLON=%%i" & set "DOT=%%k" 

rem Get elapsed time:
set "end=!endTime:%DOT%=%%100)*100+1!" & set "start=!startTime:%DOT%=%%100)*100+1!"
set /A "elap=((((10!end:%COLON%=%%100)*60+1!%%100)-((((10!start:%COLON%=%%100)*60+1!%%100)"

rem Aveyo: Fix 24 hours 
set /A "elap=!elap:-=8640000-!"

rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"

echo Start:    %startTime%
echo End:      %endTime%
echo Elapsed:  %hh:~1%%COLON%%mm:~1%%COLON%%ss:~1%%DOT%%cc:~1% & rem AveYo: display as regional
pause

*

"Lean and Mean" TIMER with Regional format, 24h and mixed input support
Adapting Aacini's substitution method body, no IF's, just one FOR (my regional fix)

1: File timer.bat placed somewhere in %PATH% or the current dir

@echo off & rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

Usage:
timer & echo start_cmds & timeout /t 3 & echo end_cmds & timer
timer & timer "23:23:23,00"
timer "23:23:23,00" & timer
timer "13.23.23,00" & timer "03:03:03.00"
timer & timer "0:00:00.00" no & cmd /v:on /c echo until midnight=!timer_end!
Input can now be mixed, for those unlikely, but possible time format changes during execution

2: Function :timer bundled with the batch script (sample usage below):

@echo off
set "TIMER=call :timer" & rem short macro
echo.
echo EXAMPLE:
call :timer
timeout /t 3 >nul & rem Any process here..
call :timer
echo.
echo SHORT MACRO:
%TIMER% & timeout /t 1 & %TIMER% 
echo.
echo TEST INPUT:
set "start=22:04:04.58"
set "end=04.22.44,22"
echo %start% ~ start & echo %end% ~ end
call :timer "%start%"
call :timer "%end%"
echo.
%TIMER% & %TIMER% "00:00:00.00" no 
echo UNTIL MIDNIGHT: %timer_end%
echo.
pause 
exit /b

:: to test it, copy-paste both above and below code sections

rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support 
:timer Usage " call :timer [input - optional] [no - optional]" :i Result printed on second call, saved to timer_end 
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

How can I override the OnBeforeUnload dialog and replace it with my own?

I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was : 1) It was giving message on all navigations I want it only for close click. 2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.

Following is the solutions code I found, which I wrote on my Master page.

function closeMe(evt) {
    if (typeof evt == 'undefined') {
        evt = window.event; }
    if (evt && evt.clientX >= (window.event.screenX - 150) &&
        evt.clientY >= -150 && evt.clientY <= 0) {
        return "Do you want to log out of your current session?";
    }
}
window.onbeforeunload = closeMe;

How to manage exceptions thrown in filters in Spring?

After reading through different methods suggested in the above answers, I decided to handle the authentication exceptions by using a custom filter. I was able to handle the response status and codes using an error response class using the following method.

I created a custom filter and modified my security config by using the addFilterAfter method and added after the CorsFilter class.

@Component
public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    //Cast the servlet request and response to HttpServletRequest and HttpServletResponse
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    // Grab the exception from the request attribute
    Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
    //Set response content type to application/json
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

    //check if exception is not null and determine the instance of the exception to further manipulate the status codes and messages of your exception
    if(exception!=null && exception instanceof AuthorizationParameterNotFoundException){
        ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(convertObjectToJson(errorResponse));
        writer.flush();
        return;
    }
    // If exception instance cannot be determined, then throw a nice exception and desired response code.
    else if(exception!=null){
            ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(convertObjectToJson(errorResponse));
            writer.flush();
            return;
        }
        else {
        // proceed with the initial request if no exception is thrown.
            chain.doFilter(httpServletRequest,httpServletResponse);
        }
    }

public String convertObjectToJson(Object object) throws JsonProcessingException {
    if (object == null) {
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(object);
}
}

SecurityConfig class

    @Configuration
    public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthFilter authenticationFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(authenticationFilter, CorsFilter.class).csrf().disable()
                .cors(); //........
        return http;
     }
   }

ErrorResponse class

public class ErrorResponse  {
private final String message;
private final String description;

public ErrorResponse(String description, String message) {
    this.message = message;
    this.description = description;
}

public String getMessage() {
    return message;
}

public String getDescription() {
    return description;
}}

Best /Fastest way to read an Excel Sheet into a DataTable?

I found it pretty easy like this

    using System;
    using System.Data;
    using System.IO;
    using Excel;

    public DataTable ExcelToDataTableUsingExcelDataReader(string storePath)
    {
        FileStream stream = File.Open(storePath, FileMode.Open, FileAccess.Read);

        string fileExtension = Path.GetExtension(storePath);
        IExcelDataReader excelReader = null;
        if (fileExtension == ".xls")
        {
            excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        }
        else if (fileExtension == ".xlsx")
        {
            excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        }

        excelReader.IsFirstRowAsColumnNames = true;
        DataSet result = excelReader.AsDataSet();
        var test = result.Tables[0];
        return result.Tables[0];
    }

Note: you need to install SharpZipLib package for this

Install-Package SharpZipLib

neat and clean! ;)

Do HttpClient and HttpClientHandler have to be disposed between requests?

I think one should use singleton pattern to avoid having to create instances of the HttpClient and closing it all the time. If you are using .Net 4.0 you could use a sample code as below. for more information on singleton pattern check here.

class HttpClientSingletonWrapper : HttpClient
{
    private static readonly Lazy<HttpClientSingletonWrapper> Lazy= new Lazy<HttpClientSingletonWrapper>(()=>new HttpClientSingletonWrapper()); 

    public static HttpClientSingletonWrapper Instance {get { return Lazy.Value; }}

    private HttpClientSingletonWrapper()
    {
    }
}

Use the code as below.

var client = HttpClientSingletonWrapper.Instance;

do { ... } while (0) — what is it good for?

It is a way to simplify error checking and avoid deep nested if's. For example:

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

How to display the string html contents into webbrowser control?

Instead of navigating to blank, you can do

webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();

No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.

Attach the Java Source Code

What worked for me (with JDK7) was the following:

  1. Download the openjdk-xy-sources.jar from GrepCode,
  2. rename the file to src.zip,
  3. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  4. restart eclipse

Alternatively, if you don't want to write to your JDK folder, you could also attach src.zip to (at least) rt.jar in eclipse in the Window | Preferences menu in Java | Installed JREs.

If you're not comfortable with downloading the sources from GrepCode, you could also get them from openJDK directly. This requires requires a bit more effort, though. Replace step one above by the following steps:

  1. Download the JDK sources from here,
  2. extract all folders from the zip file's *openjdk\jdk\src\share\classes* folder,
  3. create a file src.zip and add these folders to it,
  4. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  5. restart eclipse

A third alternative to acquire src.zip is to download the unofficial OpenJDK builds from here. The src.zip is contained within the downloaded zip.

Using port number in Windows host file

I managed to achieve this by using Windows included Networking tool netsh.

As Mat points out : The hosts file is for host name resolution only, so a combination of the two did the trick for me.

Example


Overview

example.app:80
 |                           <--Link by Hosts File
 +--> 127.65.43.21:80
       |                     <--Link by netsh Utility
       +--> localhost:8081

Actions

  • Started my server on localhost:8081
  • Added my "local DNS" in the hosts file as a new line
    • 127.65.43.21 example.app
      • Any free address in the network 127.0.0.0/8 (127.x.x.x) can be used.
      • Note: I am assuming 127.65.43.21:80 is not occupied by another service.
      • You can check with netstat -a -n -p TCP | grep "LISTENING"
  • added the following network configuration with netsh command utility
    • netsh interface portproxy add v4tov4 listenport=80 listenaddress=127.65.43.21 connectport=8081 connectaddress=127.0.0.1
  • I can now access the server at http://example.app

Notes:
- These commands/file modifications need to be executed with Admin rights

- netsh portproxy needs ipv6 libraries even only to use v4tov4, typically they will also be included by default, otherwise install them using the following command: netsh interface ipv6 install


You can see the entry you have added with the command:

netsh interface portproxy show v4tov4

You can remove the entry with the following command:

netsh interface portproxy delete v4tov4 listenport=80 listenaddress=127.65.43.21


Links to Resources:

Is the order of elements in a JSON list preserved?

"Is the order of elements in a JSON list maintained?" is not a good question. You need to ask "Is the order of elements in a JSON list maintained when doing [...] ?" As Felix King pointed out, JSON is a textual data format. It doesn't mutate without a reason. Do not confuse a JSON string with a (JavaScript) object.

You're probably talking about operations like JSON.stringify(JSON.parse(...)). Now the answer is: It depends on the implementation. 99%* of JSON parsers do not maintain the order of objects, and do maintain the order of arrays, but you might as well use JSON to store something like

{
    "son": "David",
    "daughter": "Julia",
    "son": "Tom",
    "daughter": "Clara"
}

and use a parser that maintains order of objects.

*probably even more :)

How to change the docker image installation directory?

A much simpler solution is to create a soft link point to whatever you want, such as

link -s /var/lib/docker /mnt/whatever

It works for me on my CentOS 6.5 server.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Just to add on to the topic of for in/for/$.each, I added a jsperf test case for using $.each vs for in: http://jsperf.com/each-vs-for-in/2

Different browsers/versions handle it differently, but it seems $.each and straight out for in are the cheapest options performance-wise.

If you're using for in to iterate through an associative array/object, knowing what you're after and ignoring everything else, use $.each if you use jQuery, or just for in (and then a break; once you've reached what you know should be the last element)

If you're iterating through an array to perform something with each key pair in it, should use the hasOwnProperty method if you DON'T use jQuery, and use $.each if you DO use jQuery.

Always use for(i=0;i<o.length;i++) if you don't need an associative array though... lol chrome performed that 97% faster than a for in or $.each

Where is Maven Installed on Ubuntu

Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.

As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.

For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:

The Apt-get installation will install all the required files in the following folder structure

/usr/bin/mvn

/usr/share/maven2/

/etc/maven2

P.S The Maven configuration is store in /etc/maven2

Note, it's not just apt-get that will do this, it's any .deb package installer.

How to get the month name in C#?

You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.

I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.

Here is an example of how to do it using extension methods:

using System;
using System.Globalization;

class Program
{
    static void Main()
    {

        Console.WriteLine(DateTime.Now.ToMonthName());
        Console.WriteLine(DateTime.Now.ToShortMonthName());
        Console.Read();
    }
}

static class DateTimeExtensions
{
    public static string ToMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
    }

    public static string ToShortMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
    }
}

Hope this helps!

warning: assignment makes integer from pointer without a cast

The warning comes from the fact that you're dereferencing src in the assignment. The expression *src has type char, which is an integral type. The expression "anotherstring" has type char [14], which in this particular context is implicitly converted to type char *, and its value is the address of the first character in the array. So, you wind up trying to assign a pointer value to an integral type, hence the warning. Drop the * from *src, and it should work as expected:

src = "anotherstring";

since the type of src is char *.

How do I set headers using python's urllib?

adding HTTP headers using urllib2:

from the docs:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

COPY is

Same as 'ADD', but without the tar and remote URL handling.

Reference straight from the source code.

document.getElementById replacement in angular4 / typescript?

You can tag your DOM element using #someTag, then get it with @ViewChild('someTag').

See complete example:

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';

@Component({
    selector: 'app',
    template: `
        <div #myDiv>Some text</div>
    `,
})
export class AppComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    }
}

console.log will print Some text.

How to perform element-wise multiplication of two lists?

you can multiplication using lambda

foo=[1,2,3,4]
bar=[1,2,5,55]
l=map(lambda x,y:x*y,foo,bar)

Why am I getting a FileNotFoundError?

The mistake I did was my code :

x = open('python.txt')

print(x)

But the problem was in file directory ,I saved it as python.txt instead of just python .

So my file path was ->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt

That is why it was giving a error.

Name your file without .txt it will run.

How to wait for a process to terminate to execute another process in batch file

Try something like this...

@ECHO OFF

PSKILL NOTEPAD

START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"

:LOOP
PSLIST wordpad >nul 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
) ELSE (
  ECHO Wordpad is still running
  TIMEOUT /T 5
  GOTO LOOP
)

:CONTINUE
NOTEPAD

I used PSLIST and PSEXEC, but you could also use TASKKILL and TASKLIST. The >nul 2>&1 is just there to hide all the output from PSLIST. The SLEEP 5 line is not required, but is just there to restrict how often you check if WordPad is still running.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

if (x) 

coerces x using JavaScript's internal toBoolean (http://es5.github.com/#x9.2)

x == false

coerces both sides using internal toNumber coercion (http://es5.github.com/#x9.3) or toPrimitive for objects (http://es5.github.com/#x9.1)

For full details see http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

What is the difference between os.path.basename() and os.path.dirname()?

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/2/library/os.path.html#os.path.basename

Electron: jQuery is not defined

I face the same issue and this worked for me!

Install jQuery using npm

$ npm install jquery

Then include jQuery in one of the following ways.

Using script tag

<script>window.$ = window.jQuery = require('jquery');</script>

Using Babel

import $ from 'jquery';

Using Webpack

const $ = require('jquery');

Getting and removing the first character of a string

Use this function from stringi package

> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"

Copying a rsa public key to clipboard

Another alternative solution, that is recommended in the github help pages:

pbcopy < ~/.ssh/id_rsa.pub

Should this fail, I recommend using their docs to trouble shoot or generate a new key - if not already done.

Github docs

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Casting objects in Java

Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()

The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.

So:

Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ? This is called casting

Android - border for button

Please look here about creating a shape drawable http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

Once you have done this, in the XML for your button set android:background="@drawable/your_button_border"

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

I faced the same problem. Though I am a little bit backdated developer (Still using windows to develop :P)

To solve this issue on windows :

STEP 1: Install jdk 8 if it wasn't installed (jdk 9 or 11 doesn't work but you may have them installed for using in other dev uses).

Very simple using Chocolatey:

choco install jdk8

(If installed using Chocolatey, skip steps 2 and 3)

STEP 2: Go to the Environment variables settings and set JAVA_HOME TO jdk 8's installation directory.

JAVA_HOME

STEP 3: Go to path variable and add bin directory of jdk 8 and move it to top.

Path_varriable

STEP 4: Close any open terminal sessions and restart a new session

OPTIONAL STEP 5: Depending on your objective in the terminal run (may need to add sdkmanager to path or just navigate to the directory):

sdkmanager --update

That's all! :O Enjoy fluttering! :D

How can I see the size of files and directories in linux?

File Size in MB

ls -l --b=M  filename | cut -d " " -f5

File Size in GB

ls -l --b=G  filename | cut -d " " -f5

Maven – Always download sources and javadocs

Simply modify file mvn (or mvn.cmd if in windows) and add whatever command line switches you need (as mentioned by other answers). If you don't want to modify the install files (which I'd recommend), create a mymvn (or mymvn.cmd) wrapper that invokes the regular mvn with the parameters.

How to use '-prune' option of 'find' in sh?

The thing I'd found confusing about -prune is that it's an action (like -print), not a test (like -name). It alters the "to-do" list, but always returns true.

The general pattern for using -prune is this:

find [path] [conditions to prune] -prune -o \
            [your usual conditions] [actions to perform]

You pretty much always want the -o (logical OR) immediately after -prune, because that first part of the test (up to and including -prune) will return false for the stuff you actually want (ie: the stuff you don't want to prune out).

Here's an example:

find . -name .snapshot -prune -o -name '*.foo' -print

This will find the "*.foo" files that aren't under ".snapshot" directories. In this example, -name .snapshot makes up the [conditions to prune], and -name '*.foo' -print is [your usual conditions] and [actions to perform].

Important notes:

  1. If all you want to do is print the results you might be used to leaving out the -print action. You generally don't want to do that when using -prune.

    The default behavior of find is to "and" the entire expression with the -print action if there are no actions other than -prune (ironically) at the end. That means that writing this:

     find . -name .snapshot -prune -o -name '*.foo'              # DON'T DO THIS
    

    is equivalent to writing this:

     find . \( -name .snapshot -prune -o -name '*.foo' \) -print # DON'T DO THIS
    

    which means that it'll also print out the name of the directory you're pruning, which usually isn't what you want. Instead it's better to explicitly specify the -print action if that's what you want:

     find . -name .snapshot -prune -o -name '*.foo' -print       # DO THIS
    
  2. If your "usual condition" happens to match files that also match your prune condition, those files will not be included in the output. The way to fix this is to add a -type d predicate to your prune condition.

    For example, suppose we wanted to prune out any directory that started with .git (this is admittedly somewhat contrived -- normally you only need to remove the thing named exactly .git), but other than that wanted to see all files, including files like .gitignore. You might try this:

    find . -name '.git*' -prune -o -type f -print               # DON'T DO THIS
    

    This would not include .gitignore in the output. Here's the fixed version:

    find . -name '.git*' -type d -prune -o -type f -print       # DO THIS
    

Extra tip: if you're using the GNU version of find, the texinfo page for find has a more detailed explanation than its manpage (as is true for most GNU utilities).

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

Understanding dict.copy() - shallow or deep?

It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.

Here:

>>> new = original 

you're creating a new reference to the the list/dict referenced by original.

while here:

>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)

you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.

How to read a text file into a list or an array with Python

So you want to create a list of lists... We need to start with an empty list

list_of_lists = []

next, we read the file content, line by line

with open('data') as f:
    for line in f:
        inner_list = [elt.strip() for elt in line.split(',')]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int(elt.strip()) for elt in line.split(',')]
        list_of_lists.append(inner_list)

A common use case is that of columnar data, but our units of storage are the rows of the file, that we have read one by one, so you may want to transpose your list of lists. This can be done with the following idiom

by_cols = zip(*list_of_lists)

Another common use is to give a name to each column

col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
    by_names[col_name] = by_cols[i]

so that you can operate on homogeneous data items

 mean_apple_prices = [money/fruits for money, fruits in
                     zip(by_names['apples revenue'], by_names['apples_sold'])]

Most of what I've written can be speeded up using the csv module, from the standard library. Another third party module is pandas, that lets you automate most aspects of a typical data analysis (but has a number of dependencies).


Update While in Python 2 zip(*list_of_lists) returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists) returns a zip object that is not subscriptable.

If you need indexed access you can use

by_cols = list(zip(*list_of_lists))

that gives you a list of lists in both versions of Python.

On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...

file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column

How can I do time/hours arithmetic in Google Spreadsheet?

I used the TO_PURE_NUMBER() function and it worked.

How to execute Python code from within Visual Studio Code

in new Version of VSCode (2019 and newer) We have run and debug Button for python,

Debug :F5

Run without Debug :Ctrl + F5

So you can change it by go to File > Preferences > Keyboard Shortcuts search for RUN: start Without Debugging and change Shortcut to what you want. its so easy and work for Me (my VSCode Version is 1.51 but new update is available).

How to disable GCC warnings for a few lines of code

#pragma GCC diagnostic ignored "-Wformat"

Replace "-Wformat" with the name of your warning flag.

AFAIK there is no way to use push/pop semantics for this option.

Can a normal Class implement multiple interfaces?

Of course... Almost all classes implements several interfaces. On any page of java documentation on Oracle you have a subsection named "All implemented interfaces".

Here an example of the Date class.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

File -> "Invalidate caches/Restart" This worked for me.

Getting all names in an enum as a String[]

Very similar to the accepted answer, but since I learnt about EnumSet, I can't help but use it everywhere. So for a tiny bit more succinct (Java8) answer:

public static String[] getNames(Class<? extends Enum<?>> e) {
  return EnumSet.allOf(e).stream().map(Enum::name).toArray(String[]::new);
}

iOS: how to perform a HTTP POST request?

Xcode 8 and Swift 3.0

Using URLSession:

 let url = URL(string:"Download URL")!
 let req = NSMutableURLRequest(url:url)
 let config = URLSessionConfiguration.default
 let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)

 let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()

URLSession Delegate call:

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

}


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, 
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
                   print("downloaded \(100*writ/exp)" as AnyObject)

}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){

}

Using Block GET/POST/PUT/DELETE:

 let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval:"Your request timeout time in Seconds")
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers as? [String : String] 

    let session = URLSession.shared

    let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
        let httpResponse = response as? HTTPURLResponse

        if (error != nil) {
         print(error)
         } else {
         print(httpResponse)
         }

        DispatchQueue.main.async {
           //Update your UI here
        }

    }
    dataTask.resume()

Working fine for me.. try it 100% result guarantee

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

How to parse XML and count instances of a particular node attribute?

Just to add another possibility, you can use untangle, as it is a simple xml-to-python-object library. Here you have an example:

Installation:

pip install untangle

Usage:

Your XML file (a little bit changed):

<foo>
   <bar name="bar_name">
      <type foobar="1"/>
   </bar>
</foo>

Accessing the attributes with untangle:

import untangle

obj = untangle.parse('/path_to_xml_file/file.xml')

print obj.foo.bar['name']
print obj.foo.bar.type['foobar']

The output will be:

bar_name
1

More information about untangle can be found in "untangle".

Also, if you are curious, you can find a list of tools for working with XML and Python in "Python and XML". You will also see that the most common ones were mentioned by previous answers.

Syntax of for-loop in SQL Server

Simple answer is NO !!.

There is no FOR in SQL, But you can use WHILE or GOTO to achieve the way how the FOR will work.

WHILE :

DECLARE @a INT = 10

WHILE @a <= 20
BEGIN
    PRINT @a
    SET @a = @a + 1
END

GOTO :

DECLARE @a INT = 10
a:
PRINT @a
SET @a = @a + 1
IF @a < = 20
BEGIN
    GOTO a
END

I always prefer WHILE over GOTO statement.

.includes() not working in Internet Explorer

Or just put this in a Javascript file and have a good day :)

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}

How can I switch views programmatically in a view controller? (Xcode, iPhone)

I think the OP is asking how to swap a VIEW without changing viewCONTROLLERs. Am I misunderstanding his question?

In pseudocode, he wants to do:

let myController = instantiate(someParentController)

let view1 = Bundle.main.loadNib(....) as... blah
myController.setThisViewTo( view1 )

let view2 = Bundle.main.loadNib(....) as... blah
myController.setThisViewTo( view2 )

Am I getting his question wrong?

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

How to get the current branch name in Git?

git branch | grep "*" | sed "s/* //" | awk '{printf $0}' | pbcopy

To directly copy the result to the pasteboard. Thanks to @olivier-refalo for the start…

Get bytes from std::string in C++

If this is just plain vanilla C, then:

strcpy(buffer, text.c_str());

Assuming that buffer is allocated and large enough to hold the contents of 'text', which is the assumption in your original code.

If encrypt() takes a 'const char *' then you can use

encrypt(text.c_str())

and you do not need to copy the string.

Using headers with the Python requests library's get method

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

Asp.net Validation of viewstate MAC failed

I have faced the similar issue on my website hosted on IIS. This issue generally because of IIS Application pool settings. As application pool recycle after some time that caused the issue for me.

Following steps help me to fix the issue:

  1. Open App pool of you website on IIS.
  2. Go to Advance settings on right hand pane.
  3. Scroll down to Process Model
  4. Change Idle Time-out minutes to 20 or number of minutes you don't want to recycle your App pool.

enter image description here

Then try again . It will solve your issue.

How to implement reCaptcha for ASP.NET MVC?

Step 1: Client site integration

Paste this snippet before the closing </head> tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js'></script>

Paste this snippet at the end of the <form> where you want the reCAPTCHA widget to appear:

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

Step 2: Server site integration

When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:

URL : https://www.google.com/recaptcha/api/siteverify

secret : your secret key

response : The value of 'g-recaptcha-response'.

Now in action of your MVC app:

// return ActionResult if you want
    public string RecaptchaWork()
    {
        // Get recaptcha value
        var r = Request.Params["g-recaptcha-response"];
        // ... validate null or empty value if you want
        // then
        // make a request to recaptcha api
        using (var wc = new WebClient())
        {
            var validateString = string.Format(
                "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
               "your_secret_key",    // secret recaptcha key
               r); // recaptcha value
             // Get result of recaptcha
            var recaptcha_result = wc.DownloadString(validateString);
            // Just check if request make by user or bot
            if (recaptcha_result.ToLower().Contains("false"))
            {
                 return "recaptcha false";
            }
        }
        // Do your work if request send from human :)
    }

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

go get results in 'terminal prompts disabled' error for github private repo

I had the same problem on windows "error: failed to execute prompt script (exit code 1) fatal: could not read Username for 'https://github.com': No error" trying to login to github through the login dialog. When I canceled the dialog git asked me for login and password in the command line and it worked fine.

Including a .js file within a .js file

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

How can I flush GPU memory using CUDA (physical reset is unavailable)

on macOS (/ OS X), if someone else is having trouble with the OS apparently leaking memory:

  • https://github.com/phvu/cuda-smi is useful for quickly checking free memory
  • Quitting applications seems to free the memory they use. Quit everything you don't need, or quit applications one-by-one to see how much memory they used.
  • If that doesn't cut it (quitting about 10 applications freed about 500MB / 15% for me), the biggest consumer by far is WindowServer. You can Force quit it, which will also kill all applications you have running and log you out. But it's a bit faster than a restart and got me back to 90% free memory on the cuda device.

How to remove empty lines with or without whitespace in Python

lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]

How do I install Python 3 on an AWS EC2 instance?

As of Amazon Linux version 2017.09 python 3.6 is now available:

sudo yum install python36 python36-virtualenv python36-pip

See the Release Notes for more info and other packages

Import MySQL database into a MS SQL Server

Here is my approach for importing .sql files to MS SQL:

  1. Export table from MySQL with --compatible=mssql and --extended-insert=FALSE options:

    mysqldump -u [username] -p --compatible=mssql --extended-insert=FALSE db_name table_name > table_backup.sql

  2. Split the exported file with PowerShell by 300000 lines per file:

    $i=0; Get-Content exported.sql -ReadCount 300000 | %{$i++; $_ | Out-File out_$i.sql}

  3. Run each file in MS SQL Server Management Studio

There are few tips how to speed up the inserts.

Other approach is to use mysqldump –where option. By using this option you can split your table on any condition which is supported by where sql clause.

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

Is it valid to have a html form inside another html form?

As others have said, it is not valid HTML.

It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.

Jenkins returned status code 128 with github

i had sometime ago the same issue. make sure that your ssh key doesn't have password and use not common user account (e.g. better to user account called jenkins or so).

check following article http://fourkitchens.com/blog/2011/09/20/trigger-jenkins-builds-pushing-github

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

How to check what version of jQuery is loaded?

In one line and the minimum of keystrokes (oops!):

alert($().jquery);

How to set username and password for SmtpClient object in .NET?

Use NetworkCredential

Yep, just add these two lines to your code.

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;

Finding sum of elements in Swift array

@IBOutlet var valueSource: [MultipleIntBoundSource]!

private var allFieldsCount: Int {
    var sum = 0
    valueSource.forEach { sum += $0.count }
    return sum
}

used this one for nested parameters

Rounding to 2 decimal places in SQL

you may try the TO_CHAR function to convert the result

e.g.

SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL

SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL

Hope it helps

How do I round to the nearest 0.5?

Here are a couple of methods I wrote that will always round up or down to any value.

public static Double RoundUpToNearest(Double passednumber, Double roundto)
{
    // 105.5 up to nearest 1 = 106
    // 105.5 up to nearest 10 = 110
    // 105.5 up to nearest 7 = 112
    // 105.5 up to nearest 100 = 200
    // 105.5 up to nearest 0.2 = 105.6
    // 105.5 up to nearest 0.3 = 105.6

    //if no rounto then just pass original number back
    if (roundto == 0)
    {
        return passednumber;
    }
    else
    {
        return Math.Ceiling(passednumber / roundto) * roundto;
    }
}

public static Double RoundDownToNearest(Double passednumber, Double roundto)
{
    // 105.5 down to nearest 1 = 105
    // 105.5 down to nearest 10 = 100
    // 105.5 down to nearest 7 = 105
    // 105.5 down to nearest 100 = 100
    // 105.5 down to nearest 0.2 = 105.4
    // 105.5 down to nearest 0.3 = 105.3

    //if no rounto then just pass original number back
    if (roundto == 0)
    {
        return passednumber;
    }
    else
    {
        return Math.Floor(passednumber / roundto) * roundto;
    }
}

Java multiline string

One good option.

import static some.Util.*;

    public class Java {

        public static void main(String[] args) {

            String sql = $(
              "Select * from java",
              "join some on ",
              "group by"        
            );

            System.out.println(sql);
        }

    }


    public class Util {

        public static String $(String ...sql){
            return String.join(System.getProperty("line.separator"),sql);
        }

    }

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

How do I convert seconds to hours, minutes and seconds?

I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Write a formula in an Excel Cell using VBA

I don't know why, but if you use

(...)Formula = "=SUM(D2,E2)"

(',' instead of ';'), it works.

If you step through your sub in the VB script editor (F8), you can add Range("F2").Formula to the watch window and see what the formular looks like from a VB point of view. It seems that the formular shown in Excel itself is sometimes different from the formular that VB sees...

Regex: ignore case sensitivity

The i flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i or /(?i)G[ab].*/.

How can I move all the files from one folder to another using the command line?

use move then move <file or folder> <destination directory>

Fluid width with equally spaced DIVs

If you know the number of elements per "row" and the width of the container you can use a selector to add a margin to the elements you need to cause a justified look.

I had rows of three divs I wanted justified so used the:

.tile:nth-child(3n+2) { margin: 0 10px }

this allows the center div in each row to have a margin that forces the 1st and 3rd div to the outside edges of the container

Also great for other things like borders background colors etc

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

This is just the XML Name Space declaration. We use this Name Space in order to specify that the attributes listed below, belongs to Android. Thus they starts with "android:"

You can actually create your own custom attributes. So to prevent the name conflicts where 2 attributes are named the same thing, but behave differently, we add the prefix "android:" to signify that these are Android attributes.

Thus, this Name Space declaration must be included in the opening tag of the root view of your XML file.

make div's height expand with its content

as an alternative way you can also try this that may be usefull in some situations

display:table;

jsFiddle

Save bitmap to file function

Two example works for me, for your reference.

Bitmap bitmap = Utils.decodeBase64(base64);
try {
    File file = new File(filePath);
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
}
catch (Exception e) {
    e.printStackTrace();
    LOG.i(null, "Save file error!");
    return false;
}

and this one

Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());

if (savePic != null) {
    try {
        // build directory
        if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
        }
        // output image to file
        FileOutputStream fos = new FileOutputStream(filePath);
        savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
        ret = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    LOG.i(TAG, "savePicture image parsing error");
}

How to get span tag inside a div in jQuery and assign a text?

Vanilla JS, without jQuery:

document.querySelector('#message span').innerHTML = 'hello world!'

Available in all browsers: https://caniuse.com/#search=querySelector

How do I test if a variable does not equal either of two values?

ECMA2016 Shortest answer, specially good when checking againt multiple values:

if (!["A","B", ...].includes(test)) {}

Try/catch does not seem to have an effect

Adding "-EA Stop" solved this for me.

Programmatically set left drawable in a TextView

You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)

set 0 where you don't want images

Example for Drawable on the left:

TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.


Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

To prevent that people are mislead by some of the comments to the other answers:

  1. If .schema or query from sqlite_master not gives any output, it indicates a non-existent tablename, e.g. this may also be caused by a ; semicolon at the end for .schema, .tables, ... Or just because the table really not exists. That .schema just doesn't work is very unlikely and then a bug report should be filed at the sqlite project.

... .schema can only be used from a command line; the above commands > can be run as a query through a library (Python, C#, etc.). – Mark Rushakoff Jul 25 '10 at 21:09

  1. 'can only be used from a command line' may mislead people. Almost any (likely every?) programming language can call other programs/commands. Therefore the quoted comment is unlucky as calling another program, in this case sqlite, is more likely to be supported than that the language provides a wrapper/library for every program (which not only is prone to incompleteness by the very nature of the masses of programs out there, but also is counter acting single-source principle, complicating maintenance, furthering the chaos of data in the world).

Converting stream of int's to char's in java

Most answers here propose shortcuts, which can bring you in big problems if you have no idea what you are doing. If you want to take shortcuts, then you have to know exactly what encoding your data is in.

UTF-16

Whenever java talks about characters in its documentation, it talks about 16-bit characters.

You can use a DataInputStream, which has convenient methods. For efficiency, wrap it in a BufferedReader.

// e.g. for sockets
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
char character = readChar(); // no need to cast

The thing is that each readChar() will actually perform 2 read's and combine them to one 16-bit character.

US-ASCII

US-ASCII reserves 8 bits to encode 1 character. The ASCII table only describes 128 possible characters though, so 1 bit is always unused.

You can simply perform a cast in this case.

int input = stream.read();
if (input < 0) throw new EOFException();
char character = (char) input;

Extended ASCII

UTF-8, Latin-1, ANSI and many other encodings use all 8-bits. The first 7-bit follow the ASCII table and are identical to the ones of the US-ASCII encoding. However, the 8th bit offers characters that are different in all these encodings. So, here things get interesting.

If you are a cowboy, and you think that the 8th bit does not matter (i.e. you don't care about characters like "à, é, ç, è, ô ...) then you can get away with a simple cast.

However, if you want to do this professionally, you should really ALWAYS specify a charset whenever you import/export text (e.g. sockets, files ...).

Always use charsets

Let's get serious. All the above options are cheap tricks. If you want to write flexible software you need to support a configurable charset to import/export your data. Here's a generic solution:

Read your data using a byte[] buffer and to convert that to a String using a charset parameter.

byte[] buffer = new byte[1024];
int nrOfBytes = stream.read(buffer);
String result = new String(buffer, nrOfBytes, charset);

You can also use an InputStreamReader which can be instantiated with a charset parameter.

Just one more golden rule: don't ever directly cast a byte to a character. That's always a mistake.

What does "TypeError 'xxx' object is not callable" means?

The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__)

>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Fundamental difference between Hashing and Encryption algorithms

My two liners... generally Interviewer wanted the below answer.

Hashing is one way . You can not convert your data/ string from a hash code.

Encryption is 2 way - you can decrypt again the encrypted string if you have the key with you.

add string to String array

As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.

It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Note that this implementation is not synchronized.

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");

How to convert date to timestamp in PHP?

If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z) to timestamp, here's how you'd do it:

function UTCToTimestamp($utc_datetime_str)
{
    preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
    $datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];

    return strtotime($datetime_str);
}

$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);

What is the difference between ELF files and bin files?

some resources:

  1. ELF for the ARM architecture
    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
  2. ELF from wiki
    http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:

  arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]

or using fromELF utility(built in most IDEs such as ADS though):

 fromelf -bin -o [binary-output-file] [elf-input-file]

How to create a String with carriage returns?

The fastest way I know to generate a new-line character in Java is: String.format("%n")

Of course you can put whatever you want around the %n like:

String.format("line1%nline2")

Or even if you have a lot of lines:

String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")

List all files from a directory recursively with Java

In Guava you don't have to wait for a Collection to be returned to you but can actually iterate over the files. It is easy to imagine a IDoSomethingWithThisFile interface in the signature of the below function:

public static void collectFilesInDir(File dir) {
    TreeTraverser<File> traverser = Files.fileTreeTraverser();
    FluentIterable<File> filesInPostOrder = traverser.preOrderTraversal(dir);
    for (File f: filesInPostOrder)
        System.out.printf("File: %s\n", f.getPath());
}

TreeTraverser also allows you to between various traversal styles.

Finding the median of an unsorted array

I have already upvoted the @dasblinkenlight answer since the Median of Medians algorithm in fact solves this problem in O(n) time. I only want to add that this problem could be solved in O(n) time by using heaps also. Building a heap could be done in O(n) time by using the bottom-up. Take a look to the following article for a detailed explanation Heap sort

Supposing that your array has N elements, you have to build two heaps: A MaxHeap that contains the first N/2 elements (or (N/2)+1 if N is odd) and a MinHeap that contains the remaining elements. If N is odd then your median is the maximum element of MaxHeap (O(1) by getting the max). If N is even, then your median is (MaxHeap.max()+MinHeap.min())/2 this takes O(1) also. Thus, the real cost of the whole operation is the heaps building operation which is O(n).

BTW this MaxHeap/MinHeap algorithm works also when you don't know the number of the array elements beforehand (if you have to resolve the same problem for a stream of integers for e.g). You can see more details about how to resolve this problem in the following article Median Of integer streams

Get jQuery version from inspecting the jQuery object

$().jquery will give you its version as a string.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

The page cannot be displayed because an internal server error has occurred on server

I just got this error and it was caused by a duplicate static content MIME type in the web.config

This error was being returned only on static files - eg images, css, js files were all saying this error (text by itself, no other html or text in the response).

The way to debug this is to look in web config under static content. Here we have a json file extension loaded. This was required on IIS7 but will kill the app if used on IIS8 because json is now pre-loaded at the server level.

    <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
        <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>

So solution is to remove any of these mimeType entries one at a time to confirm which are needed and which kill your app!

Update

Actually the best solution was provided by a commenter here. You can remove and then add, which will always work regardless of whether it is already defined or not. Like this:

<remove fileExtension=".json" /> 
<mimeMap fileExtension=".json" mimeType="application/json" />

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

How do you Programmatically Download a Webpage in Java

You'd most likely need to extract code from a secure web page (https protocol). In the following example, the html file is being saved into c:\temp\filename.html Enjoy!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * <b>Get the Html source from the secure url </b>
 */
public class HttpsClientUtil {
    public static void main(String[] args) throws Exception {
        String httpsURL = "https://stackoverflow.com";
        String FILENAME = "c:\\temp\\filename.html";
        BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));
        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
        con.setRequestProperty ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" );
        InputStream ins = con.getInputStream();
        InputStreamReader isr = new InputStreamReader(ins, "Windows-1252");
        BufferedReader in = new BufferedReader(isr);
        String inputLine;

        // Write each line into the file
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
            bw.write(inputLine);
        }
        in.close(); 
        bw.close();
    }
}

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Naming threads and thread-pools of ExecutorService

You could supply a ThreadFactory to newSingleThreadScheduledExecutor(ThreadFactory threadFactory). The factory will be responsibe for creating threads, and will be able to name them.

To quote the Javadoc:

Creating new threads

New threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks

svn list of files that are modified in local copy

Using Powershell you can do this:

# Checks for updates and changes in working copy.
# Regex: Excludes unmodified (first 7 columns blank). To exclude more add criteria to negative look ahead.
# -u: svn gets updates
$regex = '^(?!\s{7}).{7}\s+(.+)';
svn status -u | %{ if($_ -match $regex){ $_ } };

This will include property changes. These show in column 2. It will also catch other differences in files that show in columns 3-7.

Sources:

API vs. Webservice

An API (Application Programming Interface) is the means by which third parties can write code that interfaces with other code. A Web Service is a type of API, one that almost always operates over HTTP (though some, like SOAP, can use alternate transports, like SMTP). The official W3C definition mentions that Web Services don't necessarily use HTTP, but this is almost always the case and is usually assumed unless mentioned otherwise.

For examples of web services specifically, see SOAP, REST, and XML-RPC. For an example of another type of API, one written in C for use on a local machine, see the Linux Kernel API.

As far as the protocol goes, a Web service API almost always uses HTTP (hence the Web part), and definitely involves communication over a network. APIs in general can use any means of communication they wish. The Linux kernel API, for example, uses Interrupts to invoke the system calls that comprise its API for calls from user space.

What is the difference between encrypting and signing in asymmetric encryption?

In RSA crypto, when you generate a key pair, it's completely arbitrary which one you choose to be the public key, and which is the private key. If you encrypt with one, you can decrypt with the other - it works in both directions.

So, it's fairly simple to see how you can encrypt a message with the receiver's public key, so that the receiver can decrypt it with their private key.

A signature is proof that the signer has the private key that matches some public key. To do this, it would be enough to encrypt the message with that sender's private key, and include the encrypted version alongside the plaintext version. To verify the sender, decrypt the encrypted version, and check that it is the same as the plaintext.

Of course, this means that your message is not secret. Anyone can decrypt it, because the public key is well known. But when they do so, they have proved that the creator of the ciphertext has the corresponding private key.

However, this means doubling the size of your transmission - plaintext and ciphertext together (assuming you want people who aren't interested in verifying the signature, to read the message). So instead, typically a signature is created by creating a hash of the plaintext. It's important that fake hashes can't be created, so cryptographic hash algorithms such as SHA-2 are used.

So:

  • To generate a signature, make a hash from the plaintext, encrypt it with your private key, include it alongside the plaintext.
  • To verify a signature, make a hash from the plaintext, decrypt the signature with the sender's public key, check that both hashes are the same.

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

What are the true benefits of ExpandoObject?

The real benefit for me is the totally effortless data binding from XAML:

public dynamic SomeData { get; set; }

...

SomeData.WhatEver = "Yo Man!";

...

 <TextBlock Text="{Binding SomeData.WhatEver}" />

Java List.add() UnsupportedOperationException

Not every List implementation supports the add() method.

One common example is the List returned by Arrays.asList(): it is documented not to support any structural modification (i.e. removing or adding elements) (emphasis mine):

Returns a fixed-size list backed by the specified array.

Even if that's not the specific List you're trying to modify, the answer still applies to other List implementations that are either immutable or only allow some selected changes.

You can find out about this by reading the documentation of UnsupportedOperationException and List.add(), which documents this to be an "(optional operation)". The precise meaning of this phrase is explained at the top of the List documentation.

As a workaround you can create a copy of the list to a known-modifiable implementation like ArrayList:

seeAlso = new ArrayList<>(seeAlso);

Get current NSDate in timestamp format

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [NSString stringWithFormat:@"%lld",milliseconds];
NSLog(@"The Timestamp is = %@",strTimeStamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

Unable to launch the IIS Express Web server

I had the same problem, in my case I just cleaned and then rebuild my solution and it worked for me

How to "pretty" format JSON output in Ruby on Rails

Here is a middleware solution modified from this excellent answer by @gertas. This solution is not Rails specific--it should work with any Rack application.

The middleware technique used here, using #each, is explained at ASCIIcasts 151: Rack Middleware by Eifion Bedford.

This code goes in app/middleware/pretty_json_response.rb:

class PrettyJsonResponse

  def initialize(app)
    @app = app
  end

  def call(env)
    @status, @headers, @response = @app.call(env)
    [@status, @headers, self]
  end

  def each(&block)
    @response.each do |body|
      if @headers["Content-Type"] =~ /^application\/json/
        body = pretty_print(body)
      end
      block.call(body)
    end
  end

  private

  def pretty_print(json)
    obj = JSON.parse(json)  
    JSON.pretty_unparse(obj)
  end

end

To turn it on, add this to config/environments/test.rb and config/environments/development.rb:

config.middleware.use "PrettyJsonResponse"

As @gertas warns in his version of this solution, avoid using it in production. It's somewhat slow.

Tested with Rails 4.1.6.

What does the "More Columns than Column Names" error mean?

For the Germans:

you have to change your decimal commas into a Full stop in your csv-file (in Excel:File -> Options -> Advanced -> "Decimal seperator") , then the error is solved.

Room persistance library. Delete all

I had issues with delete all method when using RxJava to execute this task on background. This is how I finally solved it:

@Dao
interface UserDao {
    @Query("DELETE FROM User")
    fun deleteAll()
}

and

fun deleteAllUsers() {
    return Maybe.fromAction(userDao::deleteAll)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe ({
            d("database rows cleared: $it")
        }, {
            e(it)
        }).addTo(compositeDisposable)
}

How can I simulate an array variable in MySQL?

You can achieve this in MySQL using WHILE loop:

SET @myArrayOfValue = '2,5,2,23,6,';

WHILE (LOCATE(',', @myArrayOfValue) > 0)
DO
    SET @value = ELT(1, @myArrayOfValue);
    SET @myArrayOfValue= SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);

    INSERT INTO `EXEMPLE` VALUES(@value, 'hello');
END WHILE;

EDIT: Alternatively you can do it using UNION ALL:

INSERT INTO `EXEMPLE`
(
 `value`, `message`
)
(
 SELECT 2 AS `value`, 'hello' AS `message`
 UNION ALL
 SELECT 5 AS `value`, 'hello' AS `message`
 UNION ALL
 SELECT 2 AS `value`, 'hello' AS `message`
 UNION ALL
 ...
);

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

How to get parameters from the URL with JSP

www.somesite.com/Transaction_List.jsp?accountID=5

For this URL there is a method call request.getParameter in java , if you want a number here cast into int, similarly for string value cast into string. so for your requirement , just copy past below line in page,

int  accountId =(int)request.getParameter("accountID");

you can now call this value useing accountId in whole page.

here accountId is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET method if you hit POST request then their will be an error.

Hope this is helpful.

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Just answering the second part of your question about getting the name of the sheet where a table is:

Dim name as String

name = Range("Table1").Worksheet.Name

Edit:

To make things more clear: someone suggested that to use Range on a Sheet object. In this case, you need not; the Range where the table lives can be obtained using the table's name; this name is available throughout the book. So, calling Range alone works well.

Use a content script to access the page context variables and functions

Underlying cause:
Content scripts are executed in an "isolated world" environment.

Solution::
To access functions/variables of the page context ("main world") you have to inject the code into the page itself using DOM. Same thing if you want to expose your functions/variables to the page context (in your case it's the state() method).

  • Note in case communication with the page script is needed:
    Use DOM CustomEvent handler. Examples: one, two, and three.

  • Note in case chrome API is needed in the page script:
    Since chrome.* APIs can't be used in the page script, you have to use them in the content script and send the results to the page script via DOM messaging (see the note above).

Safety warning:
A page may redefine or augment/hook a built-in prototype so your exposed code may fail if the page did it in an incompatible fashion. If you want to make sure your exposed code runs in a safe environment then you should either a) declare your content script with "run_at": "document_start" and use Methods 2-3 not 1, or b) extract the original native built-ins via an empty iframe, example. Note that with document_start you may need to use DOMContentLoaded event inside the exposed code to wait for DOM.

Table of contents

  • Method 1: Inject another file
  • Method 2: Inject embedded code
  • Method 2b: Using a function
  • Method 3: Using an inline event
  • Dynamic values in the injected code

Method 1: Inject another file

This is the easiest/best method when you have lots of code. Include your actual JS code in a file within your extension, say script.js. Then let your content script be as follows (explained here: Google Chome “Application Shortcut” Custom Javascript):

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

Note: For security reasons, Chrome prevents loading of js files. Your file must be added as a "web_accessible_resources" item (example) :

// manifest.json must include: 
"web_accessible_resources": ["script.js"],

If not, the following error will appear in the console:

Denying load of chrome-extension://[EXTENSIONID]/script.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Method 2: Inject embedded code

This method is useful when you want to quickly run a small piece of code. (See also: How to disable facebook hotkeys with Chrome extension?).

var actualCode = `// Code here.
// If you want to use a variable, use $ and curly braces.
// For example, to use a fixed random number:
var someFixedRandomValue = ${ Math.random() };
// NOTE: Do not insert unsafe variables in this way, see below
// at "Dynamic values in the injected code"
`;

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

Note: template literals are only supported in Chrome 41 and above. If you want the extension to work in Chrome 40-, use:

var actualCode = ['/* Code here. Example: */' + 'alert(0);',
                  '// Beware! This array have to be joined',
                  '// using a newline. Otherwise, missing semicolons',
                  '// or single-line comments (//) will mess up your',
                  '// code ----->'].join('\n');

Method 2b: Using a function

For a big chunk of code, quoting the string is not feasible. Instead of using an array, a function can be used, and stringified:

var actualCode = '(' + function() {
    // All code is executed in a local scope.
    // For example, the following does NOT overwrite the global `alert` method
    var alert = null;
    // To overwrite a global variable, prefix `window`:
    window.alert = null;
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

This method works, because the + operator on strings and a function converts all objects to a string. If you intend on using the code more than once, it's wise to create a function to avoid code repetition. An implementation might look like:

function injectScript(func) {
    var actualCode = '(' + func + ')();'
    ...
}
injectScript(function() {
   alert("Injected script");
});

Note: Since the function is serialized, the original scope, and all bound properties are lost!

var scriptToInject = function() {
    console.log(typeof scriptToInject);
};
injectScript(scriptToInject);
// Console output:  "undefined"

Method 3: Using an inline event

Sometimes, you want to run some code immediately, e.g. to run some code before the <head> element is created. This can be done by inserting a <script> tag with textContent (see method 2/2b).

An alternative, but not recommended is to use inline events. It is not recommended because if the page defines a Content Security policy that forbids inline scripts, then inline event listeners are blocked. Inline scripts injected by the extension, on the other hand, still run. If you still want to use inline events, this is how:

var actualCode = '// Some code example \n' + 
                 'console.log(document.documentElement.outerHTML);';

document.documentElement.setAttribute('onreset', actualCode);
document.documentElement.dispatchEvent(new CustomEvent('reset'));
document.documentElement.removeAttribute('onreset');

Note: This method assumes that there are no other global event listeners that handle the reset event. If there is, you can also pick one of the other global events. Just open the JavaScript console (F12), type document.documentElement.on, and pick on of the available events.

Dynamic values in the injected code

Occasionally, you need to pass an arbitrary variable to the injected function. For example:

var GREETING = "Hi, I'm ";
var NAME = "Rob";
var scriptToInject = function() {
    alert(GREETING + NAME);
};

To inject this code, you need to pass the variables as arguments to the anonymous function. Be sure to implement it correctly! The following will not work:

var scriptToInject = function (GREETING, NAME) { ... };
var actualCode = '(' + scriptToInject + ')(' + GREETING + ',' + NAME + ')';
// The previous will work for numbers and booleans, but not strings.
// To see why, have a look at the resulting string:
var actualCode = "(function(GREETING, NAME) {...})(Hi, I'm ,Rob)";
//                                                 ^^^^^^^^ ^^^ No string literals!

The solution is to use JSON.stringify before passing the argument. Example:

var actualCode = '(' + function(greeting, name) { ...
} + ')(' + JSON.stringify(GREETING) + ',' + JSON.stringify(NAME) + ')';

If you have many variables, it's worthwhile to use JSON.stringify once, to improve readability, as follows:

...
} + ')(' + JSON.stringify([arg1, arg2, arg3, arg4]) + ')';

How to detect when keyboard is shown and hidden

Swift 4 - dd 20 october 2017

override func viewDidLoad() {
    [..]

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
}

@objc func keyboardWillAppear(_ notification: NSNotification) {
    if let userInfo = notification.userInfo, 
       let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue).cgRectValue {
           let inset = keyboardFrame.height // if scrollView is not aligned to bottom of screen, subtract offset
           scrollView.contentInset.bottom = inset
           scrollView.scrollIndicatorInsets.bottom = inset
    }
}

@objc func keyboardWillDisappear(_ notification: NSNotification) {
    scrollView.contentInset.bottom = 0
    scrollView.scrollIndicatorInsets.bottom = 0
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

How to suppress "unused parameter" warnings in C?

Labelling the attribute is ideal way. MACRO leads to sometime confusion. and by using void(x),we are adding an overhead in processing.

If not using input argument, use

void foo(int __attribute__((unused))key)
{
}

If not using the variable defined inside the function

void foo(int key)
{
   int hash = 0;
   int bkt __attribute__((unused)) = 0;

   api_call(x, hash, bkt);
}

Now later using the hash variable for your logic but doesn’t need bkt. define bkt as unused, otherwise compiler says'bkt set bt not used".

NOTE: This is just to suppress the warning not for optimization.

sql query to find the duplicate records

You can do it in a single query:

Select t.Id, t.title, z.dupCount
From yourtable T
Join
   (select title, Count (*) dupCount
    from yourtable 
    group By title
    Having Count(*) > 1) z
   On z.title = t.Title
order By dupCount Desc

How to check whether an object is a date?

The best way I found is:

!isNaN(Date.parse("some date test"))
//
!isNaN(Date.parse("22/05/2001"))  // true
!isNaN(Date.parse("blabla"))  // false

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

How do I get an OAuth 2.0 authentication token in C#

Here is a complete example. Right click on the solution to manage nuget packages and get Newtonsoft and RestSharp:

using Newtonsoft.Json.Linq;
using RestSharp;
using System;


namespace TestAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            String id = "xxx";
            String secret = "xxx";

            var client = new RestClient("https://xxx.xxx.com/services/api/oauth2/token");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            dynamic resp = JObject.Parse(response.Content);
            String token = resp.access_token;            

            client = new RestClient("https://xxx.xxx.com/services/api/x/users/v1/employees");
            request = new RestRequest(Method.GET);
            request.AddHeader("authorization", "Bearer " + token);
            request.AddHeader("cache-control", "no-cache");
            response = client.Execute(request);
        }        
    }
}

reactjs - how to set inline style of backgroundcolor?

If you want more than one style this is the correct full answer. This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>

convert NSDictionary to NSString

if you like to use for URLRequest httpBody

extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print: Fields=sdad&ServiceId=1222

PHP - Fatal error: Unsupported operand types

$total_ratings is an array, which you can't use for a division.

From above:

$total_ratings = mysqli_fetch_array($result);