Programs & Examples On #Voice recording

0

How can I use an http proxy with node.js http.Client?

One thing that took me a while to figure out, use 'http' to access the proxy, even if you're trying to proxy through to a https server. This works for me using Charles (osx protocol analyser):

var http = require('http');

http.get ({
    host: '127.0.0.1',
    port: 8888,
    path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
    console.log (response);
});

loading json data from local file into React JS

My JSON file name: terrifcalculatordata.json

[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]

First , import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>
                  

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN 
SELECT LAST_NAME,FRST_NAME  
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

Android - Using Custom Font

Provided that you placed the font in the right place and there is no error in the font file itself, your code should work like that, RATTLESNAKE.

However, it would be a lot easier if you could just define a font in your layout xml, like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <!-- This text view is styled with the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This uses my font in bold italic style" />

    <!-- This text view is styled here and overrides the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:flFont="anotherFont"
        android:textStyle="normal"
        android:text="This uses another font in normal style" />

    <!-- This text view is styled with a style and overrides the app theme -->
    <com.innovattic.font.FontTextView
        style="@style/StylishFont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This also uses another font in normal style" />

</LinearLayout>

With the accompanying res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <!-- Application theme -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:textViewStyle">@style/MyTextViewStyle</item>
    </style>

    <!-- Style to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextViewStyle" parent="@android:style/Widget.Holo.Light.TextView">
        <item name="android:textAppearance">@style/MyTextAppearance</item>
    </style>

    <!-- Text appearance to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextAppearance" parent="@android:style/TextAppearance.Holo">
        <!-- Alternatively, reference this font with the name "aspergit" -->
        <!-- Note that only our own TextView's will use the font attribute -->
        <item name="flFont">someFont</item>
        <item name="android:textStyle">bold|italic</item>
    </style>

    <!-- Alternative style, maybe for some other widget -->
    <style name="StylishFont">
        <item name="flFont">anotherFont</item>
        <item name="android:textStyle">normal</item>
    </style>

</resources>

I created a couple of tools specifically for this purpose. Refer to this project from GitHub, or take a look at this blog post which explains the whole thing.

Best way to get identity of inserted row?

I can't speak to other versions of SQL Server, but in 2012, outputting directly works just fine. You don't need to bother with a temporary table.

INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES (...)

By the way, this technique also works when inserting multiple rows.

INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES
    (...),
    (...),
    (...)

Output

ID
2
3
4

XAMPP installation on Win 8.1 with UAC Warning

change User Account Control setting via control panel

step 1 -: Go to control panel

step 2-: select 'user Accounts'

step 3-: select 'User Accounts' (Control Panel\User Accounts\User Accounts)

step 4 -: select 'Change User Account Control settings'

step 5 -: Drag the slider down to Never notify and after click ok.

Programmatically get the version number of a DLL

This works if the dll is .net or Win32. Reflection methods only work if the dll is .net. Also, if you use reflection, you have the overhead of loading the whole dll into memory. The below method does not load the assembly into memory.

// Get the file version.
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\MyAssembly.dll");

// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' +
                  "Version number: " + myFileVersionInfo.FileVersion);

From: http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx

original source

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

How to remove gaps between subplots in matplotlib?

With recent matplotlib versions you might want to try Constrained Layout. This does not work with plt.subplot() however, so you need to use plt.subplots() instead:

fig, axs = plt.subplots(4, 4, constrained_layout=True)

Rails: How do I create a default value for attributes in Rails activerecord's model?

You can do it without writing any code at all :) You just need to set the default value for the column in the database. You can do this in your migrations. For example:

create_table :projects do |t|
  t.string :status, :null => false, :default => 'P'
  ...
  t.timestamps
end

Hope that helps.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

How to open an elevated cmd using command line for Windows?

Press the Windows + X key and you can now select the Powershell or Command Prompt with admin rights. Works if you are the admin. The function can be unusable if the system is not yours.

Requery a subform from another form?

I had a similar kind of issue, but with some differences...

In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:

Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef

'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
            "[Qry_Pedidos distintos].[Codigo], " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
            "SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
            "FROM [Qry_Pedidos distintos] " & _
            "WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
            " Group BY " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "[Qry_Pedidos distintos].[Codigo];"
End Sub

Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".

But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:

Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query 
    Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)

'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
    Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub

No refresh, recalc, requery, etc, was necessary after all...

Angular2 *ngFor in select list, set active based on string from object

This should work

<option *ngFor="let title of titleArray" 
    [value]="title.Value" 
    [attr.selected]="passenger.Title==title.Text ? true : null">
  {{title.Text}}
</option>

I'm not sure the attr. part is necessary.

Kill tomcat service running on any port, Windows

Based on all the info on the post, I created a little script to make the whole process easy.

@ECHO OFF
netstat -aon |find /i "listening"

SET killport=
SET /P killport=Enter port: 
IF "%killport%"=="" GOTO Kill

netstat -aon |find /i "listening" | find "%killport%"

:Kill
SET killpid=
SET /P killpid=Enter PID to kill: 
IF "%killpid%"=="" GOTO Error

ECHO Killing %killpid%!
taskkill /F /PID %killpid%

GOTO End
:Error
ECHO Nothing to kill! Bye bye!!
:End

pause

How to get longitude and latitude of any address?

You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

How to set a cell to NaN in a pandas dataframe

You can use replace:

df['y'] = df['y'].replace({'N/A': np.nan})

Also be aware of the inplace parameter for replace. You can do something like:

df.replace({'N/A': np.nan}, inplace=True)

This will replace all instances in the df without creating a copy.

Similarly, if you run into other types of unknown values such as empty string or None value:

df['y'] = df['y'].replace({'': np.nan})

df['y'] = df['y'].replace({None: np.nan})

Reference: Pandas Latest - Replace

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece (in core since Perl 5.10) also has a strftime function and by default overloads localtime and gmtime to return Time::Piece objects:

use Time::Piece;
print localtime->strftime('%Y-%m-%d');

or without the overridden localtime:

use Time::Piece (); 
print Time::Piece::localtime->strftime('%F %T');

Parsing CSV / tab-delimited txt file with Python

Start by turning the text into a list of lists. That will take care of the parsing part:

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))

The rest can be done with indexed lookups:

d = dict()
key = lol[6][0]      # cell A7
value = lol[6][3]    # cell D7
d[key] = value       # add the entry to the dictionary
 ...

Javascript negative number

If you really want to dive into it and even need to distinguish between -0 and 0, here's a way to do it.

function negative(number) {
  return !Object.is(Math.abs(number), +number);
}

console.log(negative(-1));  // true
console.log(negative(1));   // false
console.log(negative(0));   // false
console.log(negative(-0));  // true

How to change color and font on ListView

If you want to use a color from colors.xml , experiment :

   public View getView(int position, View convertView, ViewGroup parent) {
        ... 
        View rowView = inflater.inflate(this.rowLayoutID, parent, false);
        rowView.setBackgroundColor(rowView.getResources().getColor(R.color.my_bg_color));
        TextView title = (TextView) rowView.findViewById(R.id.txtRowTitle);
        title.setTextColor(
            rowView.getResources().getColor(R.color.my_title_color));
        ...
     }

You can use too:

private static final int bgColor = 0xAAAAFFFF;
public View getView(int position, View convertView, ViewGroup parent) {
        ... 
        View rowView = inflater.inflate(this.rowLayoutID, parent, false);
            rowView.setBackgroundColor(bgColor);
...
}

Left Outer Join using + sign in Oracle 11g

LEFT OUTER JOIN

SELECT * FROM A, B WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT * FROM A, B WHERE A.column (+)= B.column

Reset ID autoincrement ? phpmyadmin

I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.

ALTER TABLE users DROP id

The above sql can be run via sql query or as php. This will delete the id column.

Then re add it again, via the code below:

ALTER TABLE  `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST

Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.

TabLayout tab selection

If you can't use tab.select() and you don't want to use a ViewPager, you can still programmatically select a tab. If you're using a custom view through TabLayout.Tab setCustomView(android.view.View view) it is simpler. Here's how to do it both ways.

// if you've set a custom view
void updateTabSelection(int position) {
    // get the position of the currently selected tab and set selected to false
    mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(false);
    // set selected to true on the desired tab
    mTabLayout.getTabAt(position).getCustomView().setSelected(true);
    // move the selection indicator
    mTabLayout.setScrollPosition(position, 0, true);

    // ... your logic to swap out your fragments
}

If you aren't using a custom view then you can do it like this

// if you are not using a custom view
void updateTabSelection(int position) {
    // get a reference to the tabs container view
    LinearLayout ll = (LinearLayout) mTabLayout.getChildAt(0);
    // get the child view at the position of the currently selected tab and set selected to false
    ll.getChildAt(mTabLayout.getSelectedTabPosition()).setSelected(false);
    // get the child view at the new selected position and set selected to true
    ll.getChildAt(position).setSelected(true);
    // move the selection indicator
    mTabLayout.setScrollPosition(position, 0, true);

    // ... your logic to swap out your fragments
}

Use a StateListDrawable to toggle between selected and unselected drawables or something similar to do what you want with colors and/or drawables.

Highest Salary in each department

SELECT empname
FROM empdetails
WHERE salary IN(SELECT deptid max(salary) AS salary
FROM empdetails
group by deptid)

React JS Error: is not defined react/jsx-no-undef

Try using

import Map from './Map';

When you use import 'module' it will just run the module as a script. This is useful when you are trying to introduce side-effects into global namespace, e. g. polyfill newer features for older/unsupported browsers.

ES6 modules are allowed to define default exports and regular exports. When you use the syntax import defaultExport from 'module' it will import the default export of that module with alias defaultExport.

For further reading on ES6 import - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No, it is not possible.

Consider a scenario where an ACBus is a derived class of base class Bus. ACBus has features like TurnOnAC and TurnOffAC which operate on a field named ACState. TurnOnAC sets ACState to on and TurnOffAC sets ACState to off. If you try to use TurnOnAC and TurnOffAC features on Bus, it makes no sense.

Get the IP Address of local computer

The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it:

fe80::1%lo0  
127.0.0.1 
::1 
fe80::21f:5bff:fe3f:1b36%en1 
10.0.0.138 
172.16.175.1
192.168.27.1

... and it's not just a matter of figuring out which of the above is "the real IP address", either... they are all "real" and useful; some more useful than others depending on what you are going to use the addresses for.

In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the relevant IP address is, given the context of the computer you are communicating with.

That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in this file.

Remove border radius from Select tag in bootstrap 3

Here is a version that works in all modern browsers. The key is using appearance:none which removes the default formatting. Since all of the formatting is gone, you have to add back in the arrow that visually differentiates the select from the input. Note: appearance is not supported in IE.

Working example: https://jsfiddle.net/gs2q1c7p/

_x000D_
_x000D_
select:not([multiple]) {_x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    background-position: right 50%;_x000D_
    background-repeat: no-repeat;_x000D_
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAMCAYAAABSgIzaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDZFNDEwNjlGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDZFNDEwNkFGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0NkU0MTA2N0Y3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0NkU0MTA2OEY3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuGsgwQAAAA5SURBVHjaYvz//z8DOYCJgUxAf42MQIzTk0D/M+KzkRGPoQSdykiKJrBGpOhgJFYTWNEIiEeAAAMAzNENEOH+do8AAAAASUVORK5CYII=);_x000D_
    padding: .5em;_x000D_
    padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
    border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
    <option>Option 1</option>_x000D_
    <option>Option 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Based on Arno Tenkink's suggestion in the comments, here is an example using a instead of a for the arrow icon.

_x000D_
_x000D_
select:not([multiple]) {_x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    background-position: right 50%;_x000D_
    background-repeat: no-repeat;_x000D_
    background-image: url('data:image/svg+xml;utf8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1"><path d="M4 8L0 4h8z"/></svg>');_x000D_
    padding: .5em;_x000D_
    padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
    border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
    <option>Option 1</option>_x000D_
    <option>Option 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to sort a List of objects by their date (java collections, List<Object>)

Do not access or modify the collection in the Comparator. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.

Date itself is comparable, so, using generics:

class MovieComparator implements Comparator<Movie> {
    public int compare(Movie m1, Movie m2) {
       //possibly check for nulls to avoid NullPointerException
       return m1.getDate().compareTo(m2.getDate());
    }
}

And do not instantiate the comparator on each sort. Use:

private static final MovieComparator comparator = new MovieComparator();

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

When to use Comparable and Comparator

I have been asked sorting of a definite range of numbers in better than nlogn time in one of interview. (Not using Counting sort)

Implementing Comparable interface over an object allows implicit sorting algos to use overridden compareTo method to order sort elements and that would be linear time.

Reload the page after ajax success

You use the ajaxStop to execute code when the ajax are completed:

$(document).ajaxStop(function(){
  setTimeout("window.location = 'otherpage.html'",100);
});

how to fetch array keys with jQuery?

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

What had caused this error on my side was the following line

include_once dirname(__FILE__) . './Config.php';

I managed to realize it was the culprit when i added the lines:

//error_reporting(E_ALL | E_DEPRECATED | E_STRICT);
//ini_set('display_errors', 1);

to all my php files.

To solve the path issue i canged the offending line to:

include_once dirname(__FILE__) . '/Config.php';

How to add text at the end of each line in Vim?

Following Macro can also be used to accomplish your task.

qqA,^[0jq4@q

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial: https://spring.io/guides/gs/rest-service-cors/

jQuery UI dialog box not positioned center screen

to position the dialog in the center of the screen :

$('#my-selector').parent().position({
                    my: "center",
                    at: "center",
                    of: window
});

What is the difference between screenX/Y, clientX/Y and pageX/Y?

Here's a picture explaining the difference between pageY and clientY.

pageY vs clientY

Same for pageX and clientX, respectively.


pageX/Y coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),

while clientX/Y coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.

See Demo

You'll probably never need screenX/Y

Get generic type of java.util.List

Use Reflection to get the Field for these then you can just do: field.genericType to get the type that contains the information about generic as well.

Add spaces between the characters of a string in Java?

Create a StringBuilder with the string and use one of its insert overloaded method:

StringBuilder sb = new StringBuilder("JAYARAM");
for (int i=1; i<sb.length(); i+=2)
    sb.insert(i, ' ');
System.out.println(sb.toString());

The above prints:

J A Y A R A M

how to open a jar file in Eclipse

Since the jar file 'executes' then it contains compiled java files known as .class files. You cannot import it to eclipse and modify the code. You should ask the supplier of the "demo" for the "source code". (or check the page you got the demo from for the source code)

Unless, you want to decompile the .class files and import to Eclipse. That may not be the case for starters.

Datatable select with multiple conditions

Dim dr As DataRow()


dr = dt.Select("A="& a & "and B="& b & "and C=" & c,"A",DataViewRowState.CurrentRows)

Where A,B,C are the column names where second parameter is for sort expression

Export database schema into SQL file

enter image description here

In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data

Calling async method synchronously

You should get the awaiter (GetAwaiter()) and end the wait for the completion of the asynchronous task (GetResult()).

string code = GenerateCodeAsync().GetAwaiter().GetResult();

List all files from a directory recursively with Java

I personally like this version of FileUtils. Here's an example that finds all mp3s or flacs in a directory or any of its subdirectories:

String[] types = {"mp3", "flac"};
Collection<File> files2 = FileUtils.listFiles(/path/to/your/dir, types , true);

How can I disable a button in a jQuery dialog from a function?

It's very simple:

$(":button:contains('Authenticate')").prop("disabled", true).addClass("ui-state-disabled");

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

The simplest general function to find the positive modulo would be this- It would work on both positive and negative values of x.

int modulo(int x,int N){
    return (x % N + N) %N;
}

Find max and second max salary for a employee table MySQL

For unique salaries (i.e. first can't be same as second):

SELECT
  MAX( s.salary ) AS max_salary,
  (SELECT
     MAX( salary ) 
   FROM salaries
   WHERE salary <> MAX( s.salary ) 
   ORDER BY salary DESC 
   LIMIT 1
  ) AS 2nd_max_salary
FROM salaries s

And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)

Strip out HTML and Special Characters

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));

Choosing the default value of an Enum type without having to change values

The default for an enum (in fact, any value type) is 0 -- even if that is not a valid value for that enum. It cannot be changed.

How do I set a value in CKEditor with Javascript?

<textarea id="editor1" name="editor1">This is sample text</textarea>

<div id="trackingDiv" ></div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );

</script>

Let try this..

Update :

To set data :

Create instance First::

var editor = CKEDITOR.instances['editor1'];

Then,

editor.setData('your data');

or

editor.insertHtml('your html data');

or

editor.insertText('your text data');  

And Retrieve data from your editor::

editor.getData();

If change the particular para HTML data in CKEditor.

var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');

These are the possible ways that I know in CKEditor

How many parameters are too many?

I would base my answer on how often the function is called.

If it is an init function that is only ever called once then let it take 10 parms or more, who cares.

If it is called a bunch of times per frame then I tend to make a structure and just pass a pointer to it since that tends to be faster ( assuming that you are not rebuilding the struct every time as well ).

What is a reasonable code coverage % for unit tests (and why)?

It depends greatly on your application. For example, some applications consist mostly of GUI code that cannot be unit tested.

Convert JS object to JSON string

For debugging in Node JS you can use util.inspect(). It works better with circular references.

var util = require('util');
var j = {name: "binchen"};
console.log(util.inspect(j));

Android studio takes too much memory

I fond this YouTube video from Google where are some tips and tricks for it. The video also includes advantages and disadvantages of suggested changes.

Improving Android Studio Performance on Memory-Constrained Machines

HTML5 phone number validation with pattern

This code will accept all country code with + sign

<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>

Some countries allow a single "0" character instead of "+" and others a double "0" character instead of the "+". Neither are standard.

What's the best way to do a backwards loop in C/C#/C++?

In C# using Linq:

foreach(var item in myArray.Reverse())
{
    // do something
}

How do I retrieve an HTML element's actual width and height?

element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.

Join/Where with LINQ and Lambda

It could be something like

var myvar = from a in context.MyEntity
            join b in context.MyEntity2 on a.key equals b.key
            select new { prop1 = a.prop1, prop2= b.prop1};

Convert JSON String To C# Object

Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.

  public class Student
{
   public string FirstName {get;set:}
   public string LastName {get;set:}
   public int[] Grades {get;set:}
}

public static Student ConvertToStudent(string std)
{
  var serializer = new JavaScriptSerializer();

  Return serializer.Deserialize<Student>(std);
 }

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Bluetooth pairing without user confirmation

Yes it is possible in theory as defined by the specification. However there is no practical implementation as yet that would allow this.

Refer: NFC Forum Connection Handover Technical Specification http://www.nfc-forum.org/specs/spec_list/

Quoting from the specification regarding the security - "The Handover Protocol requires transmission of network access data and credentials (the carrier configuration data) to allow one device to connect to a wireless network provided by another device. Because of the close proximity needed for communication between NFC Devices and Tags, eavesdropping of carrier configuration data is difficult, but not impossible, without recognition by the legitimate owner of the devices. Transmission of carrier configuration data to devices that can be brought to close proximity is deemed legitimate within the scope of this specification."

Java HashMap performance optimization / alternative

You could try to cache computed hash code to the key object.

Something like this:

public int hashCode() {
  if(this.hashCode == null) {
     this.hashCode = computeHashCode();
  }
  return this.hashCode;
}

private int computeHashCode() {
   int hash = 503;
   hash = hash * 5381 + (a[0] + a[1]);
   hash = hash * 5381 + (b[0] + b[1] + b[2]);
   return hash;
}

Of course you have to be careful not to change contents of the key after the hashCode has been calculated for the first time.

Edit: It seems that caching has code values is not worthwhile when you are adding each key only once to a map. In some other situation this could be useful.

Reading a plain text file in Java

The most intuitive method is introduced in Java 11 Files.readString

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String args[]) throws IOException {
        String content = Files.readString(Paths.get("D:\\sandbox\\mvn\\my-app\\my-app.iml"));
        System.out.print(content);
    }
}

PHP has this luxury from decades ago! ?

What is monkey patching?

What is monkey patching? Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.

Why use monkey patching? It allows us to modify or extend the behavior of libraries, modules, classes or methods at runtime without actually modifying the source code

Conclusion Monkey patching is a cool technique and now we have learned how to do that in Python. However, as we discussed, it has its own drawbacks and should be used carefully.

For more info Please refer [1]: https://medium.com/@nagillavenkatesh1234/monkey-patching-in-python-explained-with-examples-25eed0aea505

Compare two dates in Java

This is a very old post though sharing my work. Here is a little trick to do so

DateTime dtStart = new DateTime(Dateforcomparision); 
DateTime dtNow = new DateTime(); //current date

if(dtStart.getMillis() <= dtNow.getMillis())
{
   //to do
}

use comparator as per your requirement

What's the difference between text/xml vs application/xml for webservice response

According to this article application/xml is preferred.


EDIT

I did a little follow-up on the article.

The author claims that the encoding declared in XML processing instructions, like:

<?xml version="1.0" encoding="UTF-8"?>

can be ignored when text/xml media type is used.

They support the thesis with the definition of text/* MIME type family specification in RFC 2046, specifically the following fragment:

4.1.2.  Charset Parameter

   A critical parameter that may be specified in the Content-Type field
   for "text/plain" data is the character set.  This is specified with a
   "charset" parameter, as in:

     Content-type: text/plain; charset=iso-8859-1

   Unlike some other parameter values, the values of the charset
   parameter are NOT case sensitive.  The default character set, which
   must be assumed in the absence of a charset parameter, is US-ASCII.

   The specification for any future subtypes of "text" must specify
   whether or not they will also utilize a "charset" parameter, and may
   possibly restrict its values as well.  For other subtypes of "text"
   than "text/plain", the semantics of the "charset" parameter should be
   defined to be identical to those specified here for "text/plain",
   i.e., the body consists entirely of characters in the given charset.
   In particular, definers of future "text" subtypes should pay close
   attention to the implications of multioctet character sets for their
   subtype definitions.

According to them, such difficulties can be avoided when using application/xml MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.

How can I solve ORA-00911: invalid character error?

Remove the semicolon (;), backtick (``) etc. from inside a query

"Could not find or load main class" Error while running java program using cmd prompt

What's your CLASSPATH value?

It may look like this:

 .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar 

I guess your value does not contain this .;.

So, ADD IT .
When you done , restart CMD

That may works.


For example the file HelloWorld.java is in path: D:\myjavatest\org\yz\test and its package is: org.yz.test.

Now, you're in path D:\myjavatest\ on the CMD line.
Type this to compile it:

javac org/yz/test/HelloWorld.java

Then, type this to run it:

java org.yz.test.HelloWorld

You may get what you want.

fork() child and parent processes

We control fork() process call by if, else statement. See my code below:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

This is OK too; For example:
==> In "NumberController" file:

public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
    if (ModelState.IsValid)
    {
        ...
        ...
        return RedirectToAction("Index");
    }
    ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", 
                                "OperatorSign", number.OperatorId);                
    return View();
}

==> In View file (Create.cshtml):

<div class="form-group">
    @Html.LabelFor(model => model.Number1, htmlAttributes: new { @class = 
                   "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Number1, new { htmlAttributes = new { 
                        @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Number1, "", new { @class = 
                                   "text-danger" })
    </div>
</div>

Now if we remove this statement:

ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);

from back of the following statement (in our controller) :

return View();

we will see this error:

There is no ViewData item of type 'IEnumerable' that has the key 'OperatorId'.

* So be sure of the existing of these statements. *

How to remove indentation from an unordered list item?

I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:

footer div ul {
    list-style-position: inside;
    padding-left: 0;
}

This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.

Load vs. Stress testing

Load Testing: Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Example For example, to check the email functionality of an application, it could be flooded with 1000 users at a time. Now, 1000 users can fire the email transactions (read, send, delete, forward, reply) in many different ways. If we take one transaction per user per hour, then it would be 1000 transactions per hour. By simulating 10 transactions/user, we could load test the email server by occupying it with 10000 transactions/hour.

Stress Testing: Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

Example: As an example, a word processor like Writer1.1.0 by OpenOffice.org is utilized in development of letters, presentations, spread sheets etc… Purpose of our stress testing is to load it with the excess of characters.

To do this, we will repeatedly paste a line of data, till it reaches its threshold limit of handling large volume of text. As soon as the character size reaches 65,535 characters, it would simply refuse to accept more data. The result of stress testing on Writer 1.1.0 produces the result that, it does not crash under the stress and that it handle the situation gracefully, which make sure that application is working correctly even under rigorous stress conditions.

Not equal <> != operator on NULL

I just don't see the functional and seamless reason for nulls not to be comparable to other values or other nulls, cause we can clearly compare it and say they are the same or not in our context. It's funny. Just because of some logical conclusions and consistency we need to bother constantly with it. It's not functional, make it more functional and leave it to philosophers and scientists to conclude if it's consistent or not and does it hold "universal logic". :) Someone may say that it's because of indexes or something else, I doubt that those things couldn't be made to support nulls same as values. It's same as comparing two empty glasses, one is vine glass and other is beer glass, we are not comparing the types of objects but values they contain, same as you could compare int and varchar, with null it's even easier, it's nothing and what two nothingness have in common, they are the same, clearly comparable by me and by everyone else that write sql, because we are constantly breaking that logic by comparing them in weird ways because of some ANSI standards. Why not use computer power to do it for us and I doubt it would slow things down if everything related is constructed with that in mind. "It's not null it's nothing", it's not apple it's apfel, come on... Functionally is your friend and there is also logic here. In the end only thing that matter is functionality and does using nulls in that way brings more or less functionality and ease of use. Is it more useful?

Consider this code:

SELECT CASE WHEN NOT (1 = null or (1 is null and null is null)) THEN 1 ELSE 0 end

How many of you knows what will this code return? With or without NOT it returns 0. To me that is not functional and it's confusing. In c# it's all as it should be, comparison operations return value, logically this too produces value, because if it didn't there is nothing to compare (except. nothing :) ). They just "said": anything compared to null "returns" 0 and that creates many workarounds and headaches.

This is the code that brought me here:

where a != b OR (a is null and b IS not null) OR (a IS not null and b IS null)

I just need to compare if two fields (in where) have different values, I could use function, but...

afxwin.h file is missing in VC++ Express Edition

I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.

So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.

Regex for not empty and not whitespace

In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:

(.|\s)*\S(.|\s)*

- this matches any string containing at least one non-whitespace character (the \S in the middle). It can be preceded and followed by anything, any char or whitespace sequence (including new lines) - (.|\s)*.

You can try it with explanation on https://regex101.com/.

Could not load file or assembly 'System.Data.SQLite'

As someone who's had to deal with quite a few bug reports on Roadkill Wiki with exactly the same issue, this is what you need to do:

  • Are you using x64 or x86? Sqlite comes with DLLs for separate architectures - copy the right one to your bin folder, there are two DLLS for the official provider: System.Data.SQLite.dll System.Data.SQLite.Linq.dll
  • If you can't be bothered hunting around for these assemblies, enable 32 bit mode for your App Pool (a solution for dev machines only usually)
  • If you're hosting on a server, you'll need the Microsoft C++ Runtime redistributable - it's not installed on Server 2008 R2 by default. x64 version, x86 version

It's a real pain in the ass how many hoops you have to jump through when re-distributing the SQLite .NET binaries, my solution for Roadkill in the end was to copy the correct binaries to the ~/bin folder based on the architecture your using. Unfortunately that doesn't solve the C++ runtime issue.

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

What is default list styling (CSS)?

I used to set this CSS to remove the reset :

ul { 
   list-style-type: disc; 
   list-style-position: inside; 
}
ol { 
   list-style-type: decimal; 
   list-style-position: inside; 
}
ul ul, ol ul { 
   list-style-type: circle; 
   list-style-position: inside; 
   margin-left: 15px; 
}
ol ol, ul ol { 
   list-style-type: lower-latin; 
   list-style-position: inside; 
   margin-left: 15px; 
}

EDIT : with a specific class of course...

Show a div with Fancybox

I use approach with appending "singleton" link for element you want to show in fancybox. This is code, what I use with some minor edits:

function showElementInPopUp(elementId) {
    var fancyboxAnchorElementId = "fancyboxTriggerFor_" + elementId;
    if ($("#"+fancyboxAnchorElementId).length == 0) {
        $("body").append("<a id='" + fancyboxAnchorElementId + "' href='#" + elementId+ "' style='display:none;'></a>");
        $("#"+fancyboxAnchorElementId).fancybox();
    }

    $("#" + fancyboxAnchorElementId).click();
}

Additional explanation: If you show fancybox with "content" option, it will duplicate DOM, which is inside elements. Sometimes this is not OK. In my case I needed to have the same elements, because they were used in form.

Match the path of a URL, minus the filename extension

Simple:

$url = "http://php.net/manual/en/function.preg-match.php";
preg_match("/http:\/\/php\.net(.+)\.php/", $url, $matches);
echo $matches[1];

$matches[0] is your full URL, $matches[1] is the part you want.

See yourself: http://codepad.viper-7.com/hHmwI2

Using StringWriter for XML Serialization

<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).

The fix should have been as simple as:

  1. In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.
  2. In the second case, when adding the declaration stating encoding="utf-16": either
    1. simply don't add the XML declaration, OR
    2. simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)


All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.

It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:

  1. The XML declaration is optional
  2. The XML datatype stores strings always as UCS-2 / UTF-16 LE
  3. If your XML is UCS-2 / UTF-16 LE, then you:
    1. pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".
    2. if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)
  4. If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:
    1. need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database
    2. you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".
    3. Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.
    4. The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.

On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.

For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:

-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>

As you can see, it even handles characters beyond standard ASCII, given that ? is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:

-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';

results in the following error:

Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:

You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:

-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

How do I work with dynamic multi-dimensional arrays in C?

Basics

Arrays in c are declared and accessed using the [] operator. So that

int ary1[5];

declares an array of 5 integers. Elements are numbered from zero so ary1[0] is the first element, and ary1[4] is the last element. Note1: There is no default initialization, so the memory occupied by the array may initially contain anything. Note2: ary1[5] accesses memory in an undefined state (which may not even be accessible to you), so don't do it!

Multi-dimensional arrays are implemented as an array of arrays (of arrays (of ... ) ). So

float ary2[3][5];

declares an array of 3 one-dimensional arrays of 5 floating point numbers each. Now ary2[0][0] is the first element of the first array, ary2[0][4] is the last element of the first array, and ary2[2][4] is the last element of the last array. The '89 standard requires this data to be contiguous (sec. A8.6.2 on page 216 of my K&R 2nd. ed.) but seems to be agnostic on padding.

Trying to go dynamic in more than one dimension

If you don't know the size of the array at compile time, you'll want to dynamically allocate the array. It is tempting to try

double *buf3;
buf3 = malloc(3*5*sizeof(double));
/* error checking goes here */

which should work if the compiler does not pad the allocation (stick extra space between the one-dimensional arrays). It might be safer to go with:

double *buf4;
buf4 = malloc(sizeof(double[3][5]));
/* error checking */

but either way the trick comes at dereferencing time. You can't write buf[i][j] because buf has the wrong type. Nor can you use

double **hdl4 = (double**)buf;
hdl4[2][3] = 0; /* Wrong! */

because the compiler expects hdl4 to be the address of an address of a double. Nor can you use double incomplete_ary4[][]; because this is an error;

So what can you do?

  • Do the row and column arithmetic yourself
  • Allocate and do the work in a function
  • Use an array of pointers (the mechanism qrdl is talking about)

Do the math yourself

Simply compute memory offset to each element like this:

  for (i=0; i<3; ++i){
     for(j=0; j<3; ++j){
        buf3[i * 5 + j] = someValue(i,j); /* Don't need to worry about 
                                             padding in this case */
     }
  }

Allocate and do the work in a function

Define a function that takes the needed size as an argument and proceed as normal

void dary(int x, int y){
  double ary4[x][y];
  ary4[2][3] = 5;
}

Of course, in this case ary4 is a local variable and you can not return it: all the work with the array must be done in the function you call of in functions that it calls.

An array of pointers

Consider this:

double **hdl5 = malloc(3*sizeof(double*));
/* Error checking */
for (i=0; i<3; ++i){
   hdl5[i] = malloc(5*sizeof(double))
   /* Error checking */
}

Now hdl5 points to an array of pointers each of which points to an array of doubles. The cool bit is that you can use the two-dimensional array notation to access this structure---hdl5[0][2] gets the middle element of the first row---but this is none-the-less a different kind of object than a two-dimensional array declared by double ary[3][5];.

This structure is more flexible then a two dimensional array (because the rows need not be the same length), but accessing it will generally be slower and it requires more memory (you need a place to hold the intermediate pointers).

Note that since I haven't setup any guards you'll have to keep track of the size of all the arrays yourself.

Arithmetic

c provides no support for vector, matrix or tensor math, you'll have to implement it yourself, or bring in a library.

Multiplication by a scaler and addition and subtraction of arrays of the same rank are easy: just loop over the elements and perform the operation as you go. Inner products are similarly straight forward.

Outer products mean more loops.

Webpack not excluding node_modules

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
  2. Use webpack-node-externals in order to exclude other node_modules.

So your result config file should look like:

var nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc. 
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
    ...
};

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

The bootstrap docs do explain it, but it still took me a while to get it. It makes more sense when I explain it to myself in one of two ways:

If you think of the columns starting out horizontally, then you can choose when you want them to stack.

For example, if you start with columns: A B C

You decide when should they stack to be like this:

A

B

C

If you choose col-lg, then the columns will stack when the width is < 1200px.

If you choose col-md, then the columns will stack when the width is < 992px.

If you choose col-sm, then the columns will stack when the width is < 768px.

If you choose col-xs, then the columns will never stack.

On the other hand, if you think of the columns starting out stacked, then you can choose at what point they become horizontal:

If you choose col-sm, then the columns will become horizontal when the width is >= 768px.

If you choose col-md, then the columns will become horizontal when the width is >= 992px.

If you choose col-lg, then the columns will become horizontal when the width is >= 1200px.

how to call a variable in code behind to aspx page

You can access a public/protected property using the data binding expression <%# myproperty %> as given below:

    <asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>

you should call DataBind method, otherwise it can't be evaluated.

    public partial class WebForm1 : System.Web.UI.Page
    {
     public string CodeBehindVarPublic { get; set; }
      protected void Page_Load(object sender, EventArgs e)
        {
          CodeBehindVarPublic ="xyz";
       //you should call the next line  in case of using <%#CodeBehindVarPublic %>

          DataBind();
        }

}

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

How do you get a query string on Flask?

Werkzeug/Flask as already parsed everything for you. No need to do the same work again with urlparse:

from flask import request

@app.route('/')
@app.route('/data')
def data():
    query_string = request.query_string  ## There is it
    return render_template("data.html")

The full documentation for the request and response objects is in Werkzeug: http://werkzeug.pocoo.org/docs/wrappers/

jQuery: Check if div with certain class name exists

To test for div elements explicitly:

if( $('div.mydivclass').length ){...}

Differences between cookies and sessions?

Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.

MSSQL Select statement with incremental integer column... not from a table

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

Efficiently updating database using SQLAlchemy ORM

session.query(Clients).filter(Clients.id == client_id_list).update({'status': status})
session.commit()

Try this =)

jQuery hyperlinks - href value?

I almost had this problem and it was very deceiving. I am providing an answer in case someone winds up in my same position.

  1. I thought I had this problem
  2. But, I was using return false and javascript:void(0);
  3. Then a distinct difference in problem kept surfacing:
  4. I realized it's not going ALL the way to the top - and my problem zone was near the bottom of the page so this jump was strange and annoying.
  5. I realized I was using fadeIn() [jQuery library], which for a short time my content was display:none
  6. And then my content extended the reach of the page! Causing what looks like a jump!
  7. Using visibility hidden toggles now..

Hope this helps the person stuck with jumps!!

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I also had this issue - However it was for a completely different reason then any I have seen online. I realized that my app did not have the proper iOS Provisioning profile associated for app store release. I simply changed the build number, validated and resubmitted. Within 15 minutes, the new version was ready to be added as a current build. The previous two versions I tried to upload are both still processing.

I am not sure why Apple does not tell you that there is an incorrect provisioning profile for the build to be uploaded, but this was my cure!

Padding between ActionBar's home icon and title

<string name="app_name">"    "Brick Industry</string>

Just add " " for your app name It will add space between icon and title

AngularJS $http-post - convert binary to excel file and download

Worked for me -

$scope.downloadFile = function () {
        Resource.downloadFile().then(function (response) {
            var blob = new Blob([response.data], { type: "application/pdf" });
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        },
        function (error) {
            debugger;
        });
    };

Which calls the following from my resource factory-

  downloadFile: function () {
           var downloadRequst = {
                method: 'GET',
                url: 'http://localhost/api/downloadFile?fileId=dfckn4niudsifdh.pdf',
                headers: {
                    'Content-Type': "application/pdf",
                    'Accept': "application/pdf"
                },
                responseType: 'arraybuffer'
            }

            return $http(downloadRequst);
        }

Make sure your API sets the header content type too -

        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

Creating NSData from NSString in Swift

Swift 4 & 3

Creating Data object from String object has been changed in Swift 3. Correct version now is:

let data = "any string".data(using: .utf8)

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

Note: see the warning in the comments about how this can affect Electron applications.

As of v8.0 shipped August 2017, the NODE_OPTIONS environment variable exposes this configuration (see NODE_OPTIONS has landed in 8.x!). Per the article, only options whitelisted in the source (note: not an up-to-date-link!) are permitted, which includes "--max_old_space_size". Note that this article's title seems a bit misleading - it seems NODE_OPTIONS had already existed, but I'm not sure it exposed this option.

So I put in my .bashrc:
export NODE_OPTIONS=--max_old_space_size=4096

Local variable referenced before assignment?

Put a global statement at the top of your function and you should be good:

def onLoadFinished(result):
    global feed
    ...

To demonstrate what I mean, look at this little test:

x = 0
def t():
    x += 1
t()

this blows up with your exact same error where as:

x = 0
def t():
    global x
    x += 1
t()

does not.

The reason for this is that, inside t, Python thinks that x is a local variable. Furthermore, unless you explicitly tell it that x is global, it will try to use a local variable named x in x += 1. But, since there is no x defined in the local scope of t, it throws an error.

Making a WinForms TextBox behave like your browser's address bar

Very simple solution:

    private bool _focusing = false;

    protected override void OnEnter( EventArgs e )
    {
        _focusing = true;
        base.OnEnter( e );
    }

    protected override void OnMouseUp( MouseEventArgs mevent )
    {
        base.OnMouseUp( mevent );

        if( _focusing )
        {
            this.SelectAll();
            _focusing = false;
        }
    }

EDIT: Original OP was in particular concerned about the mouse-down / text-selection / mouse-up sequence, in which case the above simple solution would end up with text being partially selected.

This should solve* the problem (in practice I intercept WM_SETCURSOR):

    protected override void WndProc( ref Message m )
    {
        if( m.Msg == 32 ) //WM_SETCURSOR=0x20
        {
              this.SelectAll(); // or your custom logic here                
        }

        base.WndProc( ref m );
    }

*Actually the following sequence ends up with partial text selection but then if you move the mouse over the textbox all text will be selected again:

mouse-down / text-selection / mouse-move-out-textbox / mouse-up

Gradle proxy configuration

There are 2 ways for using Gradle behind a proxy :

Add arguments in command line

(From Guillaume Berche's post)

Add these arguments in your gradle command :

-Dhttp.proxyHost=your_proxy_http_host -Dhttp.proxyPort=your_proxy_http_port

or these arguments if you are using https :

-Dhttps.proxyHost=your_proxy_https_host -Dhttps.proxyPort=your_proxy_https_port

Add lines in gradle configuration file

in gradle.properties add the following lines :

systemProp.http.proxyHost=your_proxy_http_host
systemProp.http.proxyPort=your_proxy_http_port
systemProp.https.proxyHost=your_proxy_https_host
systemProp.https.proxyPort=your_proxy_https_port

(for gradle.properties file location, please refer to official documentation https://docs.gradle.org/current/userguide/build_environment.html


EDIT : as said by @Joost : A small but important detail that I initially overlooked: notice that the actual host name does NOT contain http:// protocol part of the URL...

Check whether a string matches a regex in JS

Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If you came across this error while using the command line its because you must be using php 7 to execute whatever it is you are trying to execute. What happened is that the code is trying to use an operator thats only available in php7+ and is causing a syntax error.

If you already have php 7+ on your computer try pointing the command line to the higher version of php you want to use.

export PATH=/usr/local/[php-7-folder]/bin/:$PATH

Here is the exact location that worked based off of my setup for reference:

export PATH=/usr/local/php5-7.1.4-20170506-100436/bin/:$PATH

The operator thats actually caused the break is the "null coalesce operator" you can read more about it here:

php7 New Operators

Best way to copy a database (SQL Server 2008)

The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.

If you cannot detach the production db you should use backup and restore.

You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.

You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.

This will lists the orphaned users:

EXEC sp_change_users_login 'Report'

If you already have a login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user'

If you want to create a new login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'

Given the lat/long coordinates, how can we find out the city/country?

An Open Source alternative is Nominatim from Open Street Map. All you have to do is set the variables in an URL and it returns the city/country of that location. Please check the following link for official documentation: Nominatim

Entity Framework The underlying provider failed on Open

For me when that usually starts happening, I have to remote desktop into the service and at the minimum restart IIS. It usually starts popping up right after I deploy code. On a few rare occasions I have had to restart the SQL services and IIS. I wrote a batch script to take a param (1 or 2) and have it setup to either do a restart of IIS ( i.e. 1), or go full nuclear (i.e. 2).

.htaccess not working apache

By default, Apache prohibits using an .htaccess file to apply rewrite rules, so

Step 1 — Enabling mod_rewrite (if not Enabled) First, we need to activate mod_rewrite. It's available but not enabled with a clean Apache 2 installation.

$ sudo a2enmod rewrite

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we'll use to define rewrite rules for redirects.

Step 2 — Setting Up .htaccess Open the default Apache configuration file using nano or your favorite text editor.

$ sudo nano /etc/apache2/sites-available/000-default.conf

Inside that file, you will find a block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented.

/etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>

    . . . 
</VirtualHost>

Save and close the file. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

Done. Your .htacess should work. This link may actually help somebody https://www.digitalocean.com/community/tutorials/how-to-rewrite-urls-with-mod_rewrite-for-apache-on-ubuntu-16-04

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.

Viscon

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Your command line mvn eclipse project generator may not be the same version as that of your eclipse, and eclipse doesn't understand for your command line tool is generating. Just use eclipse's in this case:

  • remove the project from eclipse (including all modules if multi-module)
  • run: rm -rf .settings/ .project .classpath to delete eclipse project files, also from modules
  • import your project as an existing maven project

What does the 'Z' mean in Unix timestamp '120314170138Z'?

"Z" doesn't stand for "Zulu"

I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

In my case exact error was below

':android:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzqx.class

I was using another version of google apis i.e. in one modules gradle file

if (!project.hasProperty('gms_library_version')) {
        ext.gms_library_version = '8.6.0'
   }

however in other modules version 11.6.0 as below

   compile "com.google.android.gms:play-services-ads:11.6.0"
    compile "com.google.android.gms:play-services-games:11.6.0"
    compile "com.google.android.gms:play-services-auth:11.6.0"

However to find this i did a ctrl + n in android studio and entered class name zzqx.class and then it displayed 2 jar files being pulled for this class and then i understood that somewhere i am using version 8.6.0 . On changing 8.6.0 to 11.6.0 and rebuilding the project the issue was fixed .

Hope this helps .

More on this here https://www.versionpb.com/tutorials/step-step-tutorials-libgdx-basic-setup-libgdx/implementing-google-play-services-leaderboards-in-libgdx/

Copy file(s) from one project to another using post build event...VS2010

This command works like a charm for me:

for /r "$(SolutionDir)libraries" %%f in (*.dll, *.exe) do @xcopy "%%f" "$(TargetDir)"

It recursively copies every dll and exe file from MySolutionPath\libraries into the bin\debug or bin\release.

You can find more info in here

Android LinearLayout Gradient Background

You can used a custom view to do that. With this solution, it's finished the gradient shapes of all colors in your projects:

class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    // Properties
    private val paint: Paint = Paint()
    private val rect = Rect()

    //region Attributes
    var start: Int = Color.WHITE
    var end: Int = Color.WHITE
    //endregion

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // Update Size
        val usableWidth = width - (paddingLeft + paddingRight)
        val usableHeight = height - (paddingTop + paddingBottom)
        rect.right = usableWidth
        rect.bottom = usableHeight
        // Update Color
        paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
                start, end, Shader.TileMode.CLAMP)
        // ReDraw
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawRect(rect, paint)
    }

}

I also create an open source project GradientView with this custom view:

https://github.com/lopspower/GradientView

implementation 'com.mikhaellopez:gradientview:1.1.0'

Is there a "not equal" operator in Python?

There's the != (not equal) operator that returns True when two values differ, though be careful with the types because "1" != 1. This will always return True and "1" == 1 will always return False, since the types differ. Python is dynamically, but strongly typed, and other statically typed languages would complain about comparing different types.

There's also the else clause:

# This will always print either "hi" or "no hi" unless something unforeseen happens.
if hi == "hi":     # The variable hi is being compared to the string "hi", strings are immutable in Python, so you could use the 'is' operator.
    print "hi"     # If indeed it is the string "hi" then print "hi"
else:              # hi and "hi" are not the same
    print "no hi"

The is operator is the object identity operator used to check if two objects in fact are the same:

a = [1, 2]
b = [1, 2]
print a == b # This will print True since they have the same values
print a is b # This will print False since they are different objects.

Search for executable files using find command

I had the same issue, and the answer was in the dmenu source code: the stest utility made for that purpose. You can compile the 'stest.c' and 'arg.h' files and it should work. There is a man page for the usage, that I put there for convenience:

STEST(1)         General Commands Manual         STEST(1)

NAME
       stest - filter a list of files by properties

SYNOPSIS
       stest  [-abcdefghlpqrsuwx]  [-n  file]  [-o  file]
       [file...]

DESCRIPTION
       stest takes a list of files  and  filters  by  the
       files'  properties,  analogous  to test(1).  Files
       which pass all tests are printed to stdout. If  no
       files are given, stest reads files from stdin.

OPTIONS
       -a     Test hidden files.

       -b     Test that files are block specials.

       -c     Test that files are character specials.

       -d     Test that files are directories.

       -e     Test that files exist.

       -f     Test that files are regular files.

       -g     Test  that  files  have  their set-group-ID
              flag set.

       -h     Test that files are symbolic links.

       -l     Test the contents of a directory  given  as
              an argument.

       -n file
              Test that files are newer than file.

       -o file
              Test that files are older than file.

       -p     Test that files are named pipes.

       -q     No  files are printed, only the exit status
              is returned.

       -r     Test that files are readable.

       -s     Test that files are not empty.

       -u     Test that files have their set-user-ID flag
              set.

       -v     Invert  the  sense  of  tests, only failing
              files pass.

       -w     Test that files are writable.

       -x     Test that files are executable.

EXIT STATUS
       0      At least one file passed all tests.

       1      No files passed all tests.

       2      An error occurred.

SEE ALSO
       dmenu(1), test(1)

                        dmenu-4.6                STEST(1)

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

Best way to serialize/unserialize objects in JavaScript?

I wrote serialijse because I faced the same problem as you.

you can find it at https://github.com/erossignon/serialijse

It can be used in nodejs or in a browser and can serve to serialize and deserialize a complex set of objects from one context (nodejs) to the other (browser) or vice-versa.

var s = require("serialijse");


var assert = require("assert");


// testing serialization of a simple javascript object with date
function testing_javascript_serialization_object_with_date() {

    var o = {
        date: new Date(),
        name: "foo"
    };
    console.log(o.name, o.date.toISOString());

    // JSON will fail as JSON doesn't preserve dates
    try {
        var jstr = JSON.stringify(o);
        var jo = JSON.parse(jstr);
        console.log(jo.name, jo.date.toISOString());
    } catch (err) {
        console.log(" JSON has failed to preserve Date during stringify/parse ");
        console.log("  and has generated the following error message", err.message);
    }
    console.log("");



    var str = s.serialize(o);
    var so = s.deserialize(str);
    console.log(" However Serialijse knows how to preserve date during serialization/deserialization :");
    console.log(so.name, so.date.toISOString());
    console.log("");
}
testing_javascript_serialization_object_with_date();


// serializing a instance of a class
function testing_javascript_serialization_instance_of_a_class() {

    function Person() {
        this.firstName = "Joe";
        this.lastName = "Doe";
        this.age = 42;
    }

    Person.prototype.fullName = function () {
        return this.firstName + " " + this.lastName;
    };


    // testing serialization using  JSON.stringify/JSON.parse
    var o = new Person();
    console.log(o.fullName(), " age=", o.age);

    try {
        var jstr = JSON.stringify(o);
        var jo = JSON.parse(jstr);
        console.log(jo.fullName(), " age=", jo.age);

    } catch (err) {
        console.log(" JSON has failed to preserve the object class ");
        console.log("  and has generated the following error message", err.message);
    }
    console.log("");

    // now testing serialization using serialijse  serialize/deserialize
    s.declarePersistable(Person);
    var str = s.serialize(o);
    var so = s.deserialize(str);

    console.log(" However Serialijse knows how to preserve object classes serialization/deserialization :");
    console.log(so.fullName(), " age=", so.age);
}
testing_javascript_serialization_instance_of_a_class();


// serializing an object with cyclic dependencies
function testing_javascript_serialization_objects_with_cyclic_dependencies() {

    var Mary = { name: "Mary", friends: [] };
    var Bob = { name: "Bob", friends: [] };

    Mary.friends.push(Bob);
    Bob.friends.push(Mary);

    var group = [ Mary, Bob];
    console.log(group);

    // testing serialization using  JSON.stringify/JSON.parse
    try {
        var jstr = JSON.stringify(group);
        var jo = JSON.parse(jstr);
        console.log(jo);

    } catch (err) {
        console.log(" JSON has failed to manage object with cyclic deps");
        console.log("  and has generated the following error message", err.message);
    }

    // now testing serialization using serialijse  serialize/deserialize
    var str = s.serialize(group);
    var so = s.deserialize(str);
    console.log(" However Serialijse knows to manage object with cyclic deps !");
    console.log(so);
    assert(so[0].friends[0] == so[1]); // Mary's friend is Bob
}
testing_javascript_serialization_objects_with_cyclic_dependencies();

How to do the equivalent of pass by reference for primitives in Java

You have several choices. The one that makes the most sense really depends on what you're trying to do.

Choice 1: make toyNumber a public member variable in a class

class MyToy {
  public int toyNumber;
}

then pass a reference to a MyToy to your method.

void play(MyToy toy){  
    System.out.println("Toy number in play " + toy.toyNumber);   
    toy.toyNumber++;  
    System.out.println("Toy number in play after increement " + toy.toyNumber);   
}

Choice 2: return the value instead of pass by reference

int play(int toyNumber){  
    System.out.println("Toy number in play " + toyNumber);   
    toyNumber++;  
    System.out.println("Toy number in play after increement " + toyNumber);   
    return toyNumber
}

This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);.

Choice 3: make it a class or static variable

If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.

Choice 4: Create a single element array of type int and pass that

This is considered a hack, but is sometimes employed to return values from inline class invocations.

void play(int [] toyNumber){  
    System.out.println("Toy number in play " + toyNumber[0]);   
    toyNumber[0]++;  
    System.out.println("Toy number in play after increement " + toyNumber[0]);   
}

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

How to convert int to Integer

i it integer, int to Integer

Integer intObj = new Integer(i);

add to collection

list.add(String.valueOf(intObj));

Want custom title / image / description in facebook share link from a flash app

I think this site has the solution, i will test it now. It Seems like facebook has changed the parameters of share.php so, in order to customize share window text and images you have to put parameters in a "p" array.

http://www.daddydesign.com/wordpress/how-to-create-a-custom-facebook-share-button-for-your-iframe-tab/

Check it out.

How to set RelativeLayout layout params in code not in xml?

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.setLayoutParams(labelLayoutParams);


   // If you want to add some controls in this Relative Layout
    labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);


    ImageView mImage = new ImageView(this);
    mImage.setBackgroundResource(R.drawable.popupnew_bg);        
    layout.addView(mImage,labelLayoutParams);

    setContentView(layout);

Performing Breadth First Search recursively

C# implementation of recursive breadth-first search algorithm for a binary tree.

Binary tree data visualization

IDictionary<string, string[]> graph = new Dictionary<string, string[]> {
    {"A", new [] {"B", "C"}},
    {"B", new [] {"D", "E"}},
    {"C", new [] {"F", "G"}},
    {"E", new [] {"H"}}
};

void Main()
{
    var pathFound = BreadthFirstSearch("A", "H", new string[0]);
    Console.WriteLine(pathFound); // [A, B, E, H]

    var pathNotFound = BreadthFirstSearch("A", "Z", new string[0]);
    Console.WriteLine(pathNotFound); // []
}

IEnumerable<string> BreadthFirstSearch(string start, string end, IEnumerable<string> path)
{
    if (start == end)
    {
        return path.Concat(new[] { end });
    }

    if (!graph.ContainsKey(start)) { return new string[0]; }    

    return graph[start].SelectMany(letter => BreadthFirstSearch(letter, end, path.Concat(new[] { start })));
}

If you want algorithm to work not only with binary-tree but with graphs what can have two and more nodes that points to same another node you must to avoid self-cycling by holding list of already visited nodes. Implementation may be looks like this.

Graph data visualization

IDictionary<string, string[]> graph = new Dictionary<string, string[]> {
    {"A", new [] {"B", "C"}},
    {"B", new [] {"D", "E"}},
    {"C", new [] {"F", "G", "E"}},
    {"E", new [] {"H"}}
};

void Main()
{
    var pathFound = BreadthFirstSearch("A", "H", new string[0], new List<string>());
    Console.WriteLine(pathFound); // [A, B, E, H]

    var pathNotFound = BreadthFirstSearch("A", "Z", new string[0], new List<string>());
    Console.WriteLine(pathNotFound); // []
}

IEnumerable<string> BreadthFirstSearch(string start, string end, IEnumerable<string> path, IList<string> visited)
{
    if (start == end)
    {
        return path.Concat(new[] { end });
    }

    if (!graph.ContainsKey(start)) { return new string[0]; }


    return graph[start].Aggregate(new string[0], (acc, letter) =>
    {
        if (visited.Contains(letter))
        {
            return acc;
        }

        visited.Add(letter);

        var result = BreadthFirstSearch(letter, end, path.Concat(new[] { start }), visited);
        return acc.Concat(result).ToArray();
    });
}

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

How do I embed PHP code in JavaScript?

If your whole JavaScript code gets processed by PHP, then you can do it just like that.

If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.

For example, in your index.php (or wherever you specify your layout), you'd do something like this:

<script type="text/javascript">
    var my_var = <?php echo json_encode($my_var); ?>;
</script>

You could then use my_var in your JavaScript files.

This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.

Accessing Object Memory Address

I know this is an old question but if you're still programming, in python 3 these days... I have actually found that if it is a string, then there is a really easy way to do this:

>>> spam.upper
<built-in method upper of str object at 0x1042e4830>
>>> spam.upper()
'YO I NEED HELP!'
>>> id(spam)
4365109296

string conversion does not affect location in memory either:

>>> spam = {437 : 'passphrase'}
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'
>>> str(spam)
"{437: 'passphrase'}"
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'

C++ correct way to return pointer to array from function

Your code as it stands is correct but I am having a hard time figuring out how it could/would be used in a real world scenario. With that said, please be aware of a few caveats when returning pointers from functions:

  • When you create an array with syntax int arr[5];, it's allocated on the stack and is local to the function.
  • C++ allows you to return a pointer to this array, but it is undefined behavior to use the memory pointed to by this pointer outside of its local scope. Read this great answer using a real world analogy to get a much clear understanding than what I could ever explain.
  • You can still use the array outside the scope if you can guarantee that memory of the array has not be purged. In your case this is true when you pass arr to test().
  • If you want to pass around pointers to a dynamically allocated array without worrying about memory leaks, you should do some reading on std::unique_ptr/std::shared_ptr<>.

Edit - to answer the use-case of matrix multiplication

You have two options. The naive way is to use std::unique_ptr/std::shared_ptr<>. The Modern C++ way is to have a Matrix class where you overload operator * and you absolutely must use the new rvalue references if you want to avoid copying the result of the multiplication to get it out of the function. In addition to having your copy constructor, operator = and destructor, you also need to have move constructor and move assignment operator. Go through the questions and answers of this search to gain more insight on how to achieve this.

Edit 2 - answer to appended question

int* test (int a[5], int b[5]) {
    int *c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

If you are using this as int *res = test(a,b);, then sometime later in your code, you should call delete []res to free the memory allocated in the test() function. You see now the problem is it is extremely hard to manually keep track of when to make the call to delete. Hence the approaches on how to deal with it where outlined in the answer.

How to remove/delete a large file from commit history in Git repository?

This works perfectly for me : in git extensions :

right click on the selected commit :

reset current branch to here :

hard reset ;

It's surprising nobody else is able to give this simple answer.

reset current branch to here

hard reset

How to include multiple js files using jQuery $.getScript() method

What you are looking for is an AMD compliant loader (like require.js).

http://requirejs.org/

http://requirejs.org/docs/whyamd.html

There are many good open source ones if you look it up. Basically this allows you to define a module of code, and if it is dependent on other modules of code, it will wait until those modules have finished downloading before proceeding to run. This way you can load 10 modules asynchronously and there should be no problems even if one depends on a few of the others to run.

Use find command but exclude files in two directories

Here is one way you could do it...

find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

How do I enable EF migrations for multiple contexts to separate databases?

If more databases exist use following codes in PowerShell

Add-Migration Starter -context EnrollmentAppContext 
  • 'Starter' is Migration Name

  • 'EnrollmentAppContext' is name of my app Context

You can open PowerShell in VS by doing: Tools->NuGet Package Manager->Package Manager Console

What HTTP traffic monitor would you recommend for Windows?

Try Wireshark:

Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.

There is a bit of a learning curve but it is far and away the best tool available.

Python 3: UnboundLocalError: local variable referenced before assignment

If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.

In your case, Var1 is considered as a local variable, and it's used before being set, thus the error.

To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.

Var1 = 1
Var2 = 0
def function():
    global Var1
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    Var1 =- 1
function()

Getting time span between two times in C#?

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

Addendum:

Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

Prevent RequireJS from Caching Required Scripts

The urlArgs solution has problems. Unfortunately you cannot control all proxy servers that might be between you and your user's web browser. Some of these proxy servers can be unfortunately configured to ignore URL parameters when caching files. If this happens, the wrong version of your JS file will be delivered to your user.

I finally gave up and implemented my own fix directly into require.js. If you are willing to modify your version of the requirejs library, this solution might work for you.

You can see the patch here:

https://github.com/jbcpollak/requirejs/commit/589ee0cdfe6f719cd761eee631ce68eee09a5a67

Once added, you can do something like this in your require config:

var require = {
    baseUrl: "/scripts/",
    cacheSuffix: ".buildNumber"
}

Use your build system or server environment to replace buildNumber with a revision id / software version / favorite color.

Using require like this:

require(["myModule"], function() {
    // no-op;
});

Will cause require to request this file:

http://yourserver.com/scripts/myModule.buildNumber.js

On our server environment, we use url rewrite rules to strip out the buildNumber, and serve the correct JS file. This way we don't actually have to worry about renaming all of our JS files.

The patch will ignore any script that specifies a protocol, and it will not affect any non-JS files.

This works well for my environment, but I realize some users would prefer a prefix rather than a suffix, it should be easy to modify my commit to suit your needs.

Update:

In the pull request discussion, the requirejs author suggest this might work as a solution to prefix the revision number:

var require = {
    baseUrl: "/scripts/buildNumber."
};

I have not tried this, but the implication is that this would request the following URL:

http://yourserver.com/scripts/buildNumber.myModule.js

Which might work very well for many people who can use a prefix.

Here are some possible duplicate questions:

RequireJS and proxy caching

require.js - How can I set a version on required modules as part of the URL?

How to use OpenFileDialog to select a folder?

Take a look at the Ookii Dialogs libraries which has an implementation of a folder browser dialog for Windows Forms and WPF respectively.

enter image description here

Ookii.Dialogs.WinForms

https://github.com/augustoproiete/ookii-dialogs-winforms


Ookii.Dialogs.Wpf

https://github.com/augustoproiete/ookii-dialogs-wpf

ggplot with 2 y axes on each side and different scales

It's not possible in ggplot2 because I believe plots with separate y scales (not y-scales that are transformations of each other) are fundamentally flawed. Some problems:

  • The are not invertible: given a point on the plot space, you can not uniquely map it back to a point in the data space.

  • They are relatively hard to read correctly compared to other options. See A Study on Dual-Scale Data Charts by Petra Isenberg, Anastasia Bezerianos, Pierre Dragicevic, and Jean-Daniel Fekete for details.

  • They are easily manipulated to mislead: there is no unique way to specify the relative scales of the axes, leaving them open to manipulation. Two examples from the Junkcharts blog: one, two

  • They are arbitrary: why have only 2 scales, not 3, 4 or ten?

You also might want to read Stephen Few's lengthy discussion on the topic Dual-Scaled Axes in Graphs Are They Ever the Best Solution?.

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

Hello World in Python

Unfortunately the xkcd comic isn't completely up to date anymore.

https://imgs.xkcd.com/comics/python.png

Since Python 3.0 you have to write:

print("Hello world!")

And someone still has to write that antigravity library :(

How to change option menu icon in the action bar?

If you want to change icon/title menu in the actionbar/toolbar programmatically,

STEP by STEP

  1. Declare Menu in class

private var mMenu: Menu? = null

  1. Overide onCreateOptionsMenu method and find item so you need to change

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    mMenu = menu
    menuInflater.inflate(R.menu.menu, menu)
    if (mIsFavorite){
        mMenu?.findItem(R.id.action_favorite)?.icon = yourDrawable
    } else {
        mMenu?.findItem(R.id.action_favorite)?.icon = yourDrawable
    }
    return true
    

    }

  2. Use invalidateOptionsMenu() to update some changes in menu after onCreateOptionsMenu executed. This method will re-create menu

How can I change IIS Express port for a site

Deploy your application in the IIS with the default port. Try to debug it using visual studio. It's a good practice. If you use visual studio, it will keep changing the port number most of the time. So better deploy the application in the IIS first and Open the same in visual studio and Debug it.

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

It's also worth noting that ActiveX controls only work in Windows, whereas Form Controls will work on both Windows and MacOS versions of Excel.

Executing JavaScript without a browser?

FWIW, node.js comes with a shell, try typing in:

node-repl

once you've installed node.js to see it in action. It's pretty standard to install rlwrap to get it to work nicely.

how to make a new line in a jupyter markdown cell

Just add <br> where you would like to make the new line.

$S$: a set of shops
<br>
$I$: a set of items M wants to get

Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html

Note that newlines using <br> does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br> as a space.

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

Assign variable value inside if-statement

Yes, you can assign the value of variable inside if.

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===.

It will be better if you do something like this:

int v;
if((v = someMethod()) != 0) 
   return true;

How to declare an array of objects in C#

Everything you have looks fine.

The only thing I can think of (without seeing the error message, which you should have provided), is that GameObject needs a default (no parameter) constructor.

How to combine date from one field with time from another field - MS SQL Server

Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.

Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103) 

Combine two integer arrays

Here a simple function that use variable arguments:

final static
public int[] merge(final int[] ...arrays ) {
    int size = 0;
    for ( int[] a: arrays )
        size += a.length;

        int[] res = new int[size];

        int destPos = 0;
        for ( int i = 0; i < arrays.length; i++ ) {
            if ( i > 0 ) destPos += arrays[i-1].length;
            int length = arrays[i].length;
            System.arraycopy(arrays[i], 0, res, destPos, length);
        }

        return res;
}

To use:

int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
int[] array3 = {7,8,9};
int[] array1and2and3 = merge(array1, array2, array3);
for ( int x: array1and2and3 ) 
    System.out.print( String.format("%3d", x) );

Illegal Character when trying to compile java code

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.

JavaScript Infinitely Looping slideshow with delays?

You can infinitely loop easily enough via recursion.

function it_keeps_going_and_going_and_going() {
  it_keeps_going_and_going_and_going();
}

it_keeps_going_and_going_and_going()

How to convert current date to epoch timestamp?

That should do it

import time

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(date_time, pattern)))
print epoch

Targeting only Firefox with CSS

The following code tends to throw Style lint warnings:

@-moz-document url-prefix() {
    h1 {
        color: red;
    }
}

Instead using

@-moz-document url-prefix('') {
    h1 {
        color: red;
    }
}

Helped me out! Got the solution for style lint warning from here

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

Appending a byte[] to the end of another byte[]

First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.

byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];


System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You could use this line to write to Output Window of the Visual Studio:

System.Diagnostics.Debug.WriteLine("Matrix has you...");

Must run in Debug mode.

SQL count rows in a table

Yes, SELECT COUNT(*) FROM TableName

How to join multiple collections with $lookup in mongodb

The join feature supported by Mongodb 3.2 and later versions. You can use joins by using aggregate query.
You can do it using below example :

db.users.aggregate([

    // Join with user_info table
    {
        $lookup:{
            from: "userinfo",       // other table name
            localField: "userId",   // name of users table field
            foreignField: "userId", // name of userinfo table field
            as: "user_info"         // alias for userinfo table
        }
    },
    {   $unwind:"$user_info" },     // $unwind used for getting data in object or for one record only

    // Join with user_role table
    {
        $lookup:{
            from: "userrole", 
            localField: "userId", 
            foreignField: "userId",
            as: "user_role"
        }
    },
    {   $unwind:"$user_role" },

    // define some conditions here 
    {
        $match:{
            $and:[{"userName" : "admin"}]
        }
    },

    // define which fields are you want to fetch
    {   
        $project:{
            _id : 1,
            email : 1,
            userName : 1,
            userPhone : "$user_info.phone",
            role : "$user_role.role",
        } 
    }
]);

This will give result like this:

{
    "_id" : ObjectId("5684f3c454b1fd6926c324fd"),
    "email" : "[email protected]",
    "userName" : "admin",
    "userPhone" : "0000000000",
    "role" : "admin"
}

Hope this will help you or someone else.

Thanks

How can I remove an element from a list?

if you'd like to avoid numeric indices, you can use

a <- setdiff(names(a),c("name1", ..., "namen"))

to delete names namea...namen from a. this works for lists

> l <- list(a=1,b=2)
> l[setdiff(names(l),"a")]
$b
[1] 2

as well as for vectors

> v <- c(a=1,b=2)
> v[setdiff(names(v),"a")]
b 
2

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How do you use MySQL's source command to import large files in windows

On my Xampp set-up I was able to use the following to import a database into MySQL:

C:\xampp\mysql\bin\mysql -u {username goes here} -p {leave password blank} {database name} < /path/to/file.sql [enter]

My personal experience on my local machine was as follows:
Username: Root
Database Name: testdatabase
SQL File Location: databasebackup.sql is located on my desktop

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql 

That worked for me to import my 1GB+ file into my database.

CodeIgniter removing index.php from url

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

use

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$1 [PT,L]

if you have url in this order site.com/index.php/class/method/id

NB:remove index.php in config.php should be config[index_page] = ""

NB: notice the difference at the last line instead of $0 use $1

Spring Test & Security: How to mock authentication?

Pretty Late answer though. But This has worked for me , and could be useful.

While Using Spring Security ans mockMvc, all you need to is use @WithMockUser annotation like others are mentioned.

Spring security also provides another annotation called @WithAnonymousUser for testing unauthenticated requests. However you should be careful here. You would be expecting 401, but I got 403 Forbidden Error by default. In actual scenarios, when you are running actual service, It is redirected and you end up getting the correct 401 response code.Use this annotation for anonymous requests.

You may also think of ommitting the annotaions and simply keep it unauthorized. But this usually raises the correct exceptions(like AuthenticationException), but you will get correct status code if it is handled correctly(If you are using custom handler). I used to get 500 for this. So look for the exceptions raised in the debugger, and check if it is handled rightly and returns the correct status code.

How to change theme for AlertDialog

I have written an article in my blog on how to configure the layout of an AlertDialog with XML style files. The main problem is that you need different style definitions for different layout parameters. Here is a boilerplate based on the AlertDialog style of Holo Light Platform version 19 for a style file that should cover a bunch of the standard layout aspects like text sizes and background colors.

<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    ...
    <item name="android:alertDialogTheme">@style/MyAlertDialogTheme</item>
    <item name="android:alertDialogStyle">@style/MyAlertDialogStyle</item>
    ...
</style>

<style name="MyBorderlessButton">
    <!-- Set background drawable and text size of the buttons here -->
    <item name="android:background">...</item>
    <item name="android:textSize">...</item>
</style>

<style name="MyButtonBar">
    <!-- Define a background for the button bar and a divider between the buttons here -->
    <item name="android:divider">....</item>
    <item name="android:dividerPadding">...</item>
    <item name="android:showDividers">...</item>
    <item name="android:background">...</item>
</style>

<style name="MyAlertDialogTitle">
    <item name="android:maxLines">1</item>
    <item name="android:scrollHorizontally">true</item>
</style>

<style name="MyAlertTextAppearance">
    <!-- Set text size and color of title and message here -->
    <item name="android:textSize"> ... </item>
    <item name="android:textColor">...</item>
</style>

<style name="MyAlertDialogTheme">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowTitleStyle">@style/MyAlertDialogTitle</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
    <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:textAppearanceMedium">@style/MyAlertTextAppearance</item>
    <!-- If you don't want your own button bar style use
            @android:style/Holo.Light.ButtonBar.AlertDialog
            and
            ?android:attr/borderlessButtonStyle
         instead of @style/MyButtonBar and @style/MyBorderlessButton -->
    <item name="android:buttonBarStyle">@style/MyButtonBar</item>
    <item name="android:buttonBarButtonStyle">@style/MyBorderlessButton</item>
</style>

<style name="MyAlertDialogStyle">
    <!-- Define background colors of title, message, buttons, etc. here -->
    <item name="android:fullDark">...</item>
    <item name="android:topDark">...</item>
    <item name="android:centerDark">...</item>
    <item name="android:bottomDark">...</item>
    <item name="android:fullBright">...</item>
    <item name="android:topBright">...</item>
    <item name="android:centerBright">...</item>
    <item name="android:bottomBright">...</item>
    <item name="android:bottomMedium">...</item>
    <item name="android:centerMedium">...</item>
</style>

What are some good Python ORM solutions?

SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode.

How to pause in C?

getch() can also be used which is defined in conio.h.

The sample program would look like this :

#include <stdio.h>
#include <conio.h>

int main()
{
    //your code 
    getch();
    return 0; 
} 

getch() waits for any character input from the keyboard (not necessarily enter key).

Moment.js get day name from date

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('ddd');
console.log(weekDayName);

Result: Wed

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

Result: Wednesday

SQL query to select dates between two dates

You ca try this SQL

select * from employee where rec_date between '2017-09-01' and '2017-09-11' 

Error in finding last used cell in Excel with VBA

Find Last Row in a Column OR a Table Column(ListObject) by range

Finding the last row requires:

  1. Specifying several parameters (table name, column inside table relative to first column, worksheet, range).
  2. May require switching between methods. e.g. if the range is a Table (List Object) or not. Using the wrong search type will return wrong results.

This proposed solution is more general, requires only the range ,less chance of typos and is short (just calling MyLastRow function).

Sub test()
Dim rng As Range
Dim Result As Long
Set rng = Worksheets(1).Range("D4")
Result = MyLastRow(rng)
End Sub
    Function MyLastRow(FirstRow As Range) As Long
    Dim WS As Worksheet
    Dim TableName As String
    Dim ColNumber As Long
    Dim LastRow As Long
    Dim FirstColumnTable As Long
    Dim ColNumberTable As Long
    Set WS = FirstRow.Worksheet
    TableName = GetTableName(FirstRow)
    ColNumber = FirstRow.Column
    
    ''If the table (ListObject) does not start in column "A" we need to calculate the 
    ''first Column table and how many Columns from its beginning the Column is located.
    If TableName <> vbNullString Then
     FirstColumnTable = WS.ListObjects(TableName).ListColumns(1).Range.Column
     ColNumberTable = ColNumber - FirstColumnTable + 1
    End If 

    If TableName = vbNullString Then
    LastRow = WS.Cells(WS.Rows.Count, ColNumber).End(xlUp).Row
    Else
    LastRow = WS.ListObjects(TableName).ListColumns(ColNumberTable).Range.Find( _
               What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
    MyLastRow = LastRow
    End Function
    
    ''Get Table Name by Cell Range
    Function GetTableName(CellRange As Range) As String
        If CellRange.ListObject Is Nothing Then
            GetTableName = vbNullString
        Else
            GetTableName = CellRange.ListObject.Name
        End If
    End Function

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

What does servletcontext.getRealPath("/") mean and when should I use it

There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?

How to rename files and folder in Amazon S3?

I've just got this working. You can use the AWS SDK for PHP like this:

use Aws\S3\S3Client;

$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$targetKeyname = '*** Your Target Key Name ***';        

// Instantiate the client.
$s3 = S3Client::factory();

// Copy an object.
$s3->copyObject(array(
    'Bucket'     => $targetBucket,
    'Key'        => $targetKeyname,
    'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
));

http://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingPHP.html

How to use variables in SQL statement in Python?

Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

or (e.g. with sqlite3 from the Python standard library):

cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))

or others yet (after VALUES you could have (:1, :2, :3) , or "named styles" (:fee, :fie, :fo) or (%(fee)s, %(fie)s, %(fo)s) where you pass a dict instead of a map as the second argument to execute). Check the paramstyle string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

findViewById in Fragment

You have to inflate the view

public class TestClass extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
    return v
}}

How to Use slideDown (or show) function on a table row?

You could try wrapping the contents of the row in a <span> and having your selector be $('#detailed_edit_row span'); - a bit hackish, but I just tested it and it works. I also tried the table-row suggestion above and it didn't seem to work.

update: I've been playing around with this problem, and from all indications jQuery needs the object it performs slideDown on to be a block element. So, no dice. I was able to conjure up a table where I used slideDown on a cell and it didn't affect the layout at all, so I am not sure how yours is set up. I think your only solution is to refactor the table in such a way that it's ok with that cell being a block, or just .show(); the damn thing. Good luck.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

In windows 10, to free up port 80:

in my case, I open "Services" from "Search Windows" (on the left corner on screen), then stop all of SQL server services MSSQLSERVER and it works again

Binding Combobox Using Dictionary as the Datasource

Just Try to do like this....

SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();

    // Add this code
    if(userCache != null)
    {
        userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null
        userListComboBox.DisplayMember = "Key";
        userListComboBox.ValueMember = "Value";
    }

Bootstrap 3 Navbar with Logo

My solution is add css "display: inline-block" to img tag.

<img style="display: inline-block; height: 30px; margin-top: -5px">

DEMO: jsfiddle

Lint: How to ignore "<key> is not translated in <language>" errors?

Add following to your gradle file in android section

    lintOptions {
       disable 'MissingTranslation'
    }

iOS app 'The application could not be verified' only on one device

Had the same issue on my iPad running 8.1.3 Deleting the app and installing again fixed the issue. I use two different provisioning profiles on two different machines and that could have caused this issue.

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

Resolve host name to an ip address

You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How can I quantify difference between two images?

A simple solution:

Encode the image as a jpeg and look for a substantial change in filesize.

I've implemented something similar with video thumbnails, and had a lot of success and scalability.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Below method solved my problem:

In ubuntu

Type: sudo vi /etc/mysql/my.cnf

type A to enter insert mode

In the last line paste below two line code:

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Type esc to exit input mode

Type :wq to save and close vim.

Type sudo service mysql restart to restart MySQL.

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I was also getting the same error.

nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

and when i typed the localhost in the browser, then i was getting

It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet. instead of nginx welcome page, apache2 is running on the same port,

  1. find the apache2 ports.conf file

    sudo /etc/apache2/ports.conf
    
  2. change the port other then 80 , i make it as 70

  3. save the file

  4. restart your system

it will works for you also, if you type the localhost in the browser, you will get nginx welcome page

how to access iFrame parent page using jquery?

yeah it works for me as well.

Note : we need to use window.parent.document

    $("button", window.parent.document).click(function()
    {
        alert("Functionality defined by def");
    });