Programs & Examples On #Bulk operations

How to set an iframe src attribute from a variable in AngularJS

this way i follow and its work for me fine, may it will works for you,

<iframe class="img-responsive" src="{{pdfLoc| trustThisUrl }}" ng-style="{
                height: iframeHeight * 0.75 + 'px'
            }" style="width:100%"></iframe>

here trustThisUrl is just filter,

angular.module("app").filter('trustThisUrl', ["$sce", function ($sce) {
        return function (val) {
            return $sce.trustAsResourceUrl(val);
        };
    }]);

Make git automatically remove trailing whitespace before committing

On Mac OS (or, likely, any BSD), the sed command parameters have to be slightly different. Try this:

#!/bin/sh

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
   against=HEAD
else
   # Initial commit: diff against an empty tree object
   against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -E 's/:[0-9]+:.*//' | uniq` ; do
    # Fix them!
    sed -i '' -E 's/[[:space:]]*$//' "$FILE"
    git add "$FILE"
done

Save this file as .git/hooks/pre-commit -- or look for the one that's already there, and paste the bottom chunk somewhere inside it. And remember to chmod a+x it too.

Or for global use (via Git commit hooks - global settings) you can put it in $GIT_PREFIX/git-core/templates/hooks (where GIT_PREFIX is /usr or /usr/local or /usr/share or /opt/local/share) and run git init inside your existing repos.

According to git help init:

Running git init in an existing repository is safe. It will not overwrite things that are already there. The primary reason for rerunning git init is to pick up newly added templates.

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

mysql delete under safe mode

I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

How to use <DllImport> in VB.NET?

You can also try this

Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer

I always use Declare Function instead of DllImport... Its more simply, its shorter and does the same

xcopy file, rename, suppress "Does xxx specify a file name..." message

Don't use the xcopy, use copy instead, it doesn't have this issue.

xcopy is generally used when performing recursive copies of multiple files/folders, or when you need the verification/prompting features it offers. For single file copies, the copy command works just fine.

Generate a UUID on iOS from Swift

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

How to use an existing database with an Android application

You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

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

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

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.

How do you monitor network traffic on the iPhone?

Depending on what you want to do runnning it via a Proxy is not ideal. A transparent proxy might work ok as long as the packets do not get tampered with.

I am about to reverse the GPS data that gets transferred from the iPhone to the iPad on iOS 4.3.x to get to the the vanilla data the best way to get a clean Network Dump is to use "tcpdump" and/or "pirni" as already suggested.

In this particular case where we want the Tethered data it needs to be as transparent as possible. Obviously you need your phone to be JailBroken for this to work.

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

Multiple ping script in Python

import subprocess
import os
'''
servers.txt contains ip address in following format
192.168.1.1
192.168.1.2
'''
    with open('servers.txt', 'r') as f:
        for ip in f:
            result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2",    ip],stdout=f, stderr=f).wait()
            if result:
                print(ip, "inactive")
            else:
                print(ip, "active")

What is the best way to ensure only one instance of a Bash script is running?

One line ultimate solution:

[ "$(pgrep -fn $0)" -ne "$(pgrep -fo $0)" ] && echo "At least 2 copies of $0 are running"

Android - Set text to TextView

in your activity_main.xml paste this code:

            <TextView
                 android:id="@+id/name"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_alignParentLeft="true"
                 android:layout_alignParentTop="true"
                 android:layout_marginLeft="19dp"
                 android:layout_marginTop="43dp"
                 android:text="@string/name" />

and go to res folder->values->strings.xml paste the below code with the code that already exists:

          <string name="name">Escriba su mensaje y luego seleccione el canal.</string>

the above code means that you have created a textview with id:name(android:id="@+id/name") and assigned that textview to a string with an identifier name(android:text="@string/name") in strings.xml your using that identifier name to assign the text,

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)

How to subtract hours from a date in Oracle so it affects the day also

you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual

How to connect from windows command prompt to mysql command line

The cd in your question is invalid (quoting it here because you've removed it once, and it was there when this answer was posted):

cd CD:\MYSQL\bin\

You can't cd to CD:\ anything, because CD:\ isn't a valid directory in Windows. CD: would indicate a drive, except that drives are restricted to a single letter between A and Z.

If your \MYSQL\BIN is on drive C:, then your commands need to be:

C:\>cd \MYSQL\Bin
C:\MYSQL\Bin>mysql -u root -p admin

If you're not already on C: (which you'll know by looking at the prompt in the cmd window), or your MySQL folder is on another drive (for instance, D:), change to that drive too:

C:\> cd /d D:\MYSQL\Bin
D:\MYSQL\Bin>mysql -u root -p admin

The .exe after mysql is optional, since .exe is an executable extension on Windows. If you type mysql, Windows will automatically look for an executable file with that name and run it if it finds it.

Note that in both my examples of running mysql, there are no = signs. You should just use -p with no password, and wait to be prompted for it instead.

How to reference Microsoft.Office.Interop.Excel dll?

You can also try installing it in Visual Studio via Package Manager.

Run Install-Package Microsoft.Office.Interop.Excel in the Package Console. This will automatically add it as a project reference.

Use is like this:

Using Excel=Microsoft.Office.Interop.Excel;

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

How to get row number from selected rows in Oracle

I think using

select rownum st.Branch 
  from student st 
 where st.name like '%ram%'

is a simple way; you should add single quotes in the LIKE statement. If you use row_number(), you should add over (order by 'sort column' 'asc/desc'), for instance:

select st.branch, row_number() over (order by 'sort column' 'asc/desc')  
  from student st 
 where st.name like '%ram%'

How to decompile an APK or DEX file on Android platform?

Also you can use Android Multitool. You can make minor changes in the app like hiding GUI elements or modifying small part of Logic and rebuild the apk. Its easy to use and decompile/recompile apk and jar files. Here is the Link you can checkout.

Cheers

How to enable NSZombie in Xcode?

In the preferences of your executable add the environment variable NSZombieEnabled and set the value to YES.

Convert number to varchar in SQL with formatting

Use the RIGHT function... e.g.

DECLARE @testnum TINYINT
SET @testnum = 3
PRINT RIGHT('00' + CONVERT(VARCHAR(2), @testnum), 2)

CSS Background Image Not Displaying

I have the same issue. But it works properly for me

background: url(../img/debut_dark.png) repeat

https with WCF error: "Could not find base address that matches scheme https"

I had this exact same problem. Except my solution was to add an "s" to the binding value.

Old: binding="mexHttpBinding"

New: binding="mexHttpsBinding"

web.config snippet:

<services>
    <service behaviorConfiguration="ServiceBehavior" name="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService">
        <endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" 
            contract="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService" />
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
    </service>

Parsing a JSON string in Ruby

That data looks like it is in JSON format.

You can use this JSON implementation for Ruby to extract it.

Comments in Android Layout xml

<!-- comment here -->

ExecuteNonQuery doesn't return results

Whenever you want to execute an SQL statement that shouldn't return a value or a record set, the ExecuteNonQuery should be used.

So if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement. This sounds very nice, but whenever you use the SQL Server 2005 IDE or Visual Studio to create a stored procedure it adds a small line that ruins everything.

That line is: SET NOCOUNT ON; This line turns on the NOCOUNT feature of SQL Server, which "Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results" and therefore it makes the stored procedure always to return -1 when called from the application (in my case a web application).

In conclusion, remove that line from your stored procedure, and you will now get a value indicating the number of rows affected by the statement.

Happy programming!

http://aspsoft.blogs.com/jonas/2006/10/executenonquery.html

Compile Views in ASP.NET MVC

Build > Run Code Analysis

Hotkey : Alt+F11

Helped me catch Razor errors.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Applying styles to tables with Twitter Bootstrap

Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.

enter image description here You can use :

basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables

Striped rows Table :

    <table class="table table-striped" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Name</th>
    <th>Address</th>
    <th>mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    </tbody>
    </table>

Condensed table :

Compacting a table you need to add class class=”table table-condensed” .

    <table class="table table-condensed" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Sample Name</th>
    <th>Address</th>
    <th>Mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    <tr>
    <td></td>
    <td colspan="3" align="center"></td>
    </tr>
    </tbody>
    </table>

Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial

Launch Bootstrap Modal on page load

In order to avoid bootstrap being overruled and loosing it´s funcionality, simply create a regular launch button, provide it with an Id, and 'click it' using jquery, like so: The launch button:

<button type="button" id="btnAnouncement" class="btn btn-primary" data-toggle="modal" data-target="#modalAnouncement">
  See what´s new!
</button>

The jQuery trigger:

$(document).ready(function () {
  $('#btnAnouncement').click();
)}

Hope it helps. Cheers!

How to disable the parent form when a child form is active?

What you could do, is to make sure to pass the parent form as the owner when showing the child form:

  Form newForm = new ChildForm();
  newForm.Show(this);

Then, in the child form, set up event handlers for the Activated and Deactivate events:

private void Form_Activated(object sender, System.EventArgs e)
{
    if (this.Owner != null)
    {
        this.Owner.Enabled = false; 
    }
}

private void Form_Deactivate(object sender, System.EventArgs e)
{
    if (this.Owner != null)
    {
        this.Owner.Enabled = true;
    }
}

However, this will result in a truly wierd behaviour; while you will not be able to go back and interact with the parent form immediately, activating any other application will enable it, and then the user can interact with it.

If you want to make the child form modal, use ShowDialog instead:

  Form newForm = new ChildForm();
  newForm.ShowDialog(this);

How to read if a checkbox is checked in PHP?

in BS3 you can put

  <?php
                  $checked="hola";
                  $exenta = $datosOrdenCompra[0]['exenta'];
                  var_dump($datosOrdenCompra[0]['exenta']);
                  if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){

                      $checked="on";

                  }else{
                    $checked="off";
                  }

              ?>
              <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>

Please Note the usage of isset($datosOrdenCompra[0]['exenta'])

RegEx for matching UK Postcodes

There is no such thing as a comprehensive UK postcode regular expression that is capable of validating a postcode. You can check that a postcode is in the correct format using a regular expression; not that it actually exists.

Postcodes are arbitrarily complex and constantly changing. For instance, the outcode W1 does not, and may never, have every number between 1 and 99, for every postcode area.

You can't expect what is there currently to be true forever. As an example, in 1990, the Post Office decided that Aberdeen was getting a bit crowded. They added a 0 to the end of AB1-5 making it AB10-50 and then created a number of postcodes in between these.

Whenever a new street is build a new postcode is created. It's part of the process for obtaining permission to build; local authorities are obliged to keep this updated with the Post Office (not that they all do).

Furthermore, as noted by a number of other users, there's the special postcodes such as Girobank, GIR 0AA, and the one for letters to Santa, SAN TA1 - you probably don't want to post anything there but it doesn't appear to be covered by any other answer.

Then, there's the BFPO postcodes, which are now changing to a more standard format. Both formats are going to be valid. Lastly, there's the overseas territories source Wikipedia.

+----------+----------------------------------------------+
| Postcode |                   Location                   |
+----------+----------------------------------------------+
| AI-2640  | Anguilla                                     |
| ASCN 1ZZ | Ascension Island                             |
| STHL 1ZZ | Saint Helena                                 |
| TDCU 1ZZ | Tristan da Cunha                             |
| BBND 1ZZ | British Indian Ocean Territory               |
| BIQQ 1ZZ | British Antarctic Territory                  |
| FIQQ 1ZZ | Falkland Islands                             |
| GX11 1AA | Gibraltar                                    |
| PCRN 1ZZ | Pitcairn Islands                             |
| SIQQ 1ZZ | South Georgia and the South Sandwich Islands |
| TKCA 1ZZ | Turks and Caicos Islands                     |
+----------+----------------------------------------------+

Next, you have to take into account that the UK "exported" its postcode system to many places in the world. Anything that validates a "UK" postcode will also validate the postcodes of a number of other countries.

If you want to validate a UK postcode the safest way to do it is to use a look-up of current postcodes. There are a number of options:

  • Ordnance Survey releases Code-Point Open under an open data licence. It'll be very slightly behind the times but it's free. This will (probably - I can't remember) not include Northern Irish data as the Ordnance Survey has no remit there. Mapping in Northern Ireland is conducted by the Ordnance Survey of Northern Ireland and they have their, separate, paid-for, Pointer product. You could use this and append the few that aren't covered fairly easily.

  • Royal Mail releases the Postcode Address File (PAF), this includes BFPO which I'm not sure Code-Point Open does. It's updated regularly but costs money (and they can be downright mean about it sometimes). PAF includes the full address rather than just postcodes and comes with its own Programmers Guide. The Open Data User Group (ODUG) is currently lobbying to have PAF released for free, here's a description of their position.

  • Lastly, there's AddressBase. This is a collaboration between Ordnance Survey, Local Authorities, Royal Mail and a matching company to create a definitive directory of all information about all UK addresses (they've been fairly successful as well). It's paid-for but if you're working with a Local Authority, government department, or government service it's free for them to use. There's a lot more information than just postcodes included.

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Rebase array keys after unsetting elements

Got another interesting method:

$array = array('a', 'b', 'c', 'd'); 
unset($array[2]); 

$array = array_merge($array); 

Now the $array keys are reset.

change the date format in laravel view page

You can use Carbon::createFromTimestamp

BLADE

{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}

Service has zero application (non-infrastructure) endpoints

I had the same problem. Everything works in VS2010 but when I run the same project in VS2008 I get the mentioned exception.

What I did in my VS2008 project to make it work was adding a call to the AddServiceEndpoint member of my ServiceHost object.

Here is my code snippet:

Uri baseAddress = new Uri("http://localhost:8195/v2/SystemCallbackListener");

ServiceHost host = new ServiceHost(typeof(SystemCallbackListenerImpl), baseAddress);

host.AddServiceEndpoint(typeof(CsfServiceReference.SystemCallbackListener),
                        new BasicHttpBinding(),
                        baseAddress);
host.Open();

I didn't modify the app.config file. But I guess the service endpoint could also have been added in the .config file.

pip install returning invalid syntax

You can also go into the directory where you have your pip.exe or pip3.exe located. For me it was on my D drive so here is what I did:

D:\>cd python

D:\python>cd Scripts

D:\python\Scripts>pip3.exe install tweepy

Hope it helps

Pseudo-terminal will not be allocated because stdin is not a terminal

Try ssh -t -t(or ssh -tt for short) to force pseudo-tty allocation even if stdin isn't a terminal.

See also: Terminating SSH session executed by bash script

From ssh manpage:

-T      Disable pseudo-tty allocation.

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary 
        screen-based programs on a remote machine, which can be very useful,
        e.g. when implementing menu services.  Multiple -t options force tty
        allocation, even if ssh has no local tty.

How can I find the version of the Fedora I use?

The proposed standard file is /etc/os-release. See http://www.freedesktop.org/software/systemd/man/os-release.html

You can execute something like:

$ source /etc/os-release
$ echo $ID
fedora
$ echo $VERSION_ID
17
$ echo $VERSION
17 (Beefy Miracle)

Viewing all defined variables

A few things you could use:

  • dir() will give you the list of in scope variables:
  • globals() will give you a dictionary of global variables
  • locals() will give you a dictionary of local variables

How to solve java.lang.NullPointerException error?

This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.

How does strtok() split the string into tokens in C?

strtok modifies its input string. It places null characters ('\0') in it so that it will return bits of the original string as tokens. In fact strtok does not allocate memory. You may understand it better if you draw the string as a sequence of boxes.

View JSON file in Browser

In Chrome use JSONView or Firefox use JSONView

Where does PHP's error log reside in XAMPP?

\xampp\php\logs did not exist at all for me - for whatever reason.

I simply had to create a folder in \xampp\php\ called logs and then the php_error_log file was created and written to.

Java Code for calculating Leap Year

With the course of : TestMyCode Programming assignment evaluator, that one of the exercises was this kind of issue, I wrote this answer:

import java.util.Scanner;

public class LeapYear {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Type a year: ");

        int year = Integer.parseInt(reader.nextLine());

        if (year % 400 == 0 && year % 100 == 0 && year % 4 == 0) {
            System.out.println("The year is a leap year");
        } else
         if (year % 4 == 0 && year%100!=0 ) {
            System.out.println("The year is a leap year");
        } else 
        {
            System.out.println("The year is not a leap year");
        }

    }
}

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Mysql: Select rows from a table that are not in another

This worked for me in Oracle:

SELECT a.* 
    FROM tbl1 a 
MINUS 
SELECT b.* 
    FROM tbl2 b;

Data truncated for column?

Your problem is that at the moment your incoming_Cid column defined as CHAR(1) when it should be CHAR(34).

To fix this just issue this command to change your columns' length from 1 to 34

ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);

Here is SQLFiddle demo

How to find out what is locking my tables?

A colleague and I have created a tool just for this. It's a visual representation of all the locks that your sessions produce. Give it a try (http://www.sqllockfinder.com), it's open source (https://github.com/LucBos/SqlLockFinder)

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

How to execute a file within the python interpreter?

Surprised I haven't seen this yet. You can execute a file and then leave the interpreter open after execution terminates using the -i option:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

How to handle the modal closing event in Twitter Bootstrap?

If your modal div is dynamically added then use( For bootstrap 3 and 4)

$(document).on('hide.bs.modal','#modal-id', function () {
                alert('');
 //Do stuff here
});

This will work for non-dynamic content also.

How can I save an image with PIL?

Try removing the . before the .bmp (it isn't matching BMP as expected). As you can see from the error, the save_handler is upper-casing the format you provided and then looking for a match in SAVE. However the corresponding key in that object is BMP (instead of .BMP).

I don't know a great deal about PIL, but from some quick searching around it seems that it is a problem with the mode of the image. Changing the definition of j to:

j = Image.fromarray(b, mode='RGB')

Seemed to work for me (however note that I have very little knowledge of PIL, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode, I used this page - hopefully one of the choices there will work for you.

Add alternating row color to SQL Server Reporting services report

I tried all these solutions on a Grouped Tablix with row spaces and none worked across the entire report. The result was duplicate colored rows and other solutions resulted in alternating columns!

Here is the function I wrote that worked for me using a Column Count:

Private bOddRow As Boolean
Private cellCount as Integer

Function AlternateColorByColumnCount(ByVal OddColor As String, ByVal EvenColor As String, ByVal ColCount As Integer) As String

if cellCount = ColCount Then 
bOddRow = Not bOddRow
cellCount = 0
End if 

cellCount  = cellCount  + 1

if bOddRow Then
 Return OddColor
Else
 Return EvenColor
End If

End Function

For a 7 Column Tablix I use this expression for Row (of Cells) Backcolour:

=Code.AlternateColorByColumnCount("LightGrey","White", 7)

Anaconda version with Python 3.5

According to the official docu it's recommended to downgrade the whole Python environment:

conda install python=3.5

Predicate in Java

I'm assuming you're talking about com.google.common.base.Predicate<T> from Guava.

From the API:

Determines a true or false value for a given input. For example, a RegexPredicate might implement Predicate<String>, and return true for any string that matches its given regular expression.

This is essentially an OOP abstraction for a boolean test.

For example, you may have a helper method like this:

static boolean isEven(int num) {
   return (num % 2) == 0; // simple
}

Now, given a List<Integer>, you can process only the even numbers like this:

    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    for (int number : numbers) {
        if (isEven(number)) {
            process(number);
        }
    }

With Predicate, the if test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables, which have many utility methods that takes Predicate.

Thus, you can now write something like this:

    Predicate<Integer> isEven = new Predicate<Integer>() {
        @Override public boolean apply(Integer number) {
            return (number % 2) == 0;
        }               
    };
    Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);

    for (int number : evenNumbers) {
        process(number);
    }

Note that now the for-each loop is much simpler without the if test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers, by filter-ing using a Predicate.

API links


On higher-order function

Predicate allows Iterables.filter to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers example above. Suppose we want to test if all numbers are positive. We can write something like this:

static boolean isAllPositive(Iterable<Integer> numbers) {
    for (Integer number : numbers) {
        if (number < 0) {
            return false;
        }
    }
    return true;
}

//...
if (isAllPositive(numbers)) {
    System.out.println("Yep!");
}

With a Predicate, and interoperating with the rest of the libraries, we can instead write this:

Predicate<Integer> isPositive = new Predicate<Integer>() {
    @Override public boolean apply(Integer number) {
        return number > 0;
    }       
};

//...
if (Iterables.all(numbers, isPositive)) {
    System.out.println("Yep!");
}

Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.

Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter and Iterables.all. You can, of course, pass around objects in Java. Thus, the Predicate type is defined, and you pass objects implementing this interface instead.

See also

MongoDB query multiple collections at once

Here is answer for your question.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$project : {
            posts : { $filter : {input : "$posts"  , as : "post", cond : { $eq : ['$$post.via' , 'facebook'] } } },
            admin : 1

        }}

])

Or either you can go with mongodb group option.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$unwind : "$posts"},
    {$match : {"posts.via":"facebook"}},
    { $group : {
            _id : "$_id",
            posts : {$push : "$posts"}
    }}
])

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

How to escape % in String.Format?

To complement the previous stated solution, use:

str = str.replace("%", "%%");

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

Converting URL to String and back again

Swift 3 used with UIWebViewDelegate shouldStartLoadWith

  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let urlPath: String = (request.url?.absoluteString)!
    print(urlPath)
    if urlPath.characters.last == "#" {
        return false
    }else{
        return true
    }

}

Rails update_attributes without save?

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Do something if screen width is less than 960 px

nope, none of this will work. What you need is this!!!

Try this:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}

Clearing an input text field in Angular2

Template driven method

#receiverInput="ngModel" (blur)="receiverInput.control.setValue('')"

Update MongoDB field using value of another field

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:

// { firstName: "Hello", lastName: "World" }
db.collection.update(
  {},
  [{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
  { multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
  • The first part {} is the match query, filtering which documents to update (in our case all documents).

  • The second part [{ $set: { name: { ... } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields.

  • Don't forget { multi: true }, otherwise only the first matching document will be updated.

pip3: command not found

You would need to install pip3.

On Linux, the command would be: sudo apt install python3-pip

On Mac, using brew, first brew install python3
Then brew postinstall python3

Try calling pip3 -V to see if it worked.

How to completely DISABLE any MOUSE CLICK

The easiest way to freeze the UI would be to make the AJAX call synchronous.

Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.

Get Last Part of URL PHP

A fail safe solution would be:

Referenced from https://stackoverflow.com/a/2273328/2062851

function getLastPathSegment($url) {
    $path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
    $pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
    $pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash

    if (substr($path, -1) !== '/') {
        array_pop($pathTokens);
    }
    return end($pathTokens); // get the last segment
}

echo getLastPathSegment($_SERVER['REQUEST_URI']); //9393903

Visual Studio Code: format is not using indent settings

Visual Studio Code detects the current indentation per default and uses this - ignoring the .editorconfig

Set also "editor.detectIndentation" to false

(Files -> Preferences -> Settings)

screenshot

How to know user has clicked "X" or the "Close" button?

I also had to register the closing function inside the form's "InitializeComponent()" method:

private void InitializeComponent() {
// ...
this.FormClosing += FrmMain_FormClosing;
// ...
}

My "FormClosing" function looks similar to the given answer (https://stackoverflow.com/a/2683846/3323790):

private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {
    if (e.CloseReason == CloseReason.UserClosing){
        MessageBox.Show("Closed by User", "UserClosing");
    }

    if (e.CloseReason == CloseReason.WindowsShutDown){
        MessageBox.Show("Closed by Windows shutdown", "WindowsShutDown");
    }
}

One more thing to mention: There is also a "FormClosed" function which occurs after "FormClosing". To use this function, register it as shown below:

this.FormClosed += MainPage_FormClosed;

private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
{
// your code after the form is closed
}

Are HTTP cookies port specific?

In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.

I've posted this answer so that readers will have at least one concrete option for testing each scenario.

Padding zeros to the left in postgreSQL

You can use the rpad and lpad functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char or ::text to cast them:

SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
       LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM   my_table

ios simulator: how to close an app

For closing (not quit) the running application in Simulator the keyboard shortcut is "shift+command+h".

Why isn't textarea an input[type="textarea"]?

Maybe this is going a bit too far back but…

Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.

Marc Andreessen, 11 October 1993

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

What's a good IDE for Python on Mac OS X?

I usually use either komodo edit or aquamacs with ropemacs. Although I should warn you, IDE features won't be what you're used to if you're coming from a Java or C# background. I personally find that powerful IDEs get in my way more than they help.

UPDATE: I should also point out that if you have the money Komodo IDE is worth it. It's the paid version of Komodo Edit.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I was having the same problem. When I initially created the java project in Eclipse I specified JRE 8. When I went into the project's build path and edited the JRE System Library, the Java 8 execution environment was selected. When I chose to use an "Alernate JRE" (still java 8) it fixed the error for me.

How can a add a row to a data frame in R?

There is a simpler way to append a record from one dataframe to another IF you know that the two dataframes share the same columns and types. To append one row from xx to yy just do the following where i is the i'th row in xx.

yy[nrow(yy)+1,] <- xx[i,]

Simple as that. No messy binds. If you need to append all of xx to yy, then either call a loop or take advantage of R's sequence abilities and do this:

zz[(nrow(zz)+1):(nrow(zz)+nrow(yy)),] <- yy[1:nrow(yy),]

Safely casting long to int in Java

With Google Guava's Ints class, your method can be changed to:

public static int safeLongToInt(long l) {
    return Ints.checkedCast(l);
}

From the linked docs:

checkedCast

public static int checkedCast(long value)

Returns the int value that is equal to value, if possible.

Parameters: value - any value in the range of the int type

Returns: the int value that equals value

Throws: IllegalArgumentException - if value is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE

Incidentally, you don't need the safeLongToInt wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

This work for me:

 $('#data_compra').daterangepicker({
          singleDatePicker: true,
          locale: {
           format: 'DD/MM/YYYY'
          },
         calender_style: "picker_4", }, 
function(start, end, label) {
          console.log(start.toISOString(), end.toISOString(), label); 
});

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

How can I disable the bootstrap hover color for links?

I am not a Bootstrap expert, but it sounds to me that you should define a new class called nohover (or something equivalent) then in your link code add the class as the last attribute value:

<a class="green nohover" href="#">green text</a>
<a class="yellow nohover" href="#">yellow text</a>

Then in your Bootstrap LESS/CSS file, define nohover (using the JSFiddle example above):

a:hover { color: red  }
/* Green */
a.green  { color: green; }
/* Yellow */
a.yellow  { color: yellow; }
a.nohover:hover { color: none;  }

Forked the JSFiddle here: http://jsfiddle.net/9rpkq/

Adding an .env file to React Project

  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
process.env.REACT_APP_BASE_URL

How to get the process ID to kill a nohup process?

You could try

kill -9 `pgrep [command name]`

Changing datagridview cell color dynamically

Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:

class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
        DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
    {
        if (value != null)
        {
            if ((bool) value)
            {
                cellStyle.BackColor = Color.LightGreen;
            }
            else
            {
                cellStyle.BackColor = Color.OrangeRed;
            }
        }
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}

}

Then in the code set CellTemplate property of your column to instance of your class

columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});

How can I color dots in a xy scatterplot according to column value?

I answered a very similar question:

https://stackoverflow.com/a/15982217/1467082

You simply need to iterate over the series' .Points collection, and then you can assign the points' .Format.Fill.ForeColor.RGB value based on whatever criteria you need.

UPDATED

The code below will color the chart per the screenshot. This only assumes three colors are used. You can add additional case statements for other color values, and update the assignment of myColor to the appropriate RGB values for each.

screenshot

Option Explicit
Sub ColorScatterPoints()
    Dim cht As Chart
    Dim srs As Series
    Dim pt As Point
    Dim p As Long
    Dim Vals$, lTrim#, rTrim#
    Dim valRange As Range, cl As Range
    Dim myColor As Long

    Set cht = ActiveSheet.ChartObjects(1).Chart
    Set srs = cht.SeriesCollection(1)

   '## Get the series Y-Values range address:
    lTrim = InStrRev(srs.Formula, ",", InStrRev(srs.Formula, ",") - 1, vbBinaryCompare) + 1
    rTrim = InStrRev(srs.Formula, ",")
    Vals = Mid(srs.Formula, lTrim, rTrim - lTrim)
    Set valRange = Range(Vals)

    For p = 1 To srs.Points.Count
        Set pt = srs.Points(p)
        Set cl = valRange(p).Offset(0, 1) '## assume color is in the next column.

        With pt.Format.Fill
            .Visible = msoTrue
            '.Solid  'I commented this out, but you can un-comment and it should still work
            '## Assign Long color value based on the cell value
            '## Add additional cases as needed.
            Select Case LCase(cl)
                Case "red"
                    myColor = RGB(255, 0, 0)
                Case "orange"
                    myColor = RGB(255, 192, 0)
                Case "green"
                    myColor = RGB(0, 255, 0)
            End Select

            .ForeColor.RGB = myColor

        End With
    Next


End Sub

What are these ^M's that keep showing up in my files in emacs?

^M is 0x0d, i.e. the carriage return character. If your display looks like

line 1^M
line 2^M

then the file must have come from Windows because the standard newline sequence on Windows is CR LF (0x0d 0x0a) whereas the standard newline sequence consists solely of LF on Unices.

If the file had come from a Mac OS 9 or earlier system, you would see it as

line 1^Mline 2^M

because there would be no line feeds following the carriage returns.

How to print a debug log?

You can use the php curl module to make calls to http://liveoutput.com/. This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents.

How to get the cell value by column name not by index in GridView in asp.net

It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:

e.g. For a string:

Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()

e.g. For an integer:

Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())

How to find out the MySQL root password

This worked for me:

On terminal type the following

$ sudo mysql -u root -p

Enter password://just press enter

mysql>

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

C# Linq Where Date Between 2 Dates

If someone interested to know how to work with 2 list and between dates

var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

Echo equivalent in PowerShell for script testing

By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:

$filesizecounter = 8096
"filesizecounter : $filesizecounter"

Of course, you do give up some flexibility when not using the Write-* methods.

PHP: How do I display the contents of a textfile on my page?

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Try this to open a file in php

Refer this: (http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)

PHP - Check if two arrays are equal

!=== will not work because it's a syntax error. The correct way is !== (not three "equal to" symbols)

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

PostgreSQL: How to change PostgreSQL user password?

Then type:

$ sudo -u postgres psql

Then:

\password postgres

Then to quit psql:

\q

If that does not work, reconfigure authentication.

Edit /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:

    local   all             all                                     peer

to:

    local   all             all                                     md5

Then restart the server:

$ sudo service postgresql restart

How do I make Visual Studio pause after executing a console application in debug mode?

It would actually be more effort, but you could just build in VS.Net, run it from the regular command line (cmd.exe), and then attach to the process after it starts running. This is probably not the solution you are looking for however.

How do I draw a circle in iOS Swift?

Make a class UIView and assign it this code for a simple circle

import UIKit
@IBDesignable
class DRAW: UIView {

    override func draw(_ rect: CGRect) {

        var path = UIBezierPath()
        path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100))
        UIColor.yellow.setStroke()
        UIColor.red.setFill()
        path.lineWidth = 5
        path.stroke()
        path.fill()


    }


}

What to do with "Unexpected indent" in python?

It depends in the context. Another scenario which wasn't yet covered is the following. Let's say you have one file with a class with a specific method in it

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        pass

and in the bottom of the file you have something like

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

making it the whole file look like this

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        pass

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

If in scrape_html() you open up, for example, an if/else statement

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        if condition:
            pass
        else:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

You'll need to add pass or whatever you want to to that else statement or else you'll get

Expected indented block

enter image description here

Unindent not expected

enter image description here

Expected expression

enter image description here

and in the first row

Unexpected indentation

enter image description here

Adding that pass would fix all of these four problems.

How to replace an entire line in a text file by line number

Not the greatest, but this should work:

sed -i 'Ns/.*/replacement-line/' file.txt

where N should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i option:

sed 'Ns/.*/replacement-line/' file.txt > new_file.txt

Redirecting to a relative URL in JavaScript

I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:

location.href='/otherSection'

How do I set default value of select box in angularjs

You can simple use ng-init like this

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

Convert comma separated string to array in PL/SQL

Yes, it is very frustrating that dbms_utility.comma_to_table only supports comma delimieted lists and then only when elements in the list are valid PL/SQL identifies (so numbers cause an error).

I have created a generic parsing package that will do what you need (pasted below). It is part of my "demo.zip" file, a repository of over 2000 files that support my training materials, all available at PL/SQL Obsession: www.toadworld.com/SF.

Regards, Steven Feuerstein www.plsqlchallenge.com (daily PL/SQL quiz)

    CREATE OR REPLACE PACKAGE parse
/*
   Generalized delimited string parsing package

   Author: Steven Feuerstein, [email protected]

   Latest version always available on PL/SQL Obsession: 

   www.ToadWorld.com/SF

   Click on "Trainings, Seminars and Presentations" and
   then download the demo.zip file.

   Modification History
      Date          Change
      10-APR-2009   Add support for nested list variations

   Notes:
     * This package does not validate correct use of delimiters.
       It assumes valid construction of lists.
     * Import the Q##PARSE.qut file into an installation of 
       Quest Code Tester 1.8.3 or higher in order to run
       the regression test for this package.

*/
IS
   SUBTYPE maxvarchar2_t IS VARCHAR2 (32767);

   /*
   Each of the collection types below correspond to (are returned by)
   one of the parse functions.

   items_tt - a simple list of strings
   nested_items_tt - a list of lists of strings
   named_nested_items_tt - a list of named lists of strings

   This last type also demonstrates the power and elegance of string-indexed
   collections. The name of the list of elements is the index value for
   the "outer" collection.
   */
   TYPE items_tt IS TABLE OF maxvarchar2_t
                       INDEX BY PLS_INTEGER;

   TYPE nested_items_tt IS TABLE OF items_tt
                              INDEX BY PLS_INTEGER;

   TYPE named_nested_items_tt IS TABLE OF items_tt
                                    INDEX BY maxvarchar2_t;

   /*
   Parse lists with a single delimiter.
   Example: a,b,c,d

   Here is an example of using this function:

   DECLARE
      l_list parse.items_tt;
   BEGIN
      l_list := parse.string_to_list ('a,b,c,d', ',');
   END;
   */
   FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
      RETURN items_tt;

   /*
   Parse lists with nested delimiters.
   Example: a,b,c,d|1,2,3|x,y,z

   Here is an example of using this function:

   DECLARE
      l_list parse.nested_items_tt;
   BEGIN
      l_list := parse.string_to_list ('a,b,c,d|1,2,3,4', '|', ',');
   END;
   */
   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN nested_items_tt;

   /*
   Parse named lists with nested delimiters.
   Example: letters:a,b,c,d|numbers:1,2,3|names:steven,george

   Here is an example of using this function:

   DECLARE
      l_list parse.named_nested_items_tt;
   BEGIN
   l_list := parse.string_to_list ('letters:a,b,c,d|numbers:1,2,3,4', '|', ':', ',');
   END;
   */
   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , name_delim_in  IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN named_nested_items_tt;

   PROCEDURE display_list (string_in IN VARCHAR2
                         , delim_in  IN VARCHAR2:= ','
                          );

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          );

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , name_delim_in  IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          );

   PROCEDURE show_variations;

   /* Helper function for automated testing */
   FUNCTION nested_eq (list1_in    IN items_tt
                     , list2_in    IN items_tt
                     , nulls_eq_in IN BOOLEAN
                      )
      RETURN BOOLEAN;

END parse;
/

CREATE OR REPLACE PACKAGE BODY parse
IS
   FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
      RETURN items_tt
   IS
      c_end_of_list   CONSTANT PLS_INTEGER := -99;
      l_item          maxvarchar2_t;
      l_startloc      PLS_INTEGER := 1;
      items_out       items_tt;

      PROCEDURE add_item (item_in IN VARCHAR2)
      IS
      BEGIN
         IF item_in = delim_in
         THEN
            /* We don't put delimiters into the collection. */
            NULL;
         ELSE
            items_out (items_out.COUNT + 1) := item_in;
         END IF;
      END;

      PROCEDURE get_next_item (string_in         IN     VARCHAR2
                             , start_location_io IN OUT PLS_INTEGER
                             , item_out             OUT VARCHAR2
                              )
      IS
         l_loc   PLS_INTEGER;
      BEGIN
         l_loc := INSTR (string_in, delim_in, start_location_io);

         IF l_loc = start_location_io
         THEN
            /* A null item (two consecutive delimiters) */
            item_out := NULL;
         ELSIF l_loc = 0
         THEN
            /* We are at the last item in the list. */
            item_out := SUBSTR (string_in, start_location_io);
         ELSE
            /* Extract the element between the two positions. */
            item_out :=
               SUBSTR (string_in
                     , start_location_io
                     , l_loc - start_location_io
                      );
         END IF;

         IF l_loc = 0
         THEN
            /* If the delimiter was not found, send back indication
               that we are at the end of the list. */

            start_location_io := c_end_of_list;
         ELSE
            /* Move the starting point for the INSTR search forward. */
            start_location_io := l_loc + 1;
         END IF;
      END get_next_item;
   BEGIN
      IF string_in IS NULL OR delim_in IS NULL
      THEN
         /* Nothing to do except pass back the empty collection. */
         NULL;
      ELSE
         LOOP
            get_next_item (string_in, l_startloc, l_item);
            add_item (l_item);
            EXIT WHEN l_startloc = c_end_of_list;
         END LOOP;
      END IF;

      RETURN items_out;
   END string_to_list;

   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN nested_items_tt
   IS
      l_elements   items_tt;
      l_return     nested_items_tt;
   BEGIN
      /* Separate out the different lists. */
      l_elements := string_to_list (string_in, outer_delim_in);

      /* For each list, parse out the separate items
         and add them to the end of the list of items
         for that list. */   
      FOR indx IN 1 .. l_elements.COUNT
      LOOP
         l_return (l_return.COUNT + 1) :=
            string_to_list (l_elements (indx), inner_delim_in);
      END LOOP;

      RETURN l_return;
   END string_to_list;

   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , name_delim_in  IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN named_nested_items_tt
   IS
      c_name_position constant pls_integer := 1;
      c_items_position constant pls_integer := 2;
      l_elements          items_tt;
      l_name_and_values   items_tt;
      l_return            named_nested_items_tt;
   BEGIN
      /* Separate out the different lists. */
      l_elements := string_to_list (string_in, outer_delim_in);

      FOR indx IN 1 .. l_elements.COUNT
      LOOP
         /* Extract the name and the list of items that go with 
            the name. This collection always has just two elements:
              index 1 - the name
              index 2 - the list of values
         */
         l_name_and_values :=
            string_to_list (l_elements (indx), name_delim_in);
         /*
         Use the name as the index value for this list.
         */
         l_return (l_name_and_values (c_name_position)) :=
            string_to_list (l_name_and_values (c_items_position), inner_delim_in);
      END LOOP;

      RETURN l_return;
   END string_to_list;

   PROCEDURE display_list (string_in IN VARCHAR2
                         , delim_in  IN VARCHAR2:= ','
                          )
   IS
      l_items   items_tt;
   BEGIN
      DBMS_OUTPUT.put_line (
         'Parse "' || string_in || '" using "' || delim_in || '"'
      );

      l_items := string_to_list (string_in, delim_in);

      FOR indx IN 1 .. l_items.COUNT
      LOOP
         DBMS_OUTPUT.put_line ('> ' || indx || ' = ' || l_items (indx));
      END LOOP;
   END display_list;

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          )
   IS
      l_items   nested_items_tt;
   BEGIN
      DBMS_OUTPUT.put_line(   'Parse "'
                           || string_in
                           || '" using "'
                           || outer_delim_in
                           || '-'
                           || inner_delim_in
                           || '"');
      l_items := string_to_list (string_in, outer_delim_in, inner_delim_in);


      FOR outer_index IN 1 .. l_items.COUNT
      LOOP
         DBMS_OUTPUT.put_line(   'List '
                              || outer_index
                              || ' contains '
                              || l_items (outer_index).COUNT
                              || ' elements');

         FOR inner_index IN 1 .. l_items (outer_index).COUNT
         LOOP
            DBMS_OUTPUT.put_line(   '> Value '
                                 || inner_index
                                 || ' = '
                                 || l_items (outer_index) (inner_index));
         END LOOP;
      END LOOP;
   END display_list;

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , name_delim_in  IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          )
   IS
      l_items   named_nested_items_tt;
      l_index   maxvarchar2_t;
   BEGIN
      DBMS_OUTPUT.put_line(   'Parse "'
                           || string_in
                           || '" using "'
                           || outer_delim_in
                           || '-'
                           || name_delim_in
                           || '-'
                           || inner_delim_in
                           || '"');
      l_items :=
         string_to_list (string_in
                       , outer_delim_in
                       , name_delim_in
                       , inner_delim_in
                        );

      l_index := l_items.FIRST;

      WHILE (l_index IS NOT NULL)
      LOOP
         DBMS_OUTPUT.put_line(   'List "'
                              || l_index
                              || '" contains '
                              || l_items (l_index).COUNT
                              || ' elements');

         FOR inner_index IN 1 .. l_items (l_index).COUNT
         LOOP
            DBMS_OUTPUT.put_line(   '> Value '
                                 || inner_index
                                 || ' = '
                                 || l_items (l_index) (inner_index));
         END LOOP;

         l_index := l_items.NEXT (l_index);
      END LOOP;
   END display_list;

   PROCEDURE show_variations
   IS
      PROCEDURE show_header (title_in IN VARCHAR2)
      IS
      BEGIN
         DBMS_OUTPUT.put_line (RPAD ('=', 60, '='));
         DBMS_OUTPUT.put_line (title_in);
         DBMS_OUTPUT.put_line (RPAD ('=', 60, '='));
      END show_header;
   BEGIN
      show_header ('Single Delimiter Lists');
      display_list ('a,b,c');
      display_list ('a;b;c', ';');
      display_list ('a,,b,c');
      display_list (',,b,c,,');

      show_header ('Nested Lists');
      display_list ('a,b,c,d|1,2,3|x,y,z', '|', ',');

      show_header ('Named, Nested Lists');
      display_list ('letters:a,b,c,d|numbers:1,2,3|names:steven,george'
                  , '|'
                  , ':'
                  , ','
                   );
   END;

   FUNCTION nested_eq (list1_in    IN items_tt
                     , list2_in    IN items_tt
                     , nulls_eq_in IN BOOLEAN
                      )
      RETURN BOOLEAN
   IS
      l_return   BOOLEAN := list1_in.COUNT = list2_in.COUNT;
      l_index    PLS_INTEGER := 1;
   BEGIN
      WHILE (l_return AND l_index IS NOT NULL)
      LOOP
         l_return := list1_in (l_index) = list2_in (l_index);
         l_index := list1_in.NEXT (l_index);
      END LOOP;

      RETURN l_return;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         RETURN FALSE;
   END nested_eq;
END;
/

jQuery override default validation error message display (Css) Popup/Tooltip like

If you could provide some reason as to why you need to replace the label with a div, that would certainly help...

Also, could you paste a sample that'd be helpful ( http://dpaste.com/ or http://pastebin.com/)

Javascript use variable as object name

When using the window[objname], please make sure the objname is global variables. Otherwise, will work sometime, and fail sometimes. window[objname].value.

The difference in months between dates in MySQL

As many of the answers here show, the 'right' answer depends on exactly what you need. In my case, I need to round to the closest whole number.

Consider these examples: 1st January -> 31st January: It's 0 whole months, and almost 1 month long. 1st January -> 1st February? It's 1 whole month, and exactly 1 month long.

To get the number of whole (complete) months, use:

SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-01-31');  => 0
SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-02-01');  => 1

To get a rounded duration in months, you could use:

SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1
SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1

This is accurate to +/- 5 days and for ranges over 1000 years. Zane's answer is obviously more accurate, but it's too verbose for my liking.

How do I calculate r-squared using Python and Numpy?

A very late reply, but just in case someone needs a ready function for this:

scipy.stats.linregress

i.e.

slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)

as in @Adam Marples's answer.

How can I control the width of a label tag?

You can either give class name to all label so that all can have same width :

 .class-name {  width:200px;}

Example

.labelname{  width:200px;}

or you can simple give rest of label

label {  width:200px;  display: inline-block;}

How to make a back-to-top button using CSS and HTML only?

<a href="#">Start of page</a>

"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."

Source

How to clean old dependencies from maven repositories?

I came up with a utility and hosted on GitHub to clean old versions of libraries in the local Maven repository. The utility, on its default execution removes all older versions of artifacts leaving only the latest ones. Optionally, it can remove all snapshots, sources, javadocs, and also groups or artifacts can be forced / excluded in this process. This cross platform also supports date based removal based on last access / download dates.

https://github.com/techpavan/mvn-repo-cleaner

How to select and change value of table cell with jQuery?

$("td:contains('c')").html("new");

or, more precisely $("#table_headers td:contains('c')").html("new");

and maybe for reuse you could create a function to call

function ReplaceCellContent(find, replace)
{
    $("#table_headers td:contains('" + find + "')").html(replace);
}

how to place last div into right top corner of parent div? (css)

 <div class='block1'>
    <p  style="float:left">text</p>
    <div class='block2' style="float:right">block2</div>
    <p  style="float:left; clear:left">text2</p>

 </div>

You can clear:both or clear:left depending on the exact context. Also, you will have to play around with width to get it to work correctly...

Date validation with ASP.NET validator

I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.

Write values in app.config file

As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings. But: Using Settings[key] = value will not work if the key doesn't exist.
Using Settings.Add(key, value), if the key already exists, it will join the new value to its value(s) separated by a comma, something like <add key="myKey" value="value1, value2, value3" />

To avoid these unexpected results, you have to handle two scenario's

  • If entry with the given key exists? then update its value
  • if entry with the given key doesn't exist? then create new entry(key,value)

Code

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

For more info about the check entry == null, check this post.
Hope this will help someone.

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

In Charles, go to Proxy>>Proxy Settings and select the SSL tab. Add your host to the list of Locations.

For example, if your secure call is going to https://secure.example.com, you can enter secure.example.com, or *.example.com.

Once the above is in place, you may need to right-click on the call in the main Charles window and select the SSL Proxying option.

Hope this helps.

Get the value of checked checkbox?

None of the above worked for me but simply use this:

document.querySelector('.messageCheckbox').checked;

Happy coding.

Java JRE 64-bit download for Windows?

You can also just search on sites like Tucows and CNET, they have it there too.

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Note that in an attribute selector (e.g., [attr~=value]), the tilde

Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

How to add a class to a given element?

first, give the div an id. Then, call function appendClass:

<script language="javascript">
  function appendClass(elementId, classToAppend){
    var oldClass = document.getElementById(elementId).getAttribute("class");
    if (oldClass.indexOf(classToAdd) == -1)
    {
      document.getElementById(elementId).setAttribute("class", classToAppend);
    }
}
</script>

C# - How to get Program Files (x86) on Windows 64 bit

Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

Get response from PHP file using AJAX

var data="your data";//ex data="id="+id;
      $.ajax({
       method : "POST",
       url : "file name",  //url: "demo.php"
       data : "data",
       success : function(result){
               //set result to div or target 
              //ex $("#divid).html(result)
        }
   });

How to form tuple column from two columns in Pandas

I'd like to add df.values.tolist(). (as long as you don't mind to get a column of lists rather than tuples)

import pandas as pd
import numpy as np

size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)}) 

%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

Accessing certain pixel RGB value in openCV

Try the following:

cv::Mat image = ...do some stuff...;

image.at<cv::Vec3b>(y,x); gives you the RGB (it might be ordered as BGR) vector of type cv::Vec3b

image.at<cv::Vec3b>(y,x)[0] = newval[0];
image.at<cv::Vec3b>(y,x)[1] = newval[1];
image.at<cv::Vec3b>(y,x)[2] = newval[2];

Copying PostgreSQL database to another server

I struggled quite a lot and eventually the method that allowed me to make it work with Rails 4 was:

on your old server

sudo su - postgres
pg_dump -c --inserts old_db_name > dump.sql

I had to use the postgres linux user to create the dump. also i had to use -c to force the creation of the database on the new server. --inserts tells it to use the INSERT() syntax which otherwise would not work for me :(

then, on the new server, simpy:

sudo su - postgres
psql new_database_name < dump.sql

to transfer the dump.sql file between server I simply used the "cat" to print the content and than "nano" to recreate it copypasting the content.

Also, the ROLE i was using on the two database was different so i had to find-replace all the owner name in the dump.

ORA-28000: the account is locked error getting frequently

Check the PASSWORD_LOCK_TIME parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock command.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

I know this post is old but here is what I found. It doesn't work when I link it this way(with / before css/style.csson the href attribute.

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

However, when I removed / I'm able to link properly with the css file It should be like this(without /).

<link rel="stylesheet" media="all" href="CSS/Style.css" type="text/css" />

This was giving me trouble on my project. Hope it will help somebody else.

Adding attribute in jQuery

You can do this with jQuery's .attr function, which will set attributes. Removing them is done via the .removeAttr function.

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

How can I make the computer beep in C#?

It is confirmed that Windows 7 and newer versions (at least 64bit or both) do not use system speaker and instead they route the call to the default sound device.

So, using system.beep() in win7/8/10 will not produce sound using internal system speaker. Instead, you'll get a beep sound from external speakers if they are available.

How to remove tab indent from several lines in IDLE?

Depends on your editor.

Have you tried Shift+Tab?

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

How to install easy_install in Python 2.7.1 on Windows 7

I usually just run ez_setup.py. IIRC, that works fine, at least with UAC off.

It also creates an easy_install executable in your Python\scripts subdirectory, which should be in your PATH.

UPDATE: I highly recommend not to bother with easy_install anymore! Jump right to pip, it's better in every regard!
Installation is just as simple: from the installation instructions page, you can download get-pip.py and run it. Works just like the ez_setup.py mentioned above.

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

Iterate a certain number of times without storing the iteration number anywhere

Others have addressed the inability to completely avoid an iteration variable in a for loop, but there are options to reduce the work a tiny amount. range has to generate a whole bunch of numbers after all, which involves a tiny amount of work; if you want to avoid even that, you can use itertools.repeat to just get the same (ignored) value back over and over, which involves no creation/retrieval of different objects:

from itertools import repeat

for _ in repeat(None, 200):  # Runs the loop 200 times
    ...

This will run faster in microbenchmarks than for _ in range(200):, but if the loop body does meaningful work, it's a drop in the bucket. And unlike multiplying some anonymous sequence for your loop iterable, repeat has only a trivial setup cost, with no memory overhead dependent on length.

Python convert tuple to string

Use str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

How to comment out a block of Python code in Vim

Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I used

View.inflate(getContext(), R.layout.whatever, null)

The using of View.inflate prevents the warning of using null at getLayoutInflater().inflate().

convert NSDictionary to NSString

Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.

Convert to String

NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);

Convert Back to Dictionary

NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
 response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}

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

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

HTML meta tag for content language

another language meta tag is og:locale and you can define og:locale meta tag for social media

<meta property="og:locale" content="en" />

How to get base url in CodeIgniter 2.*

Just load helper class

$this->load->helper('url');

thats it.

How can you represent inheritance in a database?

@Bill Karwin describes three inheritance models in his SQL Antipatterns book, when proposing solutions to the SQL Entity-Attribute-Value antipattern. This is a brief overview:

Single Table Inheritance (aka Table Per Hierarchy Inheritance):

Using a single table as in your first option is probably the simplest design. As you mentioned, many attributes that are subtype-specific will have to be given a NULL value on rows where these attributes do not apply. With this model, you would have one policies table, which would look something like this:

+------+---------------------+----------+----------------+------------------+
| id   | date_issued         | type     | vehicle_reg_no | property_address |
+------+---------------------+----------+----------------+------------------+
|    1 | 2010-08-20 12:00:00 | MOTOR    | 01-A-04004     | NULL             |
|    2 | 2010-08-20 13:00:00 | MOTOR    | 02-B-01010     | NULL             |
|    3 | 2010-08-20 14:00:00 | PROPERTY | NULL           | Oxford Street    |
|    4 | 2010-08-20 15:00:00 | MOTOR    | 03-C-02020     | NULL             |
+------+---------------------+----------+----------------+------------------+

\------ COMMON FIELDS -------/          \----- SUBTYPE SPECIFIC FIELDS -----/

Keeping the design simple is a plus, but the main problems with this approach are the following:

  • When it comes to adding new subtypes, you would have to alter the table to accommodate the attributes that describe these new objects. This can quickly become problematic when you have many subtypes, or if you plan to add subtypes on a regular basis.

  • The database will not be able to enforce which attributes apply and which don't, since there is no metadata to define which attributes belong to which subtypes.

  • You also cannot enforce NOT NULL on attributes of a subtype that should be mandatory. You would have to handle this in your application, which in general is not ideal.

Concrete Table Inheritance:

Another approach to tackle inheritance is to create a new table for each subtype, repeating all the common attributes in each table. For example:

--// Table: policies_motor
+------+---------------------+----------------+
| id   | date_issued         | vehicle_reg_no |
+------+---------------------+----------------+
|    1 | 2010-08-20 12:00:00 | 01-A-04004     |
|    2 | 2010-08-20 13:00:00 | 02-B-01010     |
|    3 | 2010-08-20 15:00:00 | 03-C-02020     |
+------+---------------------+----------------+
                          
--// Table: policies_property    
+------+---------------------+------------------+
| id   | date_issued         | property_address |
+------+---------------------+------------------+
|    1 | 2010-08-20 14:00:00 | Oxford Street    |   
+------+---------------------+------------------+

This design will basically solve the problems identified for the single table method:

  • Mandatory attributes can now be enforced with NOT NULL.

  • Adding a new subtype requires adding a new table instead of adding columns to an existing one.

  • There is also no risk that an inappropriate attribute is set for a particular subtype, such as the vehicle_reg_no field for a property policy.

  • There is no need for the type attribute as in the single table method. The type is now defined by the metadata: the table name.

However this model also comes with a few disadvantages:

  • The common attributes are mixed with the subtype specific attributes, and there is no easy way to identify them. The database will not know either.

  • When defining the tables, you would have to repeat the common attributes for each subtype table. That's definitely not DRY.

  • Searching for all the policies regardless of the subtype becomes difficult, and would require a bunch of UNIONs.

This is how you would have to query all the policies regardless of the type:

SELECT     date_issued, other_common_fields, 'MOTOR' AS type
FROM       policies_motor
UNION ALL
SELECT     date_issued, other_common_fields, 'PROPERTY' AS type
FROM       policies_property;

Note how adding new subtypes would require the above query to be modified with an additional UNION ALL for each subtype. This can easily lead to bugs in your application if this operation is forgotten.

Class Table Inheritance (aka Table Per Type Inheritance):

This is the solution that @David mentions in the other answer. You create a single table for your base class, which includes all the common attributes. Then you would create specific tables for each subtype, whose primary key also serves as a foreign key to the base table. Example:

CREATE TABLE policies (
   policy_id          int,
   date_issued        datetime,

   -- // other common attributes ...
);

CREATE TABLE policy_motor (
    policy_id         int,
    vehicle_reg_no    varchar(20),

   -- // other attributes specific to motor insurance ...

   FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);

CREATE TABLE policy_property (
    policy_id         int,
    property_address  varchar(20),

   -- // other attributes specific to property insurance ...

   FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);

This solution solves the problems identified in the other two designs:

  • Mandatory attributes can be enforced with NOT NULL.

  • Adding a new subtype requires adding a new table instead of adding columns to an existing one.

  • No risk that an inappropriate attribute is set for a particular subtype.

  • No need for the type attribute.

  • Now the common attributes are not mixed with the subtype specific attributes anymore.

  • We can stay DRY, finally. There is no need to repeat the common attributes for each subtype table when creating the tables.

  • Managing an auto incrementing id for the policies becomes easier, because this can be handled by the base table, instead of each subtype table generating them independently.

  • Searching for all the policies regardless of the subtype now becomes very easy: No UNIONs needed - just a SELECT * FROM policies.

I consider the class table approach as the most suitable in most situations.


The names of these three models come from Martin Fowler's book Patterns of Enterprise Application Architecture.

How to insert a timestamp in Oracle?

One can simply use

INSERT INTO MY_TABLE(MY_TIMESTAMP_FIELD)
VALUES (TIMESTAMP '2019-02-15 13:22:11.871+02:00');

This way you won't have to worry about date format string, just use default timestamp format.

Works with Oracle 11, have no idea if it does for earlier Oracle versions.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

How would I run an async Task<T> method synchronously?

I have found that SpinWait works pretty well for this.

var task = Task.Run(()=>DoSomethingAsyncronous());

if(!SpinWait.SpinUntil(()=>task.IsComplete, TimeSpan.FromSeconds(30)))
{//Task didn't complete within 30 seconds, fail...
   return false;
}

return true;

The above approach doesn't need to use .Result or .Wait(). It also lets you specify a timeout so that you're not stuck forever in case the task never completes.

Tri-state Check box in HTML?

You could use HTML's indeterminate IDL attribute on input elements.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Adding CSRFToken to Ajax request

I had this problem in a list of post in a blog, the post are in a view inside a foreach, then is difficult select it in javascript, and the problem of post method and token also exists.

This the code for javascript at the end of the view, I generate the token in javascript functión inside the view and not in a external js file, then is easy use php lavarel to generate it with csrf_token() function, and send the "delete" method directly in params. You can see that I don´t use in var route: {{ route('post.destroy', $post->id}} because I don´t know the id I want delete until someone click in destroy button, if you don´t have this problem you can use {{ route('post.destroy', $post->id}} or other like this.

  $(function(){
    $(".destroy").on("click", function(){
         var vid = $(this).attr("id");
         var v_token = "{{csrf_token()}}";
         var params = {_method: 'DELETE', _token: v_token};
         var route = "http://imagica.app/posts/" + vid + "";
    $.ajax({
         type: "POST",
         url: route,
         data: params
    });
   });
  });

and this the code of content in view (inside foreach there are more forms and the data of each post but is not inportant by this example), you can see I add a class "delete" to button and I call class in javascript.

      @foreach($posts as $post)
          <form method="POST">
            <button id="{{$post->id}}" class="btn btn-danger btn-sm pull-right destroy" type="button" >eliminar</button>
          </form>
      @endforeach

how to clear JTable

I had to get clean table without columns. I have done folowing:

jMyTable.setModel(new DefaultTableModel());

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Why am I getting this redefinition of class error?

You're defining the same class twice is why.

If your intent is to implement the methods in the CPP file then do so something like this:

gameObject::gameObject()
{
    x = 0;
    y = 0;
}
gameObject::~gameObject()
{
    //
}
int gameObject::add()
{
        return x+y;
}

Get all variables sent with POST?

The variable $_POST is automatically populated.

Try var_dump($_POST); to see the contents.

You can access individual values like this: echo $_POST["name"];

This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”

If your post data is in another format (e.g. JSON or XML, you can do something like this:

$post = file_get_contents('php://input');

and $post will contain the raw data.

Assuming you're using the standard $_POST variable, you can test if a checkbox is checked like this:

if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
     ...
}

If you have an array of checkboxes (e.g.

<form action="myscript.php" method="post">
  <input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
  <input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
  <input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
  <input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
  <input type="checkbox" name="myCheckbox[]" value="E" />val5
  <input type="submit" name="Submit" value="Submit" />
</form>

Using [ ] in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox'] won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.

For instance, if I checked all the boxes, $_POST['myCheckbox'] would be an array consisting of: {A, B, C, D, E}. Here's an example of how to retrieve the array of values and display them:

  $myboxes = $_POST['myCheckbox'];
  if(empty($myboxes))
  {
    echo("You didn't select any boxes.");
  }
  else
  {
    $i = count($myboxes);
    echo("You selected $i box(es): <br>");
    for($j = 0; $j < $i; $j++)
    {
      echo $myboxes[$j] . "<br>";
    }
  }

Enable binary mode while restoring a Database from an SQL dump

In Windows machine, please follows the preceding steps.

  1. Open file in notepad.
  2. Click on Save as
  3. Select Encoding type UTF-8.

Now source your db.

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

How do I find the size of a struct?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes. Alignment does come into play; always. The sizeof a single struct has to be such that an array of those sizes can be allocated and the individual members of the array are sufficiently aligned for the processor in question. Consequently, if the size of the struct was 5 as others have hypothesized, then an array of two such structures would be 10 bytes long, and the char pointer in the second array member would be aligned on an odd byte, which would (on most processors) cause a major bottleneck in the performance.

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

Create a file if it doesn't exist

Using input() implies Python 3, recent Python 3 versions have made the IOError exception deprecated (it is now an alias for OSError). So assuming you are using Python 3.3 or later:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except FileNotFoundError:
    file = open(fn, 'w')

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.

What is unit testing and how do you do it?

What exactly IS unit testing? Is it built into code or run as separate programs? Or something else?

From MSDN: The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

Essentially, you are writing small bits of code to test the individual bits of your code. In the .net world, you would run these small bits of code using something like NUnit or MBunit or even the built in testing tools in visual studio. In Java you might use JUnit. Essentially the test runners will build your project, load and execute the unit tests and then let you know if they pass or fail.

How do you do it?

Well it's easier said than done to unit test. It takes quite a bit of practice to get good at it. You need to structure your code in a way that makes it easy to unit test to make your tests effective.

When should it be done? Are there times or projects not to do it? Is everything unit-testable?

You should do it where it makes sense. Not everything is suited to unit testing. For example UI code is very hard to unit test and you often get little benefit from doing so. Business Layer code however is often very suitable for tests and that is where most unit testing is focused.

Unit testing is a massive topic and to fully get an understanding of how it can best benefit you I'd recommend getting hold of a book on unit testing such as "Test Driven Development by Example" which will give you a good grasp on the concepts and how you can apply them to your code.

How to launch multiple Internet Explorer windows/tabs from batch file?

Try this in your batch file:

@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com

Store boolean value in SQLite

Further to ericwa's answer. CHECK constraints can enable a pseudo boolean column by enforcing a TEXT datatype and only allowing TRUE or FALSE case specific values e.g.

CREATE TABLE IF NOT EXISTS "boolean_test"
(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT
,   "boolean" TEXT NOT NULL 
        CHECK( typeof("boolean") = "text" AND
               "boolean" IN ("TRUE","FALSE")
        )
);

INSERT INTO "boolean_test" ("boolean") VALUES ("TRUE");
INSERT INTO "boolean_test" ("boolean") VALUES ("FALSE");
INSERT INTO "boolean_test" ("boolean") VALUES ("TEST");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES ("true");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES ("false");

Error: CHECK constraint failed: boolean_test

INSERT INTO "boolean_test" ("boolean") VALUES (1);

Error: CHECK constraint failed: boolean_test

select * from boolean_test;

id  boolean
1   TRUE
2   FALSE

How to run a jar file in a linux commandline

Under linux there's a package called binfmt-support that allows you to run directly your jar without typing java -jar:

sudo apt-get install binfmt-support
chmod u+x my-jar.jar
./my-jar.jar # there you go!

Display Records From MySQL Database using JTable in Java

Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFromMySqlDatabase extends JFrame
{
    public TableFromMySqlDatabase()
    {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();

        //  Connect to an MySQL Database, run query, get result set
        String url = "jdbc:mysql://localhost:3306/yourdb";
        String userid = "root";
        String password = "sesame";
        String sql = "SELECT * FROM animals";

        // Java SE 7 has try-with-resources
        // This will ensure that the sql objects are closed when the program 
        // is finished with them
        try (Connection connection = DriverManager.getConnection( url, userid, password );
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql ))
        {
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++)
            {
                columnNames.add( md.getColumnName(i) );
            }

            //  Get row data
            while (rs.next())
            {
                ArrayList row = new ArrayList(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.add( rs.getObject(i) );
                }

                data.add( row );
            }
        }
        catch (SQLException e)
        {
            System.out.println( e.getMessage() );
        }

        // Create Vectors and copy over elements from ArrayLists to them
        // Vector is deprecated but I am using them in this example to keep 
        // things simple - the best practice would be to create a custom defined
        // class which inherits from the AbstractTableModel class
        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();

        for (int i = 0; i < data.size(); i++)
        {
            ArrayList subArray = (ArrayList)data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++)
            {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }

        for (int i = 0; i < columnNames.size(); i++ )
            columnNamesVector.add(columnNames.get(i));

        //  Create table with database data    
        JTable table = new JTable(dataVector, columnNamesVector)
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );

        JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

    public static void main(String[] args)
    {
        TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:

enter image description here

Otherwise the code will throw an SQLException stating that the driver cannot be found.

Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.

Here is what will be output:

enter image description here

Parting note:

You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

Extracting an attribute value with beautifulsoup

For me:

<input id="color" value="Blue"/>

This can be fetched by below snippet.

page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(color['value'])

Is Constructor Overriding Possible?

Because a constructor cannot be inherited in Java and Method Overriding requires inheritance. Therefore, it's not applicable.

Initialization of all elements of an array to one default value in C++?

In the C++ programming language V4, Stroustrup recommends using vectors or valarrays over builtin arrays. With valarrary's, when you create them, you can init them to a specific value like:

valarray <int>seven7s=(7777777,7);

To initialize an array 7 members long with "7777777".

This is a C++ way of implementing the answer using a C++ data structure instead of a "plain old C" array.

I switched to using the valarray as an attempt in my code to try to use C++'isms v. C'isms....

How to use 'hover' in CSS

I was working on a nice defect last time and was wondering more about how to use properly hover property for A tag link and for IE browser. A strange thing for me was that IE was not able to capture A tag link element based on a simple A selector. So, I found out how to even force capturing A tag element and I spotted that we must use more specifc CSS selector. Here is an example below - It works perfect:

li a[href]:hover {...}

Is there a developers api for craigslist.org

Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:

http://www.craigslist.org/about/bulk_posting_interface

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

As outlined in the Migrations guide to fix this, all you have to do is edit your app/Providers/AppServiceProvider.php file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migrations table.

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

After that everything should work as normal.

Correct way of getting Client's IP Addresses from http.Request

Looking at http.Request you can find the following member variables:

// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header

// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string

You can use RemoteAddr to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).

This is all you have for sure.

Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:

req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter

This is because internally http.Header.Get will normalise the key for you. (If you want to access header map directly, and not through Get, you would need to use http.CanonicalHeaderKey first.)

Finally, "X-Forwarded-For" is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:

// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
    fmt.Println(ip)
}

will produce:

10.0.0.1
10.0.0.2
10.0.0.3

Python string to unicode

>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…

.prop() vs .attr()

Dirty checkedness

This concept provides an example where the difference is observable: http://www.w3.org/TR/html5/forms.html#concept-input-checked-dirty

Try it out:

  • click the button. Both checkboxes got checked.
  • uncheck both checkboxes.
  • click the button again. Only the prop checkbox got checked. BANG!

_x000D_
_x000D_
$('button').on('click', function() {_x000D_
  $('#attr').attr('checked', 'checked')_x000D_
  $('#prop').prop('checked', true)_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>attr <input id="attr" type="checkbox"></label>_x000D_
<label>prop <input id="prop" type="checkbox"></label>_x000D_
<button type="button">Set checked attr and prop.</button>
_x000D_
_x000D_
_x000D_

For some attributes like disabled on button, adding or removing the content attribute disabled="disabled" always toggles the property (called IDL attribute in HTML5) because http://www.w3.org/TR/html5/forms.html#attr-fe-disabled says:

The disabled IDL attribute must reflect the disabled content attribute.

so you might get away with it, although it is ugly since it modifies HTML without need.

For other attributes like checked="checked" on input type="checkbox", things break, because once you click on it, it becomes dirty, and then adding or removing the checked="checked" content attribute does not toggle checkedness anymore.

This is why you should use mostly .prop, as it affects the effective property directly, instead of relying on complex side-effects of modifying the HTML.

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I had a similar issue where I couldn't connect to a database and tried the recommendations here.

At the end of the day this is what worked for me:

Used the SQL Server Configuration Manager tool to enable the TCP/IP and/or the Named Pipes protocols on the SQL Server client computer.

  1. Click Start, point to All Programs, and click SQL Server Configuration Manager.
  2. Click to expand SQL Server Network Configuration and then click Client Protocols.
  3. Right-click the TCP/IP protocol and then click Enable.
  4. Right-click the Named Pipes protocol and then click Enable.
  5. Restart the SQL server service if prompted to do so.

I am still not sure why or when this was disabled.

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

You need to specify the source dir

File> Project Structure > Modules

click the directory and click the Sources button

It's weird because usually it's done automatically. Maybe it's better if you recreate the project again.

fatal: could not create work tree dir 'kivy'

You need to ensure you are in a directory in which you have write permission. This might not be the directory in which Git is in once you open the terminal. In my case (Widows 10) I had to use the cd command to change the directory to the root directory (C:) After that it worked just fine.

Select default option value from typescript angular 6

You may use bellow like in angular 9

 <select [(ngModel)]="itemId"  formControlName="itemId" class="form-control" >
          <option [ngValue]="" disabled>Choose Gender</option>             
          <option *ngFor="let item of items"  [ngValue]="item .id" [selected]="item .id == this.id"  >
             {{item.name}}
          </option>
   </select>

What is the difference between C++ and Visual C++?

C++ is a language and Visual C++ is a compiler for that language. Certainly, it (and every other compiler) introduces tiny modifications to the language, but the language recognized is mainly the same.

Methods vs Constructors in Java

Here are some main key differences between constructor and method in java

  1. Constructors are called at the time of object creation automatically. But methods are not called during the time of object creation automatically.
  2. Constructor name must be same as the class name. Method has no such protocol.
  3. The constructors can’t have any return type. Not even void. But methods can have a return type and also void. Click to know details - Difference between constructor and method in Java

JPA or JDBC, how are they different?

In layman's terms:

  • JDBC is a standard for Database Access
  • JPA is a standard for ORM

JDBC is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS, etc. Data sets can be returned which you can handle in your app, and you can do all the usual things like INSERT, DELETE, run stored procedures, etc. It is one of the underlying technologies behind most Java database access (including JPA providers).

One of the issues with traditional JDBC apps is that you can often have some crappy code where lots of mapping between data sets and objects occur, logic is mixed in with SQL, etc.

JPA is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. Mostly, XML mapping files or annotations on getters and setters can be used to tell the JPA provider which fields on your object map to which fields in the DB. The most famous JPA provider is Hibernate, so it's a good place to start for concrete examples.

Other examples include OpenJPA, toplink, etc.

Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write from and to the DB.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I had this due to a simple ordering mistake on my end. I called

[WRONG] docker run <image> <arguments> <command>

When I should have used

docker run <arguments> <image> <command>

Same resolution on similar question: https://stackoverflow.com/a/50762266/6278