Programs & Examples On #Webgl

WebGL extends the capability of the HTML canvas element to allow it to render accelerated graphics in any compatible web browser. **DO NOT TAG QUESTIONS ABOUT 3D LIBRARIES (like THREE.js) WITH THIS TAG** unless the question is specifically about a WebGL API feature

Displaying a 3D model in JavaScript/HTML5

a couple years down the road, I'd vote for three.js because

ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)

and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)

UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link

http://threejs.org/examples and review the loaders - at least 20 of them

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

TypeError: not all arguments converted during string formatting python

For me, This error was caused when I was attempting to pass in a tuple into the string format method.

I found the solution from this question/answer

Copying and pasting the correct answer from the link (NOT MY WORK):

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.

Correct way to use Modernizr to detect IE?

You can use the < !-- [if IE] > hack to set a global js variable that then gets tested in your normal js code. A bit ugly but has worked well for me.

How can I capture the result of var_dump to a string?

Here is the complete solution as a function:

function varDumpToString ($var)
{
    ob_start();
    var_dump($var);
    return ob_get_clean();
}

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

Stacking DIVs on top of each other?

All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute divs can be overridden by other divs in the page.)

<div class="container">
  <div class="inner" style="background-color: white;"></div>
  <div class="inner" style="background-color: red;"></div>
  <div class="inner" style="background-color: green;"></div>
  <div class="inner" style="background-color: blue;"></div>
  <div class="inner" style="background-color: purple;"></div>
  <div class="inner no-display" style="background-color: black;"></div>
</div>

<style>
.container {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: yellow;
  display: grid;
  place-items: center;
  grid-template-areas:
                  "inners";
}

.inner {
  grid-area: inners;
  height: 100px;
  width: 100px;
}

.no-display {
  display: none;
}
</style>

Here's a working link

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

_x000D_
_x000D_
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
_x000D_
_x000D_

To decode, you can use the atob() function:

_x000D_
_x000D_
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
_x000D_
_x000D_

How to put comments in Django templates

As answer by Miles, {% comment %}...{% endcomment %} is used for multi-line comments, but you can also comment out text on the same line like this:

{# some text #}

remove table row with specific id

As bellow we can remove table rows with specific row id

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function remove(id)
{
$('table#test tr#'+id).remove();
// or you can use bellow line also
//$('#test tr#'+id).remove();
}
</script>
    </head>
<body>
<table id="test">
 <tr id="1"><td>bla</td><td><input type="button" onclick="remove(1)"value="Remove"></td></tr>
 <tr id="2"><td>bla</td><td><input type="button" onclick="remove(2)" value="Remove"></td></tr>
 <tr id="3"><td>bla</td><td><input type="button" onclick="remove(3)" value="Remove"></td></tr>
 <tr id="4"><td>bla</td><td><input type="button" onclick="remove(4)" value="Remove"></td></tr>
</table>
</body></html>

Local storage in Angular 2

You can also consider using library maintained by me: ngx-store (npm i ngx-store)

It makes working with localStorage, sessionStorage and cookies incredibly easy. There are a few supported methods to manipulate the data:

1) Decorator:

export class SomeComponent {
  @LocalStorage() items: Array<string> = [];

  addItem(item: string) {
    this.items.push(item);
    console.log('current items:', this.items);
    // and that's all: parsing and saving is made by the lib in the background 
  }
}

Variables stored by decorators can be also shared across different classes - there is also @TempStorage() (with an alias of @SharedStorage())) decorator designed for it.

2) Simple service methods:

export class SomeComponent {
  constructor(localStorageService: LocalStorageService) {}

  public saveSettings(settings: SettingsInterface) {
    this.localStorageService.set('settings', settings);
  }

  public clearStorage() {
    this.localStorageService.utility
      .forEach((value, key) => console.log('clearing ', key));
    this.localStorageService.clear();
  }
}

3) Builder pattern:

interface ModuleSettings {
    viewType?: string;
    notificationsCount: number;
    displayName: string;
}

class ModuleService {
    constructor(public localStorageService: LocalStorageService) {}

    public get settings(): NgxResource<ModuleSettings> {
        return this.localStorageService
            .load(`userSettings`)
            .setPath(`modules`)
            .setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array 
            .appendPath(this.moduleId)
            .setDefaultValue({});
    }

    public saveModuleSettings(settings: ModuleSettings) {
        this.settings.save(settings);
    }

    public updateModuleSettings(settings: Partial<ModuleSettings>) {
        this.settings.update(settings);
    }
}

Another important thing is you can listen for (every) storage changes, e.g. (the code below uses RxJS v5 syntax):

this.localStorageService.observe()
  .filter(event => !event.isInternal)
  .subscribe((event) => {
    // events here are equal like would be in:
    // window.addEventListener('storage', (event) => {});
    // excluding sessionStorage events
    // and event.type will be set to 'localStorage' (instead of 'storage')
  });

WebStorageService.observe() returns a regular Observable, so you can zip, filter, bounce them etc.

I'm always open to hearing suggestions and questions helping me to improve this library and its documentation.

How to read a file in other directory in python

In case you're not in the specified directory (i.e. direct), you should use (in linux):

x_file = open('path/to/direct/filename.txt')

Note the quotes and the relative path to the directory.

This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

How to center an iframe horizontally?

If you are putting a video in the iframe and you want your layout to be fluid, you should look at this webpage: Fluid Width Video

Depending on the video source and if you want to have old videos become responsive your tactics will need to change.

If this is your first video, here is a simple solution:

_x000D_
_x000D_
<div class="videoWrapper">_x000D_
    <!-- Copy & Pasted from YouTube -->_x000D_
    <iframe width="560" height="349" src="http://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And add this css:

_x000D_
_x000D_
.videoWrapper {_x000D_
 position: relative;_x000D_
 padding-bottom: 56.25%; /* 16:9 */_x000D_
 padding-top: 25px;_x000D_
 height: 0;_x000D_
}_x000D_
.videoWrapper iframe {_x000D_
 position: absolute;_x000D_
 top: 0;_x000D_
 left: 0;_x000D_
 width: 100%;_x000D_
 height: 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

Disclaimer: none of this is my code, but I've tested it and was happy with the results.

How can I add an image file into json object?

You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.

You must load the image and read the bytes from it. Then put these bytes into the JSON object.

C++ variable has initializer but incomplete type?

I got a similar error and hit this page while searching the solution.

With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.

Escaping quotation marks in PHP

Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"

Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

How to generate a random integer number from within a range

Will return a floating point number in the range [0,1]:

#define rand01() (((double)random())/((double)(RAND_MAX)))

How can I disable ReSharper in Visual Studio and enable it again?

You can disable ReSharper 5 and newer versions by using the Suspend button in menu Tools -> Options -> ReSharper.

enter image description here

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

What is the best way to iterate over a dictionary?

foreach is fastest and if you only iterate over ___.Values, it is also faster

enter image description here

Cannot find module cv2 when using OpenCV

pip install opencv-python

or

pip install opencv-python3 

will definately works fine

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

How to make an Android Spinner with initial text "Select One"?

here's a simple one

    private boolean isFirst = true;
private void setAdapter() {
    final ArrayList<String> spinnerArray = new ArrayList<String>();     
    spinnerArray.add("Select your option");
    spinnerArray.add("Option 1");
    spinnerArray.add("Option 2");
    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            TextView tv = (TextView)selectedItemView;
            String res = tv.getText().toString().trim();
            if (res.equals("Option 1")) {
            //do Something
        } else if (res.equals("Option 2")) {
            //do Something else
        }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) { }

    });

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_spinner_style,spinnerArray) {
         public View getView(int position, View convertView, ViewGroup parent) {
             View v = super.getView(position, convertView, parent);
             int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());                  
             ((TextView) v).setTypeface(tf2);
             ((TextView) v).getLayoutParams().height = height;
             ((TextView) v).setGravity(Gravity.CENTER);
             ((TextView) v).setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
             ((TextView) v).setTextColor(Color.WHITE);
             return v;
         }

         public View getDropDownView(int position, View convertView,
                 ViewGroup parent) {
             if (isFirst) {
                 isFirst = false;
                 spinnerArray.remove(0);
             }
             View v = super.getDropDownView(position, convertView, parent);                  
             ((TextView) v).setTextColor(Color.argb(255, 70, 70, 70));
             ((TextView) v).setTypeface(tf2);
             ((TextView) v).setGravity(Gravity.CENTER);
             return v;
         }
     };
     spin.setAdapter(adapter);
}

Convert Pandas Series to DateTime in a DataFrame

You can't: DataFrame columns are Series, by definition. That said, if you make the dtype (the type of all the elements) datetime-like, then you can access the quantities you want via the .dt accessor (docs):

>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205  76032930   2015-01-24 00:05:27.513000
232  76032930   2015-01-24 00:06:46.703000
233  76032930   2015-01-24 00:06:56.707000
413  76032930   2015-01-24 00:14:24.957000
565  76032930   2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205  76032930    1
232  76032930    1
233  76032930    1
413  76032930    1
565  76032930    1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205  76032930     5
232  76032930     6
233  76032930     6
413  76032930    14
565  76032930    23
dtype: int64

If you're stuck using an older version of pandas, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:

>>> df["TimeReviewed"].apply(lambda x: x.year)
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
Name: TimeReviewed, dtype: int64

How to convert DateTime to a number with a precision greater than days in T-SQL?

CAST to a float or decimal instead of an int/bigint.

The integer portion (before the decimal point) represents the number of whole days. After the decimal are the fractional days (i.e., time).

Facebook Android Generate Key Hash

I. Create key hash debug for facebook

Add code to print out the key hash for facebook

    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.google.shoppingvn", PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:",
                    Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

II. Create key hash release for facebook

  1. Download openssl-0.9.8e_X64

  2. Make a openssl folder in C drive

  3. Extract Zip files into openssl folder

  4. Start -> Run: cmd (press enter)

  5. (press) cd C:\Program Files\Java\jdk1.6.0_45\bin. Note: C:\Program Files\Java\jdk1.6.0_45\bin: is path to jdk folder in your computer

  6. (press) keytool -exportcert -alias gci -keystore D:\folder\keystorerelease | C:\openssl\bin\openssl sha1 -binary | C:\openssl\bin\openssl base64. Note: D:\folder\keystorerelease: is path to your keystorerelease

  7. Enter keystore password: This is password when your register keystorerelease.

    Then you will have a key hash: jDehABCDIQEDWAYz5Ow4sjsxLSw=

  8. Login facebook. Access to Manage Apps. Paste key hash to your app on developers.facebook.com

How to write LaTeX in IPython Notebook?

Since, I was not able to use all the latex commands in Code even after using the %%latex keyword or the $..$ limiter, I installed the nbextensions through which I could use the latex commands in Markdown. After following the instructions here: https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/README.md and then restarting the Jupyter and then localhost:8888/nbextensions and then activating "Latex Environment for Jupyter", I could run many Latex commands. Examples are here: https://rawgit.com/jfbercher/latex_envs/master/doc/latex_env_doc.html

\section{First section}
\textbf{Hello}
$
\begin{equation} 
c = \sqrt{a^2 + b^2}
\end{equation}
$
\begin{itemize}
\item First item
\item Second item
\end{itemize}
\textbf{World}

As you see, I am still unable to use usepackage. But maybe it will be improved in the future.

enter image description here

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I was facing the same problem today and made up a wrapper class, which checks before every method if the element reference is still valid. My solution to retrive the element is pretty simple so i thought i'd just share it.

private void setElementLocator()
{
    this.locatorVariable = "selenium_" + DateTimeMethods.GetTime().ToString();
    ((IJavaScriptExecutor)this.driver).ExecuteScript(locatorVariable + " = arguments[0];", this.element);
}

private void RetrieveElement()
{
    this.element = (IWebElement)((IJavaScriptExecutor)this.driver).ExecuteScript("return " + locatorVariable);
}

You see i "locate" or rather save the element in a global js variable and retrieve the element if needed. If the page gets reloaded this reference will not work anymore. But as long as only changes are made to doom the reference stays. And that should do the job in most cases.

Also it avoids re-searching the element.

John

Excel VBA to Export Selected Sheets to PDF

this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)

' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir

Sub luxation2()
    Dim Filename As String
    Filename = "temp201"



Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"


    ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False

End Sub

How to get complete month name from DateTime

You can use Culture to get month name for your country like:

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);

How can I send an inner <div> to the bottom of its parent <div>?

Here is another pure CSS trick, which doesn't affect an elements flow.

_x000D_
_x000D_
#parent {_x000D_
  min-height: 100vh; /* set height as you need */_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  background: grey;_x000D_
}_x000D_
.child {_x000D_
  margin-top: auto;_x000D_
  background: green;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <h1>Positioning with margin</h1>_x000D_
  <div class="child">_x000D_
    Content to the bottom_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dots in URL causes 404 with ASP.NET mvc and IIS

It's as simple as changing path="." to path="". Just remove the dot in the path for ExensionlessUrlHandler-Integrated-4.0 in web.config.

Here's a nice article https://weblog.west-wind.com/posts/2015/Nov/13/Serving-URLs-with-File-Extensions-in-an-ASPNET-MVC-Application

How to run VBScript from command line without Cscript/Wscript

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

Check the answer -> Here

And here is an example:

Converter.bat

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

Deleting an object in C++

Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete will call the object's destructor, just like new has to invoke the constructor.

If you weren't instantiating Object1 directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?

BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto, as is the default) variable of said function!

ECMAScript 6 arrow function that returns an object

Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

In my case, it turned out that global proxy settings in "Preferences->Network connections" were interfering with git. Which is kind of confusing, because git has dedicated property for proxy configuration. Anyway, I've added repository host to "Proxy bypass" list and the problem was gone.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}

2.example triggering multiple jobs from jenkins file with conditionals example:

 def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}

Access to the requested object is only available from the local network phpmyadmin

Hey, use these section of code.

Path for xampp is: apache\conf\extra\httpd-xampp.conf

 <LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Order deny,allow
        Allow from all
        #Allow from ::1 127.0.0.0/8 \
             #      fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
               #    fe80::/10 169.254.0.0/16

        ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
    </LocationMatch>

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Swift 4.x

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        let writingDirection = UIApplication.shared.userInterfaceLayoutDirection
        let factor: CGFloat = writingDirection == .leftToRight ? 1 : -1

        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount*factor, bottom: 0, right: insetAmount*factor)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount*factor, bottom: 0, right: -insetAmount*factor)
        self.contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

Usage:

button.centerTextAndImage(spacing: 10.0)

How to retrieve all keys (or values) from a std::map and put them into a vector?

The SGI STL has an extension called select1st. Too bad it's not in standard STL!

JavaFX - create custom button with image

A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.

import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class ImageButton extends Button {

    public void updateImages(final Image selected, final Image unselected) {
        final ImageView iv = new ImageView(selected);
        this.getChildren().add(iv);

        iv.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(unselected);
            }
        });
        iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(selected);
            }
        });

        super.setGraphic(iv);
    }
}

Replacing a fragment with another fragment inside activity group

hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about 1- How to switch fragment with other. 2- How to add fragment if Fragment container does not have any fragment.

then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.

public void switchFragment(BaseFragment baseFragment) {
    try {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
        if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
            ft.add(R.id.home_frame, baseFragment);
        } else {
            ft.replace(R.id.home_frame, baseFragment);
        }
        ft.addToBackStack(null);
        ft.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

enjoy your code time :)

ORDER BY using Criteria API

It's hard to know for sure without seeing the mappings (see @Juha's comment), but I think you want something like the following:

Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();

How to create file object from URL object (image)

Since Java 7

File file = Paths.get(url.toURI()).toFile();

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

When building a estimator (sklearn), if you forget to return self in the fit function, you get the same error.

class ImputeLags(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        """ do something """

    def transfrom(self, x):
        return x

AttributeError: 'NoneType' object has no attribute 'transform'?

Adding return self to the fit function fixes the error.

JSON for List of int

Assuming your ints are 0, 375, 668,5 and 6:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [
                       0,
                       375,
                       668,
                       5,
                       6
                   ]
}

I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

How do I convert a C# List<string[]> to a Javascript array?

JSON is valid JavaScript Object anyway, while you are printing JavaScript itself, you don't need to encode/decode JSON further once it is converted to JSON.

<script type="text/javascript">
    var addresses = @Html.Raw(Model.Addresses);
</script>

Following will be printed, and it is valid JavaScript Expression.

<script type="text/javascript">
    var addresses = [["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]];
</script>

Is there a short contains function for lists?

You can use this syntax:

if myItem in list:
    # do something

Also, inverse operator:

if myItem not in list:
    # do something

It's work fine for lists, tuples, sets and dicts (check keys).

Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.

Automatically start a Windows Service on install

Programmatic options for controlling services:

  • Native code can used, "Starting a Service". Maximum control with minimum dependencies but the most work.
  • WMI: Win32_Service has a StartService method. This is good for cases where you need to be able to perform other processing (e.g. to select which service).
  • PowerShell: execute Start-Service via RunspaceInvoke or by creating your own Runspace and using its CreatePipeline method to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed.
  • A .NET application can use ServiceController

AppCompat v7 r21 returning error in values.xml?

In my case with Eclipse IDE, I had the same problem and the solution was:
1- Install the latest available API (SDK Platform & Google APIs)
2- Create the project with the following settings:

  • Compile With: use the latest API version available at the time
  • the other values can receive values according at your requirements (look at the meaning of each one in previous comments)

AngularJS Multiple ng-app within a page

Use angular.bootstrap(element, [modules], [config]) to manually start up AngularJS application (for more information, see the Bootstrap guide).

See the following example:

_x000D_
_x000D_
// root-app_x000D_
const rootApp = angular.module('root-app', ['app1', 'app2']);_x000D_
_x000D_
// app1_x000D_
const app1 = angular.module('app1', []);_x000D_
app1.controller('main', function($scope) {_x000D_
  $scope.msg = 'App 1';_x000D_
});_x000D_
_x000D_
// app2_x000D_
const app2 = angular.module('app2', []);_x000D_
app2.controller('main', function($scope) {_x000D_
  $scope.msg = 'App 2';_x000D_
});_x000D_
_x000D_
// bootstrap_x000D_
angular.bootstrap(document.querySelector('#app1'), ['app1']);_x000D_
angular.bootstrap(document.querySelector('#app2'), ['app2']);
_x000D_
<!-- [email protected] -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>_x000D_
_x000D_
<!-- root-app -->_x000D_
<div ng-app="root-app">_x000D_
_x000D_
  <!-- app1 -->_x000D_
  <div id="app1">_x000D_
    <div ng-controller="main">_x000D_
      {{msg}}_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- app2 -->_x000D_
  <div id="app2">_x000D_
    <div ng-controller="main">_x000D_
      {{msg}}_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove non-numeric characters (except periods and commas) from a string

I'm surprised there's been no mention of filter_var here for this being such an old question...

PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND flags. Like so:

$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"

It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

EL interprets ${bean.propretyName} as described - the propertyName becomes getPropertyName() on the assumption you are using explicit or implicit methods of generating getter/setters

You can override this behavior by explicitly identifying the name as a function: ${bean.methodName()} This calls the function method Name() directly without modification.

It isn't always true that your accessors are named "get...".

How do I position one image on top of another in HTML?

Here's code that may give you ideas:

<style>
.containerdiv { float: left; position: relative; } 
.cornerimage { position: absolute; top: 0; right: 0; } 
</style>

<div class="containerdiv">
    <img border="0" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt=""">
    <img class="cornerimage" border="0" src="http://www.gravatar.com/avatar/" alt="">
<div>

JSFiddle

I suspect that Espo's solution may be inconvenient because it requires you to position both images absolutely. You may want the first one to position itself in the flow.

Usually, there is a natural way to do that is CSS. You put position: relative on the container element, and then absolutely position children inside it. Unfortunately, you cannot put one image inside another. That's why I needed container div. Notice that I made it a float to make it autofit to its contents. Making it display: inline-block should theoretically work as well, but browser support is poor there.

EDIT: I deleted size attributes from the images to illustrate my point better. If you want the container image to have its default sizes and you don't know the size beforehand, you cannot use the background trick. If you do, it is a better way to go.

Maven does not find JUnit tests to run

junitArtifactName might also be the case if the JUnit in use isn't the standard (junit:junit) but for instance...

<dependency>
    <groupId>org.eclipse.orbit</groupId>
    <artifactId>org.junit</artifactId>
    <version>4.11.0</version>
    <type>bundle</type>
    <scope>test</scope>
</dependency>

Using a .php file to generate a MySQL dump

If you want to create a backup to download it via the browser, you also can do this without using a file.

The php function passthru() will directly redirect the output of mysqldump to the browser. In this example it also will be zipped.

Pro: You don't have to deal with temp files.

Con: Won't work on Windows. May have limits with huge datasets.

<?php

$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";

$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";

header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );

$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";   

passthru( $cmd );

exit(0);
?>

How do I use raw_input in Python 3

A reliable way to address this is

from six.moves import input

six is a module which patches over many of the 2/3 common code base pain points.

Bash Templating: How to build configuration files from templates with Bash?

To follow up on plockc's answer on this page, here is a dash-suitable version, for those of you looking to avoid bashisms.

eval "cat <<EOF >outputfile
$( cat template.in )
EOF
" 2> /dev/null

How do I choose the URL for my Spring Boot webapp?

You need to set the property server.contextPath to /myWebApp.

Check out this part of the documentation

The easiest way to set that property would be in the properties file you are using (most likely application.properties) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation

EDIT

As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with server.servlet.contextPath as has been correctly mentioned in this answer.

Split Strings into words with multiple word boundary delimiters

I think the following is the best answer to suite your needs :

\W+ maybe suitable for this case, but may not be suitable for other cases.

filter(None, re.compile('[ |,|\-|!|?]').split( "Hey, you - what are you doing here!?")

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

How do I configure Maven for offline development?

A new plugin has appeared to fix shortcomings of mvn dependency:go-offline:

https://github.com/qaware/go-offline-maven-plugin

Add it in your pom, then run mvn -T1C de.qaware.maven:go-offline-maven-plugin:resolve-dependencies. Once you've setup all dynamic dependencies, maven won't try to download anything again (until you update versions).

SameSite warning Chrome 77

Fixed by adding crossorigin to the script tag.

From: https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

How to create a HashMap with two keys (Key-Pair, Value)?

You can also use guava Table implementation for this.

Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.

//create a table
  Table<String, String, String> employeeTable = HashBasedTable.create();

  //initialize the table with employee details
  employeeTable.put("IBM", "101","Mahesh");
  employeeTable.put("IBM", "102","Ramesh");
  employeeTable.put("IBM", "103","Suresh");

  employeeTable.put("Microsoft", "111","Sohan");
  employeeTable.put("Microsoft", "112","Mohan");
  employeeTable.put("Microsoft", "113","Rohan");

  employeeTable.put("TCS", "121","Ram");
  employeeTable.put("TCS", "122","Shyam");
  employeeTable.put("TCS", "123","Sunil");

  //get Map corresponding to IBM
  Map<String,String> ibmEmployees =  employeeTable.row("IBM");

Split Spark Dataframe string column into multiple columns

Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect, or using udfs. Unfortunately this only works for spark version 2.1 and above, because it requires the posexplode function.

Suppose you had the following DataFrame:

df = spark.createDataFrame(
    [
        [1, 'A, B, C, D'], 
        [2, 'E, F, G'], 
        [3, 'H, I'], 
        [4, 'J']
    ]
    , ["num", "letters"]
)
df.show()
#+---+----------+
#|num|   letters|
#+---+----------+
#|  1|A, B, C, D|
#|  2|   E, F, G|
#|  3|      H, I|
#|  4|         J|
#+---+----------+

Split the letters column and then use posexplode to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr to grab the element at index pos in this array.

import pyspark.sql.functions as f

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .show()
#+---+------------+---+---+
#|num|     letters|pos|val|
#+---+------------+---+---+
#|  1|[A, B, C, D]|  0|  A|
#|  1|[A, B, C, D]|  1|  B|
#|  1|[A, B, C, D]|  2|  C|
#|  1|[A, B, C, D]|  3|  D|
#|  2|   [E, F, G]|  0|  E|
#|  2|   [E, F, G]|  1|  F|
#|  2|   [E, F, G]|  2|  G|
#|  3|      [H, I]|  0|  H|
#|  3|      [H, I]|  1|  I|
#|  4|         [J]|  0|  J|
#+---+------------+---+---+

Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr which allows us use column values as parameters.

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .show()
#+---+-------+---+
#|num|   name|val|
#+---+-------+---+
#|  1|letter0|  A|
#|  1|letter1|  B|
#|  1|letter2|  C|
#|  1|letter3|  D|
#|  2|letter0|  E|
#|  2|letter1|  F|
#|  2|letter2|  G|
#|  3|letter0|  H|
#|  3|letter1|  I|
#|  4|letter0|  J|
#+---+-------+---+

Now we can just groupBy the num and pivot the DataFrame. Putting that all together, we get:

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .groupBy("num").pivot("name").agg(f.first("val"))\
    .show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#|  1|      A|      B|      C|      D|
#|  3|      H|      I|   null|   null|
#|  2|      E|      F|      G|   null|
#|  4|      J|   null|   null|   null|
#+---+-------+-------+-------+-------+

adding 1 day to a DATETIME format value

If you want to do this in PHP:

// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));

If you want to add the date in MySQL:

-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);

How do I implement interfaces in python?

There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError so that subclasses will be on notice that they'd better override those methods!-)

How to mute an html5 video player using jQuery

Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example

What is [Serializable] and when should I use it?

Serialization

Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization

Uses of Serialization

  1. To save the state of an object into a file, database etc. and use it latter.
  2. To send an object from one process to another (App Domain) on the same machine and also send it over wire to a process running on another machine.
  3. To create a clone of the original object as a backup while working on the main object.
  4. A set of objects can easily be copied to the system’s clipboard and then pasted into the same or another application

Below are some useful custom attributes that are used during serialization of an object

[Serializable] -> It is used when we mark an object’s serializable [NonSerialized] -> It is used when we do not want to serialize an object’s field. [OnSerializing] -> It is used when we want to perform some action while serializing an object [OnSerialized] -> It is used when we want to perform some action after serialized an object into stream.

Below is the example of serialization

[Serializable]
    internal class DemoForSerializable
    {
        internal string Fname = string.Empty;
        internal string Lname = string.Empty;

        internal Stream SerializeToMS(DemoForSerializable demo)
        {
            DemoForSerializable objSer = new DemoForSerializable();
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, objSer);
            return ms;
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext context) {
            Fname = "sheo";
            Lname = "Dayal";
        }
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
       // Do some work after serialized object
        }

    }

Here is the calling code

class Program
    {
        string fname = string.Empty;
        string Lname = string.Empty; 

       static void Main(string[] args)
        {
            DemoForSerializable demo = new DemoForSerializable();

            Stream ms = demo.SerializeToMS(demo);
            ms.Position = 0;

            DemoForSerializable demo1 = new BinaryFormatter().Deserialize(ms) as DemoForSerializable;

            Console.WriteLine(demo1.Fname);
            Console.WriteLine(demo1.Lname);
            Console.ReadLine();
        }

    }

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

One of the principal issues with pushing to a GIT is that the material you push will appear as your material, and will block submissions from other people on a team. As a GIT repository administrator, you will have to manage the hooks to prevent Alice's push from blocking Bob from pushing. To do that, you will want to ensure that your developers all belong to a group, lets call it 'developers' and that the repository is owned by root:developers, and then add this to the hooks/post-update script:

sudo chown -R root:developers $GIT_DIR
sudo chmod -R g+w $GIT_DIR

That will make it so that team members are able to push to the repository without stepping on each other's toes.

How to end C++ code

If your if statement is in Loop You can use

 break; 

If you want to escape some code & continue to loop Use :

continue;

If your if statement not in Loop You can use :

 return 0;

Or 




  exit();

In PHP how can you clear a WSDL cache?

You can safely delete the WSDL cache files. If you wish to prevent future caching, use:

ini_set("soap.wsdl_cache_enabled", 0);

or dynamically:

$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );

How can I make the browser wait to display the page until it's fully loaded?

I think this is a really bad idea. Users like to see progress, plain and simple. Keeping the page at one state for a few seconds and then instantly displaying the loaded page will make the user feel like nothing is happening and you are likely to lose visits.

One option is to show a loading status on your page while stuff processes in the background, but this is normally reserved for when the site is actually doing processing on user input.

http://www.webdeveloper.com/forum/showthread.php?t=180958

The bottom line, you at least need to show some visual activity while the page is loading, and I think having the page load in little pieces at a time is not all that bad (assuming you aren't doing something that seriously slows down page load time).

Docker - Ubuntu - bash: ping: command not found

Sometimes, the minimal installation of Linux in Docker doesn't define the path and therefore it is necessary to call ping using ....

cd /usr/sbin
ping <ip>

Laravel 5.4 redirection to custom url after login

If you look in the AuthenticatesUsers trait you will see that in the sendLoginResponse method that there is a call made to $this->redirectPath(). If you look at this method then you will discover that the redirectTo can either be a method or a variable.

This is what I now have in my auth controller.

public function redirectTo() {
    $user = Auth::user();
    switch(true) {
        case $user->isInstructor():
            return '/instructor';
        case $user->isAdmin():
        case $user->isSuperAdmin():
            return '/admin';
        default:
            return '/account';
    }
}

How to filter multiple values (OR operation) in angularJS

I've spent some time on it and thanks to @chrismarx, I saw that angular's default filterFilter allows you to pass your own comparator. Here's the edited comparator for multiple values:

  function hasCustomToString(obj) {
        return angular.isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  }
  var comparator = function (actual, expected) {
    if (angular.isUndefined(actual)) {
      // No substring matching against `undefined`
      return false;
    }
    if ((actual === null) || (expected === null)) {
      // No substring matching against `null`; only match against `null`
      return actual === expected;
    }
    // I edited this to check if not array
    if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
      // Should not compare primitives against objects, unless they have custom `toString` method
      return false;
    }
    // This is where magic happens
    actual = angular.lowercase('' + actual);
    if (angular.isArray(expected)) {
      var match = false;
      expected.forEach(function (e) {
        e = angular.lowercase('' + e);
        if (actual.indexOf(e) !== -1) {
          match = true;
        }
      });
      return match;
    } else {
      expected = angular.lowercase('' + expected);
      return actual.indexOf(expected) !== -1;
    }
  };

And if we want to make a custom filter for DRY:

angular.module('myApp')
    .filter('filterWithOr', function ($filter) {
      var comparator = function (actual, expected) {
        if (angular.isUndefined(actual)) {
          // No substring matching against `undefined`
          return false;
        }
        if ((actual === null) || (expected === null)) {
          // No substring matching against `null`; only match against `null`
          return actual === expected;
        }
        if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
          // Should not compare primitives against objects, unless they have custom `toString` method
          return false;
        }
        console.log('ACTUAL EXPECTED')
        console.log(actual)
        console.log(expected)

        actual = angular.lowercase('' + actual);
        if (angular.isArray(expected)) {
          var match = false;
          expected.forEach(function (e) {
            console.log('forEach')
            console.log(e)
            e = angular.lowercase('' + e);
            if (actual.indexOf(e) !== -1) {
              match = true;
            }
          });
          return match;
        } else {
          expected = angular.lowercase('' + expected);
          return actual.indexOf(expected) !== -1;
        }
      };
      return function (array, expression) {
        return $filter('filter')(array, expression, comparator);
      };
    });

And then we can use it anywhere we want:

$scope.list=[
  {name:'Jack Bauer'},
  {name:'Chuck Norris'},
  {name:'Superman'},
  {name:'Batman'},
  {name:'Spiderman'},
  {name:'Hulk'}
];


<ul>
  <li ng-repeat="item in list | filterWithOr:{name:['Jack','Chuck']}">
    {{item.name}}
  </li>
</ul>

Finally here's a plunkr.

Note: Expected array should only contain simple objects like String, Number etc.

Difference between $.ajax() and $.get() and $.load()

$.get = $.ajax({type: 'GET'});

$.load() is a helper function which only can be invoked on elements.

$.ajax() gives you most control. you can specify if you want to POST data, got more callbacks etc.

Datatable date sorting dd/mm/yyyy issue

I wanted to point out that when using data from the server via Ajax, the solution is super simple, but may not be immediately obvious.

When returning the sort order array, Datatables will send (in the $_POST) a 2 element array that would be equivalent to:

$_POST['order'][0] =array('column'=>'SortColumnName', 'dir'=>'asc'); 
// 2nd element is either 'asc' or 'desc'

Therefore, you may display the date in any format you want; just have your server return the sorting criteria based only upon the sortColumnName.

For example, in PHP (with MySQL), I use the following:

 if (isset($_POST['order'])) {
          switch ($_POST['order'][0]['column']) {
               case 0:// sort by Primary Key
                    $order = 'pkItemid';
                    break;
               case 1:// Sort by reference number
                    $order = 'refNo';
                    break;
               case 2://Date Started
                    $order = 'dOpen';
                    break;
               default :
                    $order = 'pkItemid';
          }
          $orderdir = ($_POST['order'][0]['dir'] === 'desc') ? 'desc' : 'asc';
     }

Note, that since nothing from the $_POST is passed to $order or $orderdir, no cross-script attack is possible.

Now, just append to a MySQL query:

$sql ="SELECT pkItemid, refNo, DATE_FORMAT(dOpen,'%b %e, %Y') AS dateStarted
       FROM tblReference 
       ORDER BY $order $orderdir;";

run the query, and return just the dateStarted value to Datatables in json.

How to make IPython notebook matplotlib plot inline

I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:

%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt

You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.

Can I target all <H> tags with a single selector?

You can also use PostCSS and the custom selectors plugin

@custom-selector :--headings h1, h2, h3, h4, h5, h6;

article :--headings {
  margin-top: 0;
}

Output:

article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
  margin-top: 0;
}

When to use cla(), clf() or close() for clearing a plot in matplotlib?

They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure class. I will discuss both cases below.

pyplot interface

pyplot is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that pyplot has been imported as import matplotlib.pyplot as plt. In this case, there are three different commands that remove stuff:

plt.cla() clears an axes, i.e. the currently active axes in the current figure. It leaves the other axes untouched.

plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close() closes a window, which will be the current window, if not specified otherwise.

Which functions suits you best depends thus on your use-case.

The close() function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using figure(number_or_name) or it can be a figure instance fig obtained, i.e., usingfig = figure(). If no argument is given to close(), the currently active window will be closed. Furthermore, there is the syntax close('all'), which closes all figures.

methods of the Figure class

Additionally, the Figure class provides methods for clearing figures. I'll assume in the following that fig is an instance of a Figure:

fig.clf() clears the entire figure. This call is equivalent to plt.clf() only if fig is the current figure.

fig.clear() is a synonym for fig.clf()

Note that even del fig will not close the associated figure window. As far as I know the only way to close a figure window is using plt.close(fig) as described above.

Appending to an object

You can use spread syntax as follows..

var alerts = { 
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
 }

alerts = {...alerts, 3: {app: 'hey there', message: 'another message'} }

How can I iterate over files in a given directory?

Since Python 3.5, things are much easier with os.scandir()

with os.scandir(path) as it:
    for entry in it:
        if entry.name.endswith(".asm") and entry.is_file():
            print(entry.name, entry.path)

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

Make error: missing separator

My error was on a variable declaration line with a multi-line extension. I have a trailing space after the "\" which made that an invalid line continuation.

MY_VAR = \
   val1 \ <-- 0x20 there caused the error.
   val2

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

How to change the background color of Action Bar's Option Menu in Android 4.2?

The Action Bar Style Generator, suggested by Sunny, is very useful, but it generates a lot of files, most of which are irrelevant if you only want to change the background colour.

So, I dug deeper into the zip it generates, and tried to narrow down what are the parts that matter, so I can make the minimum amount of changes to my app. Below is what I found out.


In the style generator, the relevant setting is Popup color, which affects "Overflow menu, submenu and spinner panel background".

enter image description here

Go on and generate the zip, but out of all the files generated, you only really need one image, menu_dropdown_panel_example.9.png, which looks something like this:

enter image description here

So, add the different resolution versions of it to res/drawable-*. (And perhaps rename them to menu_dropdown_panel.9.png.)

Then, as an example, in res/values/themes.xml you would have the following, with android:popupMenuStyle and android:popupBackground being the key settings.

<resources>

    <style name="MyAppActionBarTheme" parent="android:Theme.Holo.Light">
        <item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
        <item name="android:actionBarStyle">@style/MyApp.ActionBar</item>
    </style>

    <!-- The beef: background color for Action Bar overflow menu -->
    <style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel</item>
    </style>

    <!-- Bonus: if you want to style whole Action Bar, not just the menu -->
    <style name="MyApp.ActionBar" parent="android:Widget.Holo.Light.ActionBar.Solid">
        <!-- Blue background color & black bottom border -->
        <item name="android:background">@drawable/blue_action_bar_background</item>
    </style>   

</resources>

And, of course, in AndroidManifest.xml:

<application
    android:theme="@style/MyAppActionBarTheme" 
    ... >

What you get with this setup:

enter image description here

Note that I'm using Theme.Holo.Light as the base theme. If you use Theme.Holo (Holo Dark), there's an additional step needed as this answer describes!

Also, if you (like me) wanted to style the whole Action Bar, not just the menu, put something like this in res/drawable/blue_action_bar_background.xml:

<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="#FF000000" />
            <solid android:color="#FF2070B0" />                   
        </shape>
    </item>

    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="#FF2070B0" />
            <solid android:color="#00000000" />
            <padding android:bottom="2dp" />
        </shape>
    </item>

</layer-list>

Works great at least on Android 4.0+ (API level 14+).

Xcode 9 Swift Language Version (SWIFT_VERSION)

I just click on latest swift convert button and set App target build setting-> Swift language version: swift 4.0,

Hope this will help.

Difference between AutoPostBack=True and AutoPostBack=False?

If you want a control to postback automatically when an event is raised, you need to set the AutoPostBack property of the control to True.

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

How to get current local date and time in Kotlin

Another solution is changing the api level of your project in build.gradle and this will work.

How to increment a variable on a for loop in jinja template?

Came searching for Django's way of doing this and found this post. Maybe someone else need the django solution who come here.

{% for item in item_list %}
    {{ forloop.counter }} {# starting index 1 #}
    {{ forloop.counter0 }} {# starting index 0 #}

    {# do your stuff #}
{% endfor %}

Read more here: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/

Expand div to max width when float:left is set

Solution without fixing size on your margin

.content .right{
    overflow: auto; 
    background-color: red;
}

+1 for Merkuro, but if the size of the float changes your fixed margin will fail. If u use above CSS on the right div it will nicely change size with changing size on the left float. It is a bit more flexible like that. Check the fiddle here: http://jsfiddle.net/9ZHBK/144/

How do I add a simple onClick event handler to a canvas element?

I recommand the following article : Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes which goes through various situations.

However, it does not cover the addHitRegion API, which must be the best way (using math functions and/or comparisons is quite error prone). This approach is detailed on developer.mozilla

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Increasing the Command Timeout for SQL command

Add timeout of your SqlCommand. Please note time is in second.

// Setting command timeout to 1 second
scGetruntotals.CommandTimeout = 1;

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

How to get input from user at runtime

To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT.

Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'

example

accept x number prompt 'Please enter something: '

And then you can use the x variable in a PL/SQL block as follows:

declare 
  a number;
begin
  a := &x;
end;
/

Working with a string example:

accept x char prompt 'Please enter something: '

declare 
  a varchar2(10);
begin
  a := '&x';   -- for a substitution variable of char data type 
end;           -- to be treated as a character string it needs
/              -- to be enclosed with single quotation marks

How to align a <div> to the middle (horizontally/width) of the page

  1. Do you mean that you want to center it vertically or horizontally? You said you specified the height to 800 pixels, and wanted the div not to stretch when the width was greater than that...

  2. To center horizontally, you can use the margin: auto; attribute in CSS. Also, you'll have to make sure that the body and html elements don't have any margin or padding:

html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }

Creating dummy variables in pandas for python

For my case, dmatrices in patsy solved my problem. Actually, this function is designed for the generation of dependent and independent variables from a given DataFrame with an R-style formula string. But it can be used for the generation of dummy features from the categorical features. All you need to do would be drop the column 'Intercept' that is generated by dmatrices automatically regardless of your original DataFrame.

import pandas as pd
from patsy import dmatrices

df_original = pd.DataFrame({
   'A': ['red', 'green', 'red', 'green'],
   'B': ['car', 'car', 'truck', 'truck'],
   'C': [10,11,12,13],
   'D': ['alice', 'bob', 'charlie', 'alice']},
   index=[0, 1, 2, 3])

_, df_dummyfied = dmatrices('A ~ A + B + C + D', data=df_original, return_type='dataframe')
df_dummyfied = df_dummyfied.drop('Intercept', axis=1)

df_dummyfied.columns    
Index([u'A[T.red]', u'B[T.truck]', u'D[T.bob]', u'D[T.charlie]', u'C'], dtype='object')

df_dummyfied
   A[T.red]  B[T.truck]  D[T.bob]  D[T.charlie]     C
0       1.0         0.0       0.0           0.0  10.0
1       0.0         0.0       1.0           0.0  11.0
2       1.0         1.0       0.0           1.0  12.0
3       0.0         1.0       0.0           0.0  13.0

Maximum packet size for a TCP connection

If you are with Linux machines, "ifconfig eth0 mtu 9000 up" is the command to set the MTU for an interface. However, I have to say, big MTU has some downsides if the network transmission is not so stable, and it may use more kernel space memories.

What is the shortcut to Auto import all in Android Studio?

On Windows, highlight the code that has classes which need to be resolved and hit Alt+Enter

Use a JSON array with objects with javascript

This is your dataArray:

[
   {
      "id":28,
      "Title":"Sweden"
   },
   {
      "id":56,
      "Title":"USA"
   },
   {
      "id":89,
      "Title":"England"
   }
]

Then parseJson can be used:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

How to compare values which may both be null in T-SQL

You will have to use IS NULL or ISNULL. There really isn't a away around it.

Convert pandas dataframe to NumPy array

To convert a pandas dataframe (df) to a numpy ndarray, use this code:

df.values

array([[nan, 0.2, nan],
       [nan, nan, 0.5],
       [nan, 0.2, 0.5],
       [0.1, 0.2, nan],
       [0.1, 0.2, 0.5],
       [0.1, nan, 0.5],
       [0.1, nan, nan]])

Is there a C++ gdb GUI for Linux?

Eclipse CDT will provide an experience comparable to using Visual Studio. I use Eclipse CDT on a daily basis for writing code and debugging local and remote processes.

If your not familiar with using an Eclipse based IDE, the GUI will take a little getting used to. However, once you get to understand the GUI ideas that are unique to Eclipse (e.g. a perspective), using the tool becomes a nice experience.

The CDT tooling provides a decent C/C++ indexer that allows you to quickly find references to methods in your code base. It also provides a nice macro expansion tool and limited refactoring support.

With regards to support for debugging, CDT is able to do everything in your list with the exception of reading a core dump (it may support this, but I have never tried to use this feature). Also, my experience with debugging code using templates is limited, so I'm not sure what kind of experience CDT will provide in this regard.

For more information about debugging using Eclipse CDT, you may want to check out these guides:

Android and setting alpha for (image) view alpha

I am not sure about the XML but you can do it by code in the following way.

ImageView myImageView = new ImageView(this);
myImageView.setAlpha(xxx);

In pre-API 11:

  • range is from 0 to 255 (inclusive), 0 being transparent and 255 being opaque.

In API 11+:

  • range is from 0f to 1f (inclusive), 0f being transparent and 1f being opaque.

Predict() - Maybe I'm not understanding it

instead of newdata you are using newdate in your predict code, verify once. and just use Coupon$estimate <- predict(model, Coupon) It will work.

Set div height to fit to the browser using CSS

I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.

Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)

More about fr units here.

_x000D_
_x000D_
.container{
  width: 100vw;
  height:100vh; 
  display: grid;
  grid-template-columns: 1fr 3fr;
}

/*You don't need this*/
.div1{
  background-color: yellow;
}

.div2{
  background-color: red;
}
_x000D_
<div class='container'>
  <div class='div1'>This is div 1</div>
  <div class='div2'>This is div 2</div>
</div>
_x000D_
_x000D_
_x000D_

Binding Listbox to List<object> in WinForms

Granted, this isn't going to provide you anything truly meaningful unless the objects have properly overriden ToString() (or you're not really working with a generic list of objects and can bind to specific fields):

List<object> objList = new List<object>();

// Fill the list

someListBox.DataSource = objList;

What is the difference between “int” and “uint” / “long” and “ulong”?

The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.

The limits for int (32 bit) are:

int: –2147483648 to 2147483647 
uint: 0 to 4294967295 

And for long (64 bit):

long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Create SQL script that create database and tables

Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:

Right-click on the Database, select Tasks and then Generate Scripts, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.

If you are happy with the default options, you can do the whole job in a matter of seconds.

If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).

Turning multi-line string into single comma-separated

You can also print like this:

Just awk: using printf

bash-3.2$ cat sample.log
something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)

bash-3.2$ awk ' { if($2 != "") { if(NR==1) { printf $2 } else { printf "," $2 } } }' sample.log
+12.0,+15.5,+9.0,+13.5

SVN: Is there a way to mark a file as "do not commit"?

I came to this thread looking for a way to make an "atomic" commit of just some files and instead of ignoring some files on commit I went the other way and only commited the files I wanted:

svn ci filename1 filename2

Maybe, it will help someone.

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

The C++ ? General ? Additional Include Directories parameter is for listing directories where the compiler will search for header files.

You need to tell the linker where to look for libraries to link to. To access this setting, right-click on the project name in the Solution Explorer window, then Properties ? Linker ? General ? Additional Library Directories. Enter <boost_path>\stage\lib here (this is the path where the libraries are located if you build Boost using default options).

Angular2 - Input Field To Accept Only Numbers

I have made some modifications in the above directive and implemented min, max, maxlength.

   import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[numberOnly]'
})
export class NumbersOnlyDirective {

  private regex: RegExp = new RegExp(/[0-9]/g);
  // Allow key codes for special events. Reflect :
  private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
  // Backspace, tab, end, home

  @Input() maxlength: number;
  @Input() min: number;
  @Input() max: number;

  constructor(private el: ElementRef) {
  }
    @HostListener('keydown', ['$event'])
    onKeyDown(event: KeyboardEvent) {
    e = <KeyboardEvent>event;

if ((
  (this.specialKeys.indexOf(event.which) > -1) ||
  // to allow backspace, enter, escape, arrows  
  (e.which == 65 && e.ctrlKey == true) ||
  // Allow: Ctrl+C        
  (e.which == 67 && e.ctrlKey == true) ||
  // Allow: Ctrl+X
  (e.which == 88 && e.ctrlKey == true))) {
  return;
} else if (// to allow numbers  
  (e.which >= 48 && e.which <= 57) ||
  // to allow numpad number  
  (event.which >= 96 && event.which <= 105)) { }
else {
      event.preventDefault();
    }
    let current: string = this.el.nativeElement.value;

    let next: string = current.concat(event.key);
    if ((next && !String(next).match(this.regex)) ||
      (this.maxlength && next.length > this.maxlength) ||
      (this.min && +next < this.min) ||
      (this.max && +next >= this.max)) {
      event.preventDefault();
    }

  }
}

SQL alias for SELECT statement

You can do this using the WITH clause of the SELECT statement:

;
WITH my_select As (SELECT ... FROM ...) 
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...

.NET obfuscation tools/strategy

I've been also using SmartAssembly. I found that Ezrinz .Net Reactor much better for me on .net applications. It obfuscates, support Mono, merges assemblies and it also also has a very nice licensing module to create trial version or link the licence to a particular machine (very easy to implement). Price is also very competitive and when I needed support they where fast. Eziriz

Just to be clear I'm just a custumer who likes the product and not in any way related with the company.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

After trying most of the solutions here, I finally just added a reference to the project from the click once project, this changed it to Include (Auto) from Include and it finally worked.

What values for checked and selected are false?

Actually, the HTML 4.01 spec says that these attributes do not require values. I haven't personally encountered a situation where providing a value rendered these controls as unselected.

Here are the respective links to the spec document for selected and checked.

Edit: Firebug renders the checkbox as checked regardless of any values I put in quotes for the checked attribute (including just typing "checked" with no values whatsoever), and IE 8's Developer Tools forces checked="checked". I'm not sure if any similar tools exist for other browsers that might alter the rendered state of a checkbox, however.

Failure during conversion to COFF: file invalid or corrupt

If you have installed VS2012 as well, the old cvtres file will no longer work.

Try removing the file (I simply renamed):
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\cvtres.exe

You can also debug using the /VERBOSE linker option in order to get more information regarding the linker error. There you should see an error message that the invoke to cvtres fails.

LINQ orderby on date field in descending order

I was trying to also sort by a DateTime field descending and this seems to do the trick:

var ud = (from d in env 
     orderby -d.ReportDate.Ticks                 
     select  d.ReportDate.ToString("yyyy-MMM") ).Distinct(); 

react-router scroll to top on every transition

My solution: a component that I'm using in my screens components (where I want a scroll to top).

import { useLayoutEffect } from 'react';

const ScrollToTop = () => {
    useLayoutEffect(() => {
        window.scrollTo(0, 0);
    }, []);

    return null;
};

export default ScrollToTop;

This preserves scroll position when going back. Using useEffect() was buggy for me, when going back the document would scroll to top and also had a blink effect when route was changed in an already scrolled document.

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>
#include <conio.h>
int main()
{
    int i,j;
    int b=0;
    for (i=2;i<=100;i++){
        for (j=2;j<=i;j++){
            if (i%j==0){
                break;
            }
        }
        if (i==j)
            print f("\n%d",j);
    }
    getch ();
}

Using jquery to get all checked checkboxes with a certain class name

I know this has a bunch of great answers on this question already but I found this while browsing around and I find it really easy to use. Thought I'd share for anyone else looking.

HTML:

<fieldset>
    <!-- these will be affected by check all -->
    <div><input type="checkbox" class="checkall"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- these won't be affected by check all; different field set -->
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>

jQuery:

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
});

Reference: Easiest "Check All" with jQuery

Convert a date format in PHP

Use date_create and date_format

Try this.

function formatDate($input, $output){
  $inputdate = date_create($input);
  $output = date_format($inputdate, $output);
  return $output;
}

How to check if a string contains a substring in Bash

I use this function (one dependency not included but obvious). It passes the tests shown below. If the function returns a value > 0 then the string was found. You could just as easily return 1 or 0 instead.

function str_instr {
   # Return position of ```str``` within ```string```.
   # >>> str_instr "str" "string"
   # str: String to search for.
   # string: String to search.
   typeset str string x
   # Behavior here is not the same in bash vs ksh unless we escape special characters.
   str="$(str_escape_special_characters "${1}")"
   string="${2}"
   x="${string%%$str*}"
   if [[ "${x}" != "${string}" ]]; then
      echo "${#x} + 1" | bc -l
   else
      echo 0
   fi
}

function test_str_instr {
   str_instr "(" "'foo@host (dev,web)'" | assert_eq 11
   str_instr ")" "'foo@host (dev,web)'" | assert_eq 19
   str_instr "[" "'foo@host [dev,web]'" | assert_eq 11
   str_instr "]" "'foo@host [dev,web]'" | assert_eq 19
   str_instr "a" "abc" | assert_eq 1
   str_instr "z" "abc" | assert_eq 0
   str_instr "Eggs" "Green Eggs And Ham" | assert_eq 7
   str_instr "a" "" | assert_eq 0
   str_instr "" "" | assert_eq 0
   str_instr " " "Green Eggs" | assert_eq 6
   str_instr " " " Green "  | assert_eq 1
}

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I had a similar issue. I had mentioned a wrong output folder path in angular.json

"outputPath": "dist/",

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

How to get the current location latitude and longitude in android

Use Location Listener Method

@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}

good example of Javadoc

The documentation of Google Guava's EventBus package and classes is a good example of Javadoc. Especially the package documentation with the quick start is well written.

@property retain, assign, copy, nonatomic in Objective-C

After reading many articles I decided to put all the attributes information together:

  1. atomic //default
  2. nonatomic
  3. strong=retain //default
  4. weak= unsafe_unretained
  5. retain
  6. assign //default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite //default

Below is a link to the detailed article where you can find these attributes.

Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

Here is the Sample Description from Article

  1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :

@property (retain) NSString *name;

@synthesize name;
  1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;

Explain:

Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

  1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
  1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

  1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;
  1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;
  1. unsafe_unretained

    -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

Example:

@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;
  1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Example:

@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

What is the best open XML parser for C++?

I am a C++ newbie and after trying a couple different suggestions on this page I must say I like pugixml the most. It has easy to understand documentation and a high level API which was all I was looking for.

How do I execute a stored procedure once for each row returned by query?

use a cursor

ADDENDUM: [MS SQL cursor example]

declare @field1 int
declare @field2 int
declare cur CURSOR LOCAL for
    select field1, field2 from sometable where someotherfield is null

open cur

fetch next from cur into @field1, @field2

while @@FETCH_STATUS = 0 BEGIN

    --execute your sproc on each row
    exec uspYourSproc @field1, @field2

    fetch next from cur into @field1, @field2
END

close cur
deallocate cur

in MS SQL, here's an example article

note that cursors are slower than set-based operations, but faster than manual while-loops; more details in this SO question

ADDENDUM 2: if you will be processing more than just a few records, pull them into a temp table first and run the cursor over the temp table; this will prevent SQL from escalating into table-locks and speed up operation

ADDENDUM 3: and of course, if you can inline whatever your stored procedure is doing to each user ID and run the whole thing as a single SQL update statement, that would be optimal

Using PowerShell credentials without being prompted for a password

why dont you try something very simple?

use psexec with command 'shutdown /r /f /t 0' and a PC list from CMD.

TypeScript function overloading

As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.

myComponent {
  method(): { console.info("no args"); },
  method(arg): { console.info("with arg"); }
}

Calling:

myComponent.method()

seems to execute the method with arguments, silently ignoring the no-arg version, with output:

with arg

Can I replace groups in Java regex?

You could use Matcher#start(group) and Matcher#end(group) to build a generic replacement method:

public static String replaceGroup(String regex, String source, int groupToReplace, String replacement) {
    return replaceGroup(regex, source, groupToReplace, 1, replacement);
}

public static String replaceGroup(String regex, String source, int groupToReplace, int groupOccurrence, String replacement) {
    Matcher m = Pattern.compile(regex).matcher(source);
    for (int i = 0; i < groupOccurrence; i++)
        if (!m.find()) return source; // pattern not met, may also throw an exception here
    return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), replacement).toString();
}

public static void main(String[] args) {
    // replace with "%" what was matched by group 1 
    // input: aaa123ccc
    // output: %123ccc
    System.out.println(replaceGroup("([a-z]+)([0-9]+)([a-z]+)", "aaa123ccc", 1, "%"));

    // replace with "!!!" what was matched the 4th time by the group 2
    // input: a1b2c3d4e5
    // output: a1b2c3d!!!e5
    System.out.println(replaceGroup("([a-z])(\\d)", "a1b2c3d4e5", 2, 4, "!!!"));
}

Check online demo here.

How can I use different certificates on specific connections?

If creating a SSLSocketFactory is not an option, just import the key into the JVM

  1. Retrieve the public key: $openssl s_client -connect dev-server:443, then create a file dev-server.pem that looks like

    -----BEGIN CERTIFICATE----- 
    lklkkkllklklklklllkllklkl
    lklkkkllklklklklllkllklkl
    lklkkkllklk....
    -----END CERTIFICATE-----
    
  2. Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem. Password: changeit

  3. Restart JVM

Source: How to solve javax.net.ssl.SSLHandshakeException?

Why is String immutable in Java?

From the Security point of view we can use this practical example:

DBCursor makeConnection(String IP,String PORT,String USER,String PASS,String TABLE) {

    // if strings were mutable IP,PORT,USER,PASS can be changed by validate function
    Boolean validated = validate(IP,PORT,USER,PASS);

    // here we are not sure if IP, PORT, USER, PASS changed or not ??
    if (validated) {
         DBConnection conn = doConnection(IP,PORT,USER,PASS);
    }

    // rest of the code goes here ....
}

How to access model hasMany Relation with where condition?

Just in case anyone else encounters the same problems.

Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().

You can easily find out investigating the Laravel source:

// Illuminate\Database\Eloquent\Model.php
...
/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

This also explains why my code worked, whenever I loaded the data using the load() method before.

Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.

wget can't download - 404 error

Actually I don't know what is the reason exactly, I have faced this like of problem. if you have the domain's IP address (ex 208.113.139.4), please use the IP address instead of domain (in this case www.icerts.com)

wget 192.243.111.11/images/logo.jpg

Go to find the IP from URL https://ipinfo.info/html/ip_checker.php

What is the difference between declarations, providers, and import in NgModule?

imports are used to import supporting modules like FormsModule, RouterModule, CommonModule, or any other custom-made feature module.

declarations are used to declare components, directives, pipes that belong to the current module. Everyone inside declarations knows each other. For example, if we have a component, say UsernameComponent, which displays a list of the usernames and we also have a pipe, say toupperPipe, which transforms a string to an uppercase letter string. Now If we want to show usernames in uppercase letters in our UsernameComponent then we can use the toupperPipe which we had created before but the question is how UsernameComponent knows that the toupperPipe exists and how it can access and use that. Here come the declarations, we can declare UsernameComponent and toupperPipe.

Providers are used for injecting the services required by components, directives, pipes in the module.

How do I clone a Django model instance object and save it to the database?

If you have a OneToOneField then you should do it this way:

    tmp = Foo.objects.get(pk=1)
    tmp.pk = None
    tmp.id = None
    instance = tmp

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

How to always show the vertical scrollbar in a browser?

Just a note: In OS X Lion, overflow set to "scroll" behaves more like auto in that scrollbars will only show when being used. They will disappear when not in use. So if any the solutions above don't appear to be working that might be why.

This is what you'll need to fix it:

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 7px;
}
::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: rgba(0, 0, 0, .5);
  -webkit-box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}

You can style it accordingly.

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

How do I increase memory on Tomcat 7 when running as a Windows Service?

//ES/tomcat -> This may not work if you have changed the service name during the installation.

Either run the command without any service name

.\bin\tomcat7w.exe //ES

or with exact service name

.\bin\tomcat7w.exe //ES/YourServiceName

cURL error 60: SSL certificate: unable to get local issuer certificate

If you are using PHP 5.6 with Guzzle, Guzzle has switched to using the PHP libraries autodetect for certificates rather than it's process (ref). PHP outlines the changes here.

Finding out Where PHP/Guzzle is Looking for Certificates

You can dump where PHP is looking using the following PHP command:

 var_dump(openssl_get_cert_locations());

Getting a Certificate Bundle

For OS X testing, you can use homebrew to install openssl brew install openssl and then use openssl.cafile=/usr/local/etc/openssl/cert.pem in your php.ini or Zend Server settings (under OpenSSL).

A certificate bundle is also available from curl/Mozilla on the curl website: https://curl.haxx.se/docs/caextract.html

Telling PHP Where the Certificates Are

Once you have a bundle, either place it where PHP is already looking (which you found out above) or update openssl.cafile in php.ini. (Generally, /etc/php.ini or /etc/php/7.0/cli/php.ini or /etc/php/php.ini on Unix.)

Redirect to specified URL on PHP script completion?

don't forget to put a 'die' after your call to make the redirect happen before the rest of the code on the page is run threw. a. if you have header functions further down the page they will override the ones further up the code.

b: im assuming you dont want the rest of the code on the page to be run and that why your putting this redirect in in the first place [maybe].

example:

<?php

// do something here

header("Location: http://example.com/thankyou.php");
die();

//code down here now wont get run

?>

How can I remove the outline around hyperlinks images?

I would bet most users aren't the type of user that use the keyboard as a navigation control. Is it then acceptable to annoy the majority of your users for a small group that prefers to use keyboard navigation? Short answer — depends on who your users are.

Also, I don't see this experience in the same way in Firefox and Safari. So this argument seems to be mostly for IE. It all really depends on your user base and their level of knowledge — how they use the site.

If you really want to know where you are and you are a keyboard user, you can always look at the status bar as you key through the site.

How can I do a case insensitive string comparison?

You should use static String.Compare function like following

x => String.Compare (x.Username, (string)drUser["Username"],
                     StringComparison.OrdinalIgnoreCase) == 0

How to add url parameters to Django template url tag?

Im not sure if im out of the subject, but i found solution for me; You have a class based view, and you want to have a get parameter as a template tag:

class MyView(DetailView):
    model = MyModel

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['tag_name'] = self.request.GET.get('get_parameter_name', None)
        return ctx

Then you make your get request /mysite/urlname?get_parameter_name='stuff.

In your template, when you insert {{ tag_name }}, you will have access to the get parameter value ('stuff'). If you have an url in your template that also needs this parameter, you can do

 {% url 'my_url' %}?get_parameter_name={{ tag_name }}"

You will not have to modify your url configuration

PHP mPDF save file as PDF

Try this:

$mpdf->Output('my_filename.pdf','D'); 

because:

D - means Download
F - means File-save only

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Just add this line of code in your build.gradle file and it will work.

implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

Also add these below line if above did not work at all.

compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
    exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'

compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'

TypeScript for ... of with index / key?

"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}

Javascript change font color

Try like this:

var clr = 'green';
var html = '<font color="' + clr + '">' + onlineff + ' </font>';

This being said, you should avoid using the <font> tag. It is now deprecated. Use CSS to change the style (color) of a given element in your markup.

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

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

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

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

How do I implement IEnumerable<T>

If you choose to use a generic collection, such as List<MyObject> instead of ArrayList, you'll find that the List<MyObject> will provide both generic and non-generic enumerators that you can use.

using System.Collections;

class MyObjects : IEnumerable<MyObject>
{
    List<MyObject> mylist = new List<MyObject>();

    public MyObject this[int index]  
    {  
        get { return mylist[index]; }  
        set { mylist.Insert(index, value); }  
    } 

    public IEnumerator<MyObject> GetEnumerator()
    {
        return mylist.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

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

Here comes the long-winded – yet easy to understand – script, inspired by the solution of nicerobot, that only requests the response headers and avoids using IFS as suggested here. It outputs a bounce message when it encounters a response >= 400. This echo can be replaced with a bounce-script.

# set the url to probe
url='http://localhost:8080'
# use curl to request headers (return sensitive default on timeout: "timeout 500"). Parse the result into an array (avoid settings IFS, instead use read)
read -ra result <<< $(curl -Is --connect-timeout 5 "${url}" || echo "timeout 500")
# status code is second element of array "result"
status=${result[1]}
# if status code is greater than or equal to 400, then output a bounce message (replace this with any bounce script you like)
[ $status -ge 400  ] && echo "bounce at $url with status $status"

How do I launch a program from command line without opening a new cmd window?

20190907

OS: Win 10

I'm making an exe in c++, for some reason usting START make my program fail.

So, just use quotes:

"c:\folder\program.exe"

How to print to the console in Android Studio?

Run your application in debug mode by clicking on

enter image description here

in the upper menu of Android Studio.

In the bottom status bar, click 5: Debug button, next to the 4: Run button.

Now you should select the Logcat console.

In search box, you can type the tag of your message, and your message should appear, like in the following picture (where the tag is CREATION):

enter image description here

Check this article for more information.

Python data structure sort list alphabetically

ListName.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: ListName.sort(reverse=False)

App.settings - the Angular way?

I find this Angular How-to: Editable Config Files from Microsoft Dev blogs being the best solution. You can configure dev build settings or prod build settings.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

how to execute php code within javascript

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the result class.

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

Debug JavaScript in Eclipse

I tried to get aptana running on my ubuntu 10.4. Unfortunately I didn't succeed. Chrome on the other hand, has an eclipse plugin that lets you debug javascript that's running in a chrome instance. Works very well. YOu'll have to install the eclipse plugin you'll find here:

http://code.google.com/p/chromedevtools/

Set Breakpoints in the javascript sources you edit in eclipse and browser your page in chrome. As soon as a javascript breakpoint is hit, the eclipse debugger halts and lets you step into, step over, browse the variables etc. Very nice!

Understanding checked vs unchecked exceptions in Java

1 . If you are unsure about an exception, check the API:

 java.lang.Object
 extended by java.lang.Throwable
  extended by java.lang.Exception
   extended by java.lang.RuntimeException  //<-NumberFormatException is a RuntimeException  
    extended by java.lang.IllegalArgumentException
     extended by java.lang.NumberFormatException

2 . Yes, and every exception that extends it.

3 . There is no need to catch and throw the same exception. You can show a new File Dialog in this case.

4 . FileNotFoundException is already a checked exception.

5 . If it is expected that the method calling someMethod to catch the exception, the latter can be thrown. It just "passes the ball". An example of it usage would be if you want to throw it in your own private methods, and handle the exception in your public method instead.

A good reading is the Oracle doc itself: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html

Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.

The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

There's also an important bit of information in the Java Language Specification:

The checked exception classes named in the throws clause are part of the contract between the implementor and user of the method or constructor.

The bottom line IMHO is that you can catch any RuntimeException, but you are not required to and, in fact the implementation is not required to maintain the same non-checked exceptions thrown, as those are not part of the contract.

Pipe to/from the clipboard in Bash script

Copy and paste to clipboard in Windows (Cygwin):

See:

$ clip.exe -?

CLIP
Description:
    Redirects output of command line tools to the Windows clipboard.
    This text output can then be pasted into other programs.
Parameter List:
/?                  Displays this help message.
Examples:
DIR | CLIP          Places a copy of the current directory
                        listing into the Windows clipboard.
CLIP < README.TXT   Places a copy of the text from readme.txt
                        on to the Windows clipboard.

Also getclip (it can be used instead of Shift + Ins!) and putclip (echo oaeuoa | putclip.exe to put it into clip) exist.

How do you implement a class in C?

Use a struct to simulate the data members of a class. In terms of method scope you can simulate private methods by placing the private function prototypes in the .c file and the public functions in the .h file.

How exactly does <script defer="defer"> work?

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.

defer works with chrome , firefox , ie > 7 and Safari

ref: https://developer.mozilla.org/en-US/docs/HTML/Element/script

Free Rest API to retrieve current datetime as string (timezone irrelevant)

TimezoneDb provides a free API: http://timezonedb.com/api

GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.

You can use Greenwich, UK if you'd like GMT.

Which MySQL data type to use for storing boolean values

Referring to this link Boolean datatype in Mysql, according to the application usage, if one wants only 0 or 1 to be stored, bit(1) is the better choice.

NSRange to Range<String.Index>

A riff on the great answer by @Emilie, not a replacement/competing answer.
(Xcode6-Beta5)

var original    = "This is a test"
var replacement = "!"

var startIndex = advance(original.startIndex, 1) // Start at the second character
var endIndex   = advance(startIndex, 2) // point ahead two characters
var range      = Range(start:startIndex, end:endIndex)
var final = original.stringByReplacingCharactersInRange(range, withString:replacement)

println("start index: \(startIndex)")
println("end index:   \(endIndex)")
println("range:       \(range)")
println("original:    \(original)")
println("final:       \(final)")

Output:

start index: 4
end index:   7
range:       4..<7
original:    This is a test
final:       !his is a test

Notice the indexes account for multiple code units. The flag (REGIONAL INDICATOR SYMBOL LETTERS ES) is 8 bytes and the (FACE WITH TEARS OF JOY) is 4 bytes. (In this particular case it turns out that the number of bytes is the same for UTF-8, UTF-16 and UTF-32 representations.)

Wrapping it in a func:

func replaceString(#string:String, #with:String, #start:Int, #length:Int) ->String {
    var startIndex = advance(original.startIndex, start) // Start at the second character
    var endIndex   = advance(startIndex, length) // point ahead two characters
    var range      = Range(start:startIndex, end:endIndex)
    var final = original.stringByReplacingCharactersInRange(range, withString: replacement)
    return final
}

var newString = replaceString(string:original, with:replacement, start:1, length:2)
println("newString:\(newString)")

Output:

newString: !his is a test

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

Server Discovery And Monitoring engine is deprecated

mongoose.connect("DBURL", {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true },(err)=>{
    if(!err){
         console.log('MongoDB connection sucess');
        }
    else{ 
        console.log('connection not established :' + JSON.stringify(err,undefined,2));
    }
});

What is an uber jar?

For Java Developers who use SpringBoot, ÜBER/FAT JAR is normally the final result of the package phase of maven (or build task if you use gradle).

Inside the Fat JAR one can find a META-INF directory inside which the MANIFEST.MF file lives with all the info regarding the Main class. More importantly, at the same level of META-INF directory you find the BOOT-INF directory inside which the directory lib lives and contains all the .jar files that are the dependencies of your application.

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I solved this simply:

<div ng-repeat="Object in List | filter: (FilterObj.FilterProperty1 ? {'ObjectProperty1': FilterObj.FilterProperty1} : '') | filter:(FilterObj.FilterProperty2 ? {'ObjectProperty2': FilterObj.FilterProperty2} : '')">

Android Lint contentDescription warning

Non textual widgets need a content description in some ways to describe textually the image so that screens readers to be able to describe the user interface. You can ignore the property xmlns:tools="http://schemas.android.com/tools"
tools:ignore="contentDescription"
or define the property android:contentDescription="your description"

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

OR you can do this

var ObjectId = require('mongoose').Types.ObjectId; var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );

as mentioned here Mongoose's find method with $or condition does not work properly

Git Ignores and Maven targets

It is possible to use patterns in a .gitignore file. See the gitignore man page. The pattern */target/* should ignore any directory named target and anything under it. Or you may try */target/** to ignore everything under target.

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

React-Native: Application has not been registered error

My issue was that in AndroidManifest.xml and MainActivity.java package names were different. So in manifest I had package=com.companyName.appName and in activity package com.appName

How to put a text beside the image?

You need to go throgh these scenario:

How about using display:inline-block?

1) Take one <div/> give it style=display:inline-block make it vertical-align:top and put image inside that div.

2) Take another div and give it also the same style display:inline-block; and put all the labels/divs inside this div.

Here is the prototype of your requirement

JS Fiddle Demo

CodeIgniter Disallowed Key Characters

i saw this error when i was trying to send a form, and in one of the fields' names, i let the word "endereço".

echo form_input(array('class' => 'form-control', 'name' => 'endereco', 'placeholder' => 'Endereço', 'value' => set_value('endereco')));

When i changed 'ç' for 'c', the error was gone.

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

How can I hide a TD tag using inline JavaScript or CSS?

What do you expect to happen in it's place? The table can't reflow to fill the space left - this seems like a recipe for buggy browser responses.

Think about hiding the contents of the td, not the td itself.

insert data into database using servlet and jsp in eclipse

I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.

DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());

finding multiples of a number in Python

For the first ten multiples of 5, say

>>> [5*n for n in range(1,10+1)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Check if number is prime number

This is basically an implementation of a brilliant suggestion made by Eric Lippert somewhere above.

    public static bool isPrime(int number)
    {
        if (number == 1) return false;
        if (number == 2 || number == 3 || number == 5) return true;
        if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0) return false;

        var boundary = (int)Math.Floor(Math.Sqrt(number));

        // You can do less work by observing that at this point, all primes 
        // other than 2 and 3 leave a remainder of either 1 or 5 when divided by 6. 
        // The other possible remainders have been taken care of.
        int i = 6; // start from 6, since others below have been handled.
        while (i <= boundary)
        {
            if (number % (i + 1) == 0 || number % (i + 5) == 0)
                return false;

            i += 6;
        }

        return true;
    }