Programs & Examples On #Lemon

Lemon is a parser generator, maintained as part of the SQLite project, that generates an LALR(1) parser in the C programming language from an input context-free grammar.

Can a website detect when you are using Selenium with chromedriver?

It works for some websites, remove property webdriver from navigator

from selenium import webdriver
driver = webdriver.Chrome()
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source":
        "const newProto = navigator.__proto__;"
        "delete newProto.webdriver;"
        "navigator.__proto__ = newProto;"
    })

Gradle failed to resolve library in Android Studio

Try this

  1. Clean project
  2. Invalidate cache and restart studio
  3. Check android SDK path is proper
  4. Check is there any error in any of your resource file

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@watson

On windows forms it is available, at the top of the class put

  static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
       //other stuff here
    }

since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).

using System.Security.Principal 

is also needed.

How do I run a PowerShell script when the computer starts?

Prerequisite:

1. Start powershell with the "Run as Administrator" option

2. Enable running unsigned scripts with:

set-executionpolicy remotesigned

3. prepare your powershell script and know its path:

$path = "C:\Users\myname\myscript.ps1"

Steps:

1. setup a trigger, see also New-JobTrigger (PSScheduledJob) - PowerShell | Microsoft Docs

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30

2. register a scheduled job, see also Register-ScheduledJob (PSScheduledJob) - PowerShell | Microsoft Docs

Register-ScheduledJob -Trigger $trigger -FilePath $path -Name MyScheduledJob

you can check it with Get-ScheduledJob -Name MyScheduledJob

3. Reboot Windows (restart /r) and check the result with:

Get-Job -name MyScheduledJob

see also Get-Job (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs

References:

  1. How to enable execution of PowerShell scripts? - Super User
  2. Use PowerShell to Create Job that Runs at Startup | Scripting Blog

Make xargs handle filenames that contain spaces

Given the specific title of this post, here's my suggestion:

ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'

The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:

ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo

The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.

SQL Query Multiple Columns Using Distinct on One Column Only

I needed to do the same and had to query a query to get the result

I set my first query up to bring in all IDs from the table and all other information needed to filter:

SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));

Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)

SELECT DISTINCT ID
FROM q04_1;

Saved that as q04_2

I then wrote another query which brought in the required information linked to the ID

SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;

Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.

This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)

SSH configuration: override the default username

There is a Ruby gem that interfaces your ssh configuration file which is called sshez.

All you have to do is sshez <alias> [email protected] -p <port-number>, and then you can connect using ssh <alias>. It is also useful since you can list your aliases using sshez list and can easily remove them using sshez remove alias.

JavaScript single line 'if' statement - best syntax, this alternative?

This one line is much cleaner.

if(dog) alert('bark bark');

I prefer this. hope it helps someone

Javascript Regular Expression Remove Spaces

In production and works across line breaks

This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.

text.replace(/[\n\r\s\t]+/g, ' ')

Calculating the SUM of (Quantity*Price) from 2 different tables

I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.

select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
    select o.orderID, o.price * o.qty as subtotal
    from product p inner join orderitem o on p.ProductID= o.productID
    where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal

SQLAlchemy equivalent to SQL "LIKE" statement

If you use native sql, you can refer to my code, otherwise just ignore my answer.

SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text

bar_tags = "banana"

# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""

# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Oracle SQL, concatenate multiple columns + add text

Below query works for me @Oracle 10G ----

select PHONE, CONTACT, (ADDR1 ||  '-' || ADDR2 || '-' || ADDR3) as Address
from CUSTOMER_DETAILS
where Code='341'; 

O/P -

1111 [email protected] 4th street-capetown-sa

Item frequency count in Python

The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})

Restore LogCat window within Android Studio

If all of the above methods does not work then try the below mechanism. Sometimes, the android studio does not show logcat options because of the project you select is not an android project. If you want to debug an APK, create an empty android project then it will start showing the logcat option.

Boolean.parseBoolean("1") = false...?

It accepts only a string value of "true" to represent boolean true. Best what you can do is

boolean uses_votes = "1".equals(o.get("uses_votes"));

Or if the Map actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.

virtualenvwrapper and Python 3

virtualenvwrapper now lets you specify the python executable without the path.

So (on OSX at least)mkvirtualenv --python=python3 nameOfEnvironment will suffice.

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

What is the easiest way to clear a database from the CLI with manage.py in Django?

Using Django Extensions, running:

./manage.py reset_db

Will clear the database tables, then running:

./manage.py syncdb

Will recreate them (south may ask you to migrate things).

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

Assume file is already created in the predefined directory with name "table.txt"

  • 1) change the ownership for file :

    sudo chown username:username table.txt
    
  • 2) change the mode of the file

    sudo chmod 777 table.txt
    

Now, try it should work!

How to trigger click on page load?

$("document").ready({
    $("ul.galleria li:first-child img").click(function(){alert('i work click triggered'});
}); 

$("document").ready(function() { 
    $("ul.galleria li:first-child img").trigger('click'); 
}); 

just make sure the click handler is added prior to the trigger event in the call stack sequence.

  $("document").ready(function() { 
        $("ul.galleria li:first-child img").trigger('click'); 
    }); 

   $("document").ready({
        $("ul.galleria li:first-child img").click(function(){alert('i fail click triggered'});
    }); 

How to load my app from Eclipse to my Android phone instead of AVD

What I did, by reading all of above answers and it worked as well: 7 deadly steps

  1. Connect your android phone with the pc on which you are running eclipse/your map project.
  2. Let it install all the necessary drivers.. When done, open your smart phone, go to: Settings > Applications > Development > USB debugging and enable it on by clicking on the check button at the right side.
  3. Also, enable Settings > Unknowresoures
  4. Come back to eclipse on your pc. Right click on the project/application, Run As > Run configurations... >Choose Device>Target Select your device Run.
  5. Click on the Target tab from top. By default it is on the first tab Android
  6. Choose the second radio button which says Launch on all compatible deivces/AVDs. Then click Apply at the bottom and afterwards, click Run.
  7. Here you go, it will automatically install your application's .apk file into your smart phone and make it run over it., just like on emulator.

If you get it running, please help others too.

Super-simple example of C# observer/observable with delegates

The observer pattern is usually implemented with events.

Here's an example:

using System;

class Observable
{
    public event EventHandler SomethingHappened;

    public void DoSomething() =>
        SomethingHappened?.Invoke(this, EventArgs.Empty);
}

class Observer
{
    public void HandleEvent(object sender, EventArgs args)
    {
        Console.WriteLine("Something happened to " + sender);
    }
}

class Test
{
    static void Main()
    {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.DoSomething();
    }
}

See the linked article for a lot more detail.

Note that the above example uses C# 6 null-conditional operator to implement DoSomething safely to handle cases where SomethingHappened has not been subscribed to, and is therefore null. If you're using an older version of C#, you'd need code like this:

public void DoSomething()
{
    var handler = SomethingHappened;
    if (handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}

Collapsing Sidebar with Bootstrap

Via Angular: using ng-class of Angular, we can hide and show the side bar.

http://jsfiddle.net/DVE4f/359/

<div class="container" style="width:100%" ng-app ng-controller="AppCtrl">
<div class="row">
    <div ng-class="showgraphSidebar ? 'col-xs-3' : 'hidden'" id="colPush" >
        Sidebar
    </div>
    <div ng-class="showgraphSidebar ? 'col-xs-9' : 'col-xs-12'"  id="colMain"  >
        <button  ng-click='toggle()' >Sidebar Toggle</a>
    </div>    
  </div>
</div>

.

function AppCtrl($scope) {
    $scope.showgraphSidebar = false;
    $scope.toggle = function() {
        $scope.showgraphSidebar = !$scope.showgraphSidebar;
    }
}

How do I convert a number to a numeric, comma-separated formatted string?

I looked at several of the options. Here are my two favorites, because I needed to round the value.

,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2   = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy --------- 
--- Hank Freeman : [email protected] 
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
   SELECT
   FileGroupName = DS.name
   ,FileGroupType =
      CASE DS.[type]
        WHEN 'FG' THEN 'Filegroup'
        WHEN 'FD' THEN 'Filestream'
        WHEN 'FX' THEN 'Memory-optimized'
        WHEN 'PS' THEN 'Partition Scheme'
        ELSE 'Unknown'
      END
   ,SchemaName = SCH.name
   ,TableName = OBJ.name
   ,IndexType =
      CASE IDX.[type]
        WHEN 0 THEN 'Heap'
        WHEN 1 THEN 'Clustered'
        WHEN 2 THEN 'Nonclustered'
        WHEN 3 THEN 'XML'
        WHEN 4 THEN 'Spatial'
        WHEN 5 THEN 'Clustered columnstore'
        WHEN 6 THEN 'Nonclustered columnstore'
        WHEN 7 THEN 'Nonclustered hash'
      END
   ,IndexName = IDX.name
   ,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','')  --- MUST show for all types when no Primary key
   --,( Case WHEN IDX.[type] IN (2,6,7) then 0  else  p.rows  end )as Rowcounts_T
   ,AllocationDesc = AU.type_desc
/*
   ,RowCounts = p.rows  --- MUST show for all types when no Primary key
   ,TotalSizeKB2  = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
   ,UsedSizeKB    = Cast(Round(SUM(AU.used_pages / 0.128),0)as int) 
   ,DataSizeKB    = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
    --replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
   ,TotalSizeKB   = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
   ,UsedSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','') 
   ,DataSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
   ,DataSizeKB2   = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
   ,DataSizeKB3   = format(SUM(AU.data_pages / 0.128),'##,##0')
   --SELECT Format(1234567.8, '##,##0.00')
   ---
   ,is_default    = CONVERT(INT,DS.is_default)
   ,is_read_only = CONVERT(INT,DS.is_read_only)
  FROM
   sys.filegroups DS -- you could also use sys.data_spaces
    LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
    LEFT JOIN sys.partitions PA
      ON (AU.[type] IN (1,3) AND
          AU.container_id = PA.hobt_id) OR
         (AU.[type] = 2 AND
          AU.container_id = PA.[partition_id])
    LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
    LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
    LEFT JOIN sys.indexes IDX
      ON PA.[object_id] = IDX.[object_id] AND
         PA.index_id = IDX.index_id
    -----
    INNER JOIN 
      sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
  WHERE
    OBJ.type_desc = 'USER_TABLE' -- only include user tables
    OR
    DS.[type] = 'FD' -- or the filestream filegroup
  GROUP BY
    DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type]  ,DS.is_default   ,DS.is_read_only -- discard different allocation units
   ,p.rows  ,AU.type_desc  --- 
  ORDER BY
    DS.name ,SCH.name ,OBJ.name ,IDX.name
   ---
   ;

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

Java: Multiple class declarations in one file

I believe you simply call PrivateImpl what it is: a non-public top-level class. You can also declare non-public top-level interfaces as well.

e.g., elsewhere on SO: Non-public top-level class vs static nested class

As for changes in behavior between versions, there was this discussion about something that "worked perfectly" in 1.2.2. but stopped working in 1.4 in sun's forum: Java Compiler - unable to declare a non public top level classes in a file.

Difference between one-to-many and many-to-one relationship

What is the real difference between one-to-many and many-to-one relationship?

There are conceptual differences between these terms that should help you visualize the data and also possible differences in the generated schema that should be fully understood. Mostly the difference is one of perspective though.

In a one-to-many relationship, the local table has one row that may be associated with many rows in another table. In the example from SQL for beginners, one Customer may be associated to many Orders.

In the opposite many-to-one relationship, the local table may have many rows that are associated with one row in another table. In our example, many Orders may be associated to one Customer. This conceptual difference is important for mental representation.

In addition, the schema which supports the relationship may be represented differently in the Customer and Order tables. For example, if the customer has columns id and name:

id,name
1,Bill Smith
2,Jim Kenshaw

Then for a Order to be associated with a Customer, many SQL implementations add to the Order table a column which stores the id of the associated Customer (in this schema customer_id:

id,date,amount,customer_id
10,20160620,12.34,1
11,20160620,7.58,1
12,20160621,158.01,2

In the above data rows, if we look at the customer_id id column, we see that Bill Smith (customer-id #1) has 2 orders associated with him: one for $12.34 and one for $7.58. Jim Kenshaw (customer-id #2) has only 1 order for $158.01.

What is important to realize is that typically the one-to-many relationship doesn't actually add any columns to the table that is the "one". The Customer has no extra columns which describe the relationship with Order. In fact the Customer might also have a one-to-many relationship with ShippingAddress and SalesCall tables and yet have no additional columns added to the Customer table.

However, for a many-to-one relationship to be described, often an id column is added to the "many" table which is a foreign-key to the "one" table -- in this case a customer_id column is added to the Order. To associated order #10 for $12.34 to Bill Smith, we assign the customer_id column to Bill Smith's id 1.

However, it is also possible for there to be another table that describes the Customer and Order relationship, so that no additional fields need to be added to the Order table. Instead of adding a customer_id field to the Order table, there could be Customer_Order table that contains keys for both the Customer and Order.

customer_id,order_id
1,10
1,11
2,12

In this case, the one-to-many and many-to-one is all conceptual since there are no schema changes between them. Which mechanism depends on your schema and SQL implementation.

Hope this helps.

Creating and Update Laravel Eloquent

Isn't this the same as updateOrCreate()?

It is similar but not the same. The updateOrCreate() will only work for one row at a time which doesn't allow bulk insert. InsertOnDuplicateKey will work on many rows.

https://github.com/yadakhov/insert-on-duplicate-key

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

How to get primary key of table?

MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-

SHOW INDEXES FROM products \G

It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -

*************************** 1. row ***************************
        Table: products
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: product_id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 

To just display primary key from the table use :-

SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'

Javascript string replace with regex to strip off illegal characters

What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).

Syntax: [characters] where characters is a list with characters.

Example:

var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");

Is it possible to put CSS @media rules inline?

Hey I just wrote it.

Now you can use <div style="color: red; @media (max-width: 200px) { color: green }"> or so.

Enjoy.

JavaScript hashmap equivalent

In ECMAScript 6 you can use WeakMap.

Example:

var wm1 = new WeakMap(),
    wm2 = new WeakMap(),
    wm3 = new WeakMap();
var o1 = {},
    o2 = function(){},
    o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // A value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // Keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // Undefined, because there is no value for o2 on wm2
wm2.get(o3); // Undefined, because that is the set value

wm1.has(o2); // True
wm2.has(o2); // False
wm2.has(o3); // True (even if the value itself is 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37
wm3.clear();
wm3.get(o1); // Undefined, because wm3 was cleared and there is no value for o1 anymore

wm1.has(o1);   // True
wm1.delete(o1);
wm1.has(o1);   // False

But:

Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys).

GCM with PHP (Google Cloud Messaging)

After searching for a long time finally I am able to figure out what I exactly needed, Connecting to the GCM using PHP as a server side scripting language, The following tutorial will give us a clear idea of how to setup everything we need to get started with GCM

Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

Go install fails with error: no install location for directory xxx outside GOPATH

You'll want to have 3 directories inside your chosen GOPATH directory.

GOPATH
     /bin
     /src
       /someProgram
        program.go
       /someLibrary
        library.go
     /pkg

Then you'll run go install from inside either someProgram (which puts an executable in bin) or someLibrary (which puts a library in pkg).

How to cut an entire line in vim and paste it?

  1. Go to the line, and first press esc, and then Shift + v.

(This would have highlighted the line)

  1. press d

(The line is now deleted)

  1. Go to the location, where you wanted to paste the line, and hit p.

In a nutshell,

Esc -> Shift + v -> d -> p

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

How to find a Java Memory Leak

You really need to use a memory profiler that tracks allocations. Take a look at JProfiler - their "heap walker" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools.

Get folder name from full file path

I think you want to get parent folder name from file path. It is easy to get. One way is to create a FileInfo type object and use its Directory property.

Example:

FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");

String dirName = fInfo.Directory.Name;

Resolve Git merge conflicts in favor of their changes during a pull

If you're already in conflicted state, and you want to just accept all of theirs:

git checkout --theirs .
git add .

If you want to do the opposite:

git checkout --ours .
git add .

This is pretty drastic, so make sure you really want to wipe everything out like this before doing it.

Return a 2d array from a function

That code isn't going to work, and it's not going to help you learn proper C++ if we fix it. It's better if you do something different. Raw arrays (especially multi-dimensional arrays) are difficult to pass correctly to and from functions. I think you'll be much better off starting with an object that represents an array but can be safely copied. Look up the documentation for std::vector.

In your code, you could use vector<vector<int> > or you could simulate a 2-D array with a 36-element vector<int>.

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Representing Directory & File Structure in Markdown Syntax

If you wish to generate it dynamically I recommend using Frontend-md. It is simple to use.

Python: Find index of minimum item in list of floats

Use of the argmin method for numpy arrays.

import numpy as np
np.argmin(myList)

However, it is not the fastest method: it is 3 times slower than OP's answer on my computer. It may be the most concise one though.

HTML/Javascript Button Click Counter

    <!DOCTYPE html>
<html>
<head>
<script>
     var clicks = 0;
    function myFunction() {

        clicks += 1;
        document.getElementById("demo").innerHTML = clicks;


    }
</script>
</head>
<body>

<p>Click the button to trigger a function.</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

</body>
</html>

This should work for you :) Yes var should be used

How to upload file using Selenium WebDriver in Java

This is what I use to upload the image through upload window:

    //open upload window
    upload.click();

    //put path to your image in a clipboard
    StringSelection ss = new StringSelection("C:\\IMG_3827.JPG");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

    //imitate mouse events like ENTER, CTRL+C, CTRL+V
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

done

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Try this

Sub Sample()
    Dim test As Worksheet
    Sheets(1).Copy After:=Sheets(Sheets.Count)
    Set test = ActiveSheet
    test.Name = "copied sheet!"
End Sub

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

What is an application binary interface (ABI)?

In order to call code in shared libraries, or call code between compilation units, the object file needs to contain labels for the calls. C++ mangles the names of method labels in order to enforce data hiding and allow for overloaded methods. That is why you cannot mix files from different C++ compilers unless they explicitly support the same ABI.

"Input string was not in a correct format."

I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.

I'd declared a string and was formatting it for use with JQTree which requires curly braces ({}). You have to use doubled curly braces for it to be accepted as a properly formatted string:

string measurements = string.empty;
measurements += string.Format(@"
    {{label: 'Measurement Name: {0}',
        children: [
            {{label: 'Measured Value: {1}'}},
            {{label: 'Min: {2}'}},
            {{label: 'Max: {3}'}},
            {{label: 'Measured String: {4}'}},
            {{label: 'Expected String: {5}'}},
        ]
    }},",
    drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
    drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
    drv["Min"] == null ? "NULL" : drv["Min"],
    drv["Max"] == null ? "NULL" : drv["Max"],
    drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
    drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);

Hopefully this will help other folks who find this question but aren't parsing numerical data.

getch and arrow codes

I have written a function using getch to get arrow code. it's a quick'n'dirty solution but the function will return an ASCII code depending on arrow key : UP : -10 DOWN : -11 RIGHT : -12 LEFT : -13

Moreover,with this function, you will be able to differenciate the ESCAPE touch and the arrow keys. But you have to press ESC 2 time to activate the ESC key.

here the code :

char getch_hotkey_upgrade(void)
{
  char ch = 0,ch_test[3] = {0,0,0};

    ch_test[0]=getch();

    if(ch_test[0] == 27)
    {
        ch_test[1]=getch();

        if (ch_test[1]== 91)
        {
            ch_test[2]=getch();

            switch(ch_test[2])
            {
            case 'A':
                //printf("You pressed the up arrow key !!\n");
                //ch = -10;
                ch = -10;
                break;
            case 'B':
                //printf("You pressed the down arrow key !!\n");
                ch = -11;
                break;
            case 'C':
                //printf("You pressed the right arrow key !!\n");
                ch = -12;
                break;
            case 'D':
                //printf("You pressed the left arrow key !!\n");
                ch = -13;
                break;
            }
        }
        else
         ch = ch_test [1];
    }
    else
        ch = ch_test [0];
  return ch;
}

When is JavaScript synchronous?

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

JavaScript timers operate with this same kind of callback.

Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.

Structure padding and packing

Structure packing suppresses structure padding, padding used when alignment matters most, packing used when space matters most.

Some compilers provide #pragma to suppress padding or to make it packed to n number of bytes. Some provide keywords to do this. Generally pragma which is used for modifying structure padding will be in the below format (depends on compiler):

#pragma pack(n)

For example ARM provides the __packed keyword to suppress structure padding. Go through your compiler manual to learn more about this.

So a packed structure is a structure without padding.

Generally packed structures will be used

  • to save space

  • to format a data structure to transmit over network using some protocol (this is not a good practice of course because you need to
    deal with endianness)

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

For those of you developing on localhost follow these steps:

  1. Tap the "+" button next to Information Property List and add App Transport Security Settings and assign it a Dictionary Type
  2. Tap the "+" button next to the newly created App Transport Security Settings entry and add NSExceptionAllowsInsecureHTTPLoads of type Boolean and set its value to YES.
  3. Right click on NSExceptionAllowsInsecureHTTPLoads entry and click the "Shift Row Right" option to make it a child of the above entry.
  4. Tap the "+" button next to the NSExceptionAllowsInsecureHTTPLoads entry and add Allow Arbitrary Loads of type Boolean and set its value to YES

Note: It should in the end look something like presented in the following picture

enter image description here

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.

Model:

public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}

Html helper extension:

   public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
    var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var metadata = modelMetadata;

    var viewData = new
    {
        HtmlAttributes = new
            {
                @class = htmlClass,
                placeholder = metadata.Watermark,
            }
    };
    return htmlHelper.EditorFor(expression, viewData);

}

A corresponding view:

@Html.BsEditorFor(x => x.Title)

How do I determine whether my calculation of pi is accurate?

You could use multiple approaches and see if they converge to the same answer. Or grab some from the 'net. The Chudnovsky algorithm is usually used as a very fast method of calculating pi. http://www.craig-wood.com/nick/articles/pi-chudnovsky/

Enter key pressed event handler

For those who struggle at capturing Enter key on TextBox or other input control, if your Form has AcceptButton defined, you will not be able to use KeyDown event to capture Enter.

What you should do is to catch the Enter key at form level. Add this code to the form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
    {
        //do something
        return true;
    }
    else
    {
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

How can I do DNS lookups in Python, including referring to /etc/hosts?

Sounds like you don't want to resolve dns yourself (this might be the wrong nomenclature) dnspython appears to be a standalone dns client that will understandably ignore your operating system because its bypassing the operating system's utillities.

We can look at a shell utility named getent to understand how the (debian 11 alike) operating system resolves dns for programs, this is likely the standard for all *nix like systems that use a socket implementation.

see man getent's "hosts" section, which mentions the use of getaddrinfo, which we can see as man getaddrinfo

and to use it in python, we have to extract some info from the data structures

.

import socket

def get_ipv4_by_hostname(hostname):
    # see `man getent` `/ hosts `
    # see `man getaddrinfo`

    return list(
        i        # raw socket structure
            [4]  # internet protocol info
            [0]  # address
        for i in 
        socket.getaddrinfo(
            hostname,
            0  # port, required
        )
        if i[0] is socket.AddressFamily.AF_INET  # ipv4

        # ignore duplicate addresses with other socket types
        and i[1] is socket.SocketKind.SOCK_RAW  
    )

print(get_ipv4_by_hostname('localhost'))
print(get_ipv4_by_hostname('google.com'))

Calculate correlation with cor(), only for numerical columns

Another option would be to just use the excellent corrr package https://github.com/drsimonj/corrr and do

require(corrr)
require(dplyr)

myData %>% 
   select(x,y,z) %>%  # or do negative or range selections here
   correlate() %>%
   rearrange() %>%  # rearrange by correlations
   shave() # Shave off the upper triangle for a cleaner result

Steps 3 and 4 are entirely optional and are just included to demonstrate the usefulness of the package.

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to print Two-Dimensional Array like table

Iliya,

Sorry for that.

you code is work. but its had some problem with Array row and columns

here i correct your code this work correctly, you can try this ..

public static void printMatrix(int size, int row, int[][] matrix) {

    for (int i = 0; i < 7 * matrix[row].length; i++) {
        System.out.print("-");
    }
    System.out.println("-");

    for (int i = 1; i <= matrix[row].length; i++) {
        System.out.printf("| %4d ", matrix[row][i - 1]);
    }
    System.out.println("|");

    if (row == size - 1) {

        // when we reach the last row,
        // print bottom line "---------"

        for (int i = 0; i < 7 * matrix[row].length; i++) {
            System.out.print("-");
        }
        System.out.println("-");

    }
}

public static void length(int[][] matrix) {

    int rowsLength = matrix.length;

    for (int k = 0; k < rowsLength; k++) {

        printMatrix(rowsLength, k, matrix);

    }

}

public static void main(String[] args) {

    int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }

    };

    length(matrix);

}

and out put look like

----------------------
|    1 |    2 |    5 |
----------------------
|    3 |    4 |    6 |
----------------------
|    7 |    8 |    9 |
----------------------

I can't understand why this JAXB IllegalAnnotationException is thrown

This is happening be cause you have 2 classes with same name. For, example, I have 2 SOAP web-services named settings and settings2 both have the same class GetEmployee and this is ambiguous proving the error.

Passing variable number of arguments around

You can try macro also.

#define NONE    0x00
#define DBG     0x1F
#define INFO    0x0F
#define ERR     0x07
#define EMR     0x03
#define CRIT    0x01

#define DEBUG_LEVEL ERR

#define WHERESTR "[FILE : %s, FUNC : %s, LINE : %d]: "
#define WHEREARG __FILE__,__func__,__LINE__
#define DEBUG(...)  fprintf(stderr, __VA_ARGS__)
#define DEBUG_PRINT(X, _fmt, ...)  if((DEBUG_LEVEL & X) == X) \
                                      DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)

int main()
{
    int x=10;
    DEBUG_PRINT(DBG, "i am x %d\n", x);
    return 0;
}

Is mongodb running?

Correct, closing the shell will stop MongoDB. Try using the --fork command line arg for the mongod process which makes it run as a daemon instead. I'm no Unix guru, but I'm sure there must be a way to then get it to auto start when the machine boots up.

e.g.

mongod --fork --logpath /var/log/mongodb.log --logappend

Check out the full documentation on Starting and Stopping Mongo.

Set android shape color programmatically

this is the solution that works for me...wrote it in another question as well: How to change shape color dynamically?

//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);

//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();

//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)

Hashing a dictionary?

I do it like this:

hash(str(my_dict))

How to get the python.exe location programmatically?

I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe

which gives this value on my machine:

C:\Python25\Python.exe

You just read the registry key to get the location.

However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.

T-SQL query to show table definition?

Have you tried sp_help?

sp_help 'TableName'

in iPhone App How to detect the screen resolution of the device

See the UIScreen Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html

if([[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"scale")])
{
    if ([[UIScreen mainScreen] scale] < 1.1)
        NSLog(@"Standard Resolution Device");

    if ([[UIScreen mainScreen] scale] > 1.9)
        NSLog(@"High Resolution Device");
}

How to write log base(2) in c/c++

Improved version of what Ustaman Sangat did

static inline uint64_t
log2(uint64_t n)
{
    uint64_t val;
    for (val = 0; n > 1; val++, n >>= 1);

    return val;
}

How to Delete node_modules - Deep Nested Folder in Windows

Okay so my problem was that i had .bin folder inside node_modules and i wasn't able to delete that, I tried all the above solutions for the same but nothing worked.

Error which was repeating was "u do not have permission to delete the folder or its been used by some other program".

Solution that i found "I had Antivirus installed on my pc ,which was unknowingly using the files from node_modules folder".

I uninstalled the antivirus or u can change permission setting from antivirus setting option (depends on which antivirus u have).Now i am able to delete node_modules folder.

Typescript sleep

If you are using angular5 and above, please include the below method in your ts file.

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

then call this delay() method wherever you want.

e.g:

validateInputValues() {
    if (null == this.id|| this.id== "") {
        this.messageService.add(
            {severity: 'error', summary: 'ID is Required.'});
        this.delay(3000).then(any => {
            this.messageService.clear();
        });
    }
}

This will disappear message growl after 3 seconds.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

System32 is where Windows historically placed all 32bit DLLs, and System was for the 16bit DLLs. When microsoft created the 64 bit OS, everyone I know of expected the files to reside under System64, but Microsoft decided it made more sense to put 64bit files under System32. The only reasoning I have been able to find, is that they wanted everything that was 32bit to work in a 64bit Windows w/o having to change anything in the programs -- just recompile, and it's done. The way they solved this, so that 32bit applications could still run, was to create a 32bit windows subsystem called Windows32 On Windows64. As such, the acronym SysWOW64 was created for the System directory of the 32bit subsystem. The Sys is short for System, and WOW64 is short for Windows32OnWindows64.
Since windows 16 is already segregated from Windows 32, there was no need for a Windows 16 On Windows 64 equivalence. Within the 32bit subsystem, when a program goes to use files from the system32 directory, they actually get the files from the SysWOW64 directory. But the process is flawed.

It's a horrible design. And in my experience, I had to do a lot more changes for writing 64bit applications, that simply changing the System32 directory to read System64 would have been a very small change, and one that pre-compiler directives are intended to handle.

How to push local changes to a remote git repository on bitbucket

I'm with Git downloaded from https://git-scm.com/ and set up ssh follow to the answer for instructions https://stackoverflow.com/a/26130250/4058484.

Once the generated public key is verified in my Bitbucket account, and by referring to the steps as explaned on http://www.bohyunkim.net/blog/archives/2518 I found that just 'git push' is working:

git clone https://[email protected]/me/test.git
cd test
cp -R ../dummy/* .
git add .
git pull origin master 
git commit . -m "my first git commit" 
git config --global push.default simple
git push

Shell respond are as below:

$ git push
Counting objects: 39, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (39/39), done.
Writing objects: 100% (39/39), 2.23 MiB | 5.00 KiB/s, done.
Total 39 (delta 1), reused 0 (delta 0)
To https://[email protected]/me/test.git 992b294..93835ca  master -> master

It even works for to push on merging master to gh-pages in GitHub

git checkout gh-pages
git merge master
git push

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

How can I convert a PFX certificate file for use with Apache on a linux server?

Additionally to

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key

I also generated Certificate Authority (CA) certificate:

openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts

And included it in Apache config file:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 SSLCACertificateFile /path/to/domain-ca.crt
 ...
</VirtualHost>

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

How to do 3 table JOIN in UPDATE query?

An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.

UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}

Example:

UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;

What does <> mean?

could be a shorthand for React.Fragment

Github: Can I see the number of downloads for a repo?

I had made a web app that shows GitHub release statistics in a clean format: https://hanadigital.github.io/grev/

How to delete file from public folder in laravel 5.1

First, you should go to config/filesystems.php and set 'root' => public_path() like so:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => public_path(),
],

Then, you can use Storage::delete($filename);

Python timedelta in years

def age(dob):
    import datetime
    today = datetime.date.today()

    if today.month < dob.month or \
      (today.month == dob.month and today.day < dob.day):
        return today.year - dob.year - 1
    else:
        return today.year - dob.year

>>> import datetime
>>> datetime.date.today()
datetime.date(2009, 12, 1)
>>> age(datetime.date(2008, 11, 30))
1
>>> age(datetime.date(2008, 12, 1))
1
>>> age(datetime.date(2008, 12, 2))
0

Checking if jquery is loaded using Javascript

A quick way is to run a jQuery command in the developer console. On any browser hit F12 and try to access any of the element .

 $("#sideTab2").css("background-color", "yellow");

enter image description here

Best way to compare dates in Android

SimpleDateFormat sdf=new SimpleDateFormat("d/MM/yyyy");
Date date=null;
Date date1=null;
try {
       date=sdf.parse(startDate);
       date1=sdf.parse(endDate);
    }  catch (ParseException e) {
              e.printStackTrace();
    }
if (date1.after(date) && date1.equals(date)) {
//..do your work..//
}

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

EasyPHP is very good :

  • lightweight & portable : no windows service (like wamp)
  • easy to configure (all configuration files in the same folder : httpd.conf, php.ini & my.ini)
  • auto restarts apache when you edit httpd.conf

WAMP or UWAMP are good choices if you need to test with multiples versions of PHP and Apache.

But you can also use multiple versions of PHP with EasyPHP (by downloading the PHP version you need on php.net, and loading this version by editing httpd.conf) :

LoadModule php4_module "${path}/php4/php4apache2_2.dll"

How do I export (and then import) a Subversion repository?

Assuming you have the necessary privileges to run svnadmin, you need to use the dump and load commands.

Git push error pre-receive hook declined

I solved this issue by changing remote 'origin' url from http to git protocol in .git/config

Are one-line 'if'/'for'-statements good Python style?

This is an example of "if else" with actions.

>>> def fun(num):
    print 'This is %d' % num
>>> fun(10) if 10 > 0 else fun(2)
this is 10
OR
>>> fun(10) if 10 < 0 else 1
1

Make a phone call programmatically

Probably the mymobileNO.titleLabel.text value doesn't include the scheme tel://

Your code should look like this:

NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

Where are the python modules stored?

On Windows machine python modules are located at (system drive and python version may vary):

C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Lib

How do I change the text of a span element using JavaScript?

Using innerHTML is SO NOT RECOMMENDED. Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.

document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!

The right way:

span = document.getElementById("myspan");
txt = document.createTextNode("your cool text");
span.appendChild(txt);

For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP

Edited nov 4th 2017:

Modified third line of code according to @mumush suggestion: "use appendChild(); instead".
Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.

Changing the width of Bootstrap popover

To change the popover width you may override the template:

$('#name').popover({
    template: '<div class="popover" role="tooltip" style="width: 500px;"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"><div class="data-content"></div></div></div>'
})

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I got the same problem and I just added the content of ~/.ssh/id_rsa.pub to my account in GitHub. After that just try again git push origin master, it should work.

Is there a performance difference between i++ and ++i in C?

From Efficiency versus intent by Andrew Koenig :

First, it is far from obvious that ++i is more efficient than i++, at least where integer variables are concerned.

And :

So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use i++ instead of ++i, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.

So, if the resulting value is not used, I would use ++i. But not because it is more efficient: because it correctly states my intent.

Postgres "psql not recognized as an internal or external command"

Always better to install a previous version or in the installation make sure you specify the '/data' in a separate directory folder "C:\data"

How can I check if given int exists in array?

int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));

Returns an invalid index (length of the array) if not found.

Javascript setInterval not working

Change setInterval("func",10000) to either setInterval(funcName, 10000) or setInterval("funcName()",10000). The former is the recommended method.

default select option as blank

If you don't need any empty option at first, try this first line:

    <option style="display:none"></option>

Content is not allowed in Prolog SAXParserException

This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client. In one of my xsd it was defined as below

<xs:import schemaLocation="" namespace="http://MultiChoice.PaymentService/DataContracts" />

Where the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.

<xs:import schemaLocation="multichoice.paymentservice.DataContracts.xsd" namespace="http://MultiChoice.PaymentService/DataContracts" />

Transpose a range in VBA

First copy the source range then paste-special on target range with Transpose:=True, short sample:

Option Explicit

Sub test()
  Dim sourceRange As Range
  Dim targetRange As Range

  Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(5, 1))
  Set targetRange = ActiveSheet.Cells(6, 1)

  sourceRange.Copy
  targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub

The Transpose function takes parameter of type Varaiant and returns Variant.

  Sub transposeTest()
    Dim transposedVariant As Variant
    Dim sourceRowRange As Range
    Dim sourceRowRangeVariant As Variant

    Set sourceRowRange = Range("A1:H1") ' one row, eight columns
    sourceRowRangeVariant = sourceRowRange.Value
    transposedVariant = Application.Transpose(sourceRowRangeVariant)

    Dim rangeFilledWithTransposedData As Range
    Set rangeFilledWithTransposedData = Range("I1:I8") ' eight rows, one column
    rangeFilledWithTransposedData.Value = transposedVariant
  End Sub

I will try to explaine the purpose of 'calling transpose twice'. If u have row data in Excel e.g. "a1:h1" then the Range("a1:h1").Value is a 2D Variant-Array with dimmensions 1 to 1, 1 to 8. When u call Transpose(Range("a1:h1").Value) then u get transposed 2D Variant Array with dimensions 1 to 8, 1 to 1. And if u call Transpose(Transpose(Range("a1:h1").Value)) u get 1D Variant Array with dimension 1 to 8.

First Transpose changes row to column and second transpose changes the column back to row but with just one dimension.

If the source range would have more rows (columns) e.g. "a1:h3" then Transpose function just changes the dimensions like this: 1 to 3, 1 to 8 Transposes to 1 to 8, 1 to 3 and vice versa.

Hope i did not confuse u, my english is bad, sorry :-).

SyntaxError: Cannot use import statement outside a module

I had this problem in a fledgling Express API project.

The offending server code in src/server/server.js:

import express from 'express';
import {initialDonationItems, initialExpenditureItems} from "./DemoData";

const server = express();

server.get('/api/expenditures', (req, res) => {
  res.type('json');
  res.send(initialExpenditureItems);
});

server.get('/api/donations', (req, res) => {
  res.type('json');
  res.send(initialDonationItems);
});

server.listen(4242, () => console.log('Server is running...'));

Here were my dependencies:

{
  "name": "contributor-api",
  "version": "0.0.1",
  "description": "A Node backend to provide storage services",
  "scripts": {
    "dev-server": "nodemon --exec babel-node src/server/server.js --ignore dist/",
    "test": "jest tests"
  },
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.9.6",
    "@babel/node": "^7.8.7",
    "babel-loader": "^8.1.0",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.7",
    "sequelize-cli": "^5.5.1"
  },
  "devDependencies": {
    "jest": "^25.5.4",
    "nodemon": "^2.0.3"
  }
}

And here was the runner that threw the error:

nodemon --exec babel-node src/server/server.js --ignore dist

This was frustrating, as I had a similar Express project that worked fine.

The solution was firstly to add this dependency:

npm install @babel/preset-env

And then to wire it in using a babel.config.js in the project root:

module.exports = {
  presets: ['@babel/preset-env'],
};

I don't fully grok why this works, but I copied it from an authoritative source, so I am happy to stick with it.

Apply global variable to Vuejs

If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

Python speed testing - Time Difference - milliseconds

Arrow: Better dates & times for Python

import arrow
start_time = arrow.utcnow()
end_time = arrow.utcnow()
(end_time - start_time).total_seconds()  # senconds
(end_time - start_time).total_seconds() * 1000  # milliseconds

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

Bootstrap Datepicker - Months and Years Only

For the latest bootstrap-datepicker (1.4.0 at the time of writing), you need to use this:

$('#myDatepicker').datepicker({
    format: "mm/yyyy",
    startView: "year", 
    minViewMode: "months"
})

Source: Bootstrap Datepicker Options

Loop backwards using indices in Python?

In my opinion, this is the most readable:

for i in reversed(xrange(101)):
    print i,

How to send PUT, DELETE HTTP request in HttpURLConnection?

Even Rest Template can be an option :

String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<RequestDAO>....";
    RestTemplate rest = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/xml");
    headers.add("Accept", "*/*");
    HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
    ResponseEntity<String> responseEntity =
            rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);

     responseEntity.getBody().toString();

Cannot access wamp server on local network

go Setting -> General and change url in WordPress Address (URL) and Site Address (URL)

enter your pc name or your ip address in place of localhost

before : http://localhost/wordpress-test

after : http://your-pc-name/wordpress-test

...and that's it..you can access wordpress from any pc in your LAN...!!!

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Get the distance between two geo points

An approximated solution (based on an equirectangular projection), much faster (it requires only 1 trig and 1 square root).

This approximation is relevant if your points are not too far apart. It will always over-estimate compared to the real haversine distance. For example it will add no more than 0.05382 % to the real distance if the delta latitude or longitude between your two points does not exceed 4 decimal degrees.

The standard formula (Haversine) is the exact one (that is, it works for any couple of longitude/latitude on earth) but is much slower as it needs 7 trigonometric and 2 square roots. If your couple of points are not too far apart, and absolute precision is not paramount, you can use this approximate version (Equirectangular), which is much faster as it uses only one trigonometric and one square root.

// Approximate Equirectangular -- works if (lat1,lon1) ~ (lat2,lon2)
int R = 6371; // km
double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
double y = (lat2 - lat1);
double distance = Math.sqrt(x * x + y * y) * R;

You can optimize this further by either:

  1. Removing the square root if you simply compare the distance to another (in that case compare both squared distance);
  2. Factoring-out the cosine if you compute the distance from one master point to many others (in that case you do the equirectangular projection centered on the master point, so you can compute the cosine once for all comparisons).

For more info see: http://www.movable-type.co.uk/scripts/latlong.html

There is a nice reference implementation of the Haversine formula in several languages at: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

Use ISNULL(field, 0) It can also be used with aggregates:

ISNULL(count(field), 0)

However, you might consider changing count(field) to count(*)

Edit:

try:

closedcases = ISNULL(
   (select count(closed) from ticket       
    where assigned_to = c.user_id and closed is not null       
    group by assigned_to), 0), 

opencases = ISNULL(
    (select count(closed) from ticket 
     where assigned_to = c.user_id and closed is null 
     group by assigned_to), 0),

Wait until flag=true

Because javascript in a browser is single threaded (except for webworkers which aren't involved here) and one thread of javascript execution runs to completion before another can run, your statement:

while(flag==false) {}

will simply run forever (or until the browser complains about a non-responsive javascript loop), the page will appear to be hung and no other javascript will ever get a chance to run, thus the flag's value can never be changed.

For a little more explanation, Javascript is an event driven language. That means that it runs a piece of Javascript until it returns control back to the interpreter. Then, only when it returns back to the interpreter, Javascript gets the next event from the event queue and runs it.

All things like timers and network events run through the event queue. So, when a timer fires or a network request arrives, it does not ever "interrupt" the currently running Javascript. Instead, an event gets put in the Javascript event queue and then, when the currently running Javascript finishes, the next event is pulled from the event queue and it gets its turn to run.

So, when you do an infinite loop such as while(flag==false) {}, the currently running Javascript never finishes and thus the next event is never pulled from the event queue and thus the value of flag never gets changed. They key here is that Javascript is not interrupt driven. When a timer fires, it does not interrupt the currently running Javascript, run some other Javascript and then let the currently running Javascript continue. It just gets put in the event queue waiting until the currently running Javascript is done to get its turn to run.


What you need to do is rethink how your code works and find a different way to trigger whatever code you want to run when the flag value changes. Javascript is designed as an event-driven language. So, what you need to do is figure out what events you can register an interest in so you can either listen for the event that might cause the flag to change and you can examine the flag on that event or you can trigger your own event from whatever code might change the flag or you can implement a callback function that whatever code changes that flag can call your callback whenever the piece of code responsible for changing the flag value would change it's value to true, it just calls the callback function and thus your code that wants to run when the flag gets set to true will get to run at the right time. This is much, much more efficient than trying to use some sort of timer to constantly check the flag value.

function codeThatMightChangeFlag(callback) {
    // do a bunch of stuff
    if (condition happens to change flag value) {
        // call the callback to notify other code
        callback();
    }
}

What is the pythonic way to unpack tuples?

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

Leaflet - How to find existing markers, and delete markers?

you have to put your "var marker" out of the function. Then later you can access it :

var marker;
function onMapClick(e) {
        marker = new L.Marker(e.latlng, {draggable:true});
        map.addLayer(marker);
        marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
};

then later :

map.removeLayer(marker)

But you can only have the latest marker that way, because each time, the var marker is erased by the latest. So one way to go is to create a global array of marker, and you add your marker in the global array.

Internal Error 500 Apache, but nothing in the logs?

Check your php error log which might be a separate file from your apache error log.

Find it by going to phpinfo() and check for error_log attribute. If it is not set. Set it: https://stackoverflow.com/a/12835262/445131

Maybe your post_max_size is too small for what you're trying to post, or one of the other max memory settings is too low.

Export table data from one SQL Server to another

Just to show yet another option (for SQL Server 2008 and above):

  1. right-click on Database -> select 'Tasks' -> select 'Generate Scripts'
  2. Select specific database objects you want to copy. Let's say one or more tables. Click Next
  3. Click Advanced and scroll down to 'Types of Data to script' and choose 'Schema and Data'. Click OK
  4. Choose where to save generated script and proceed by clicking Next

Best solution to protect PHP code without encryption

If you can't create a "cloud app" that you host yourself and they access via the Web, then you could look into creating a virtual appliance using a virtual server (from VMWare, Parallels, Sun, etc) and install a "lite" version of Linux on that. Put your PHP code in the virtual environment and install the virtual machine on their server. Make sure to create a way to prevent loading into root. Of course, this would involve physically visiting the client yourself.

SQL Call Stored Procedure for each Row without using a cursor

In case the order is important

--declare counter
DECLARE     @CurrentRowNum BIGINT = 0;
--Iterate over all rows in [DataTable]
WHILE (1 = 1)
    BEGIN
        --Get next row by number of row
        SELECT TOP 1 @CurrentRowNum = extendedData.RowNum
                    --here also you can store another values
                    --for following usage
                    --@MyVariable = extendedData.Value
        FROM    (
                    SELECT 
                        data.*
                        ,ROW_NUMBER() OVER(ORDER BY (SELECT 0)) RowNum
                    FROM [DataTable] data
                ) extendedData
        WHERE extendedData.RowNum > @CurrentRowNum
        ORDER BY extendedData.RowNum

        --Exit loop if no more rows
        IF @@ROWCOUNT = 0 BREAK;

        --call your sproc
        --EXEC dbo.YOURSPROC @MyVariable
    END

Copy/Paste from Excel to a web page

In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:

http://jsfiddle.net/duwood/sTX7y/

HTML

<p>Paste excel data here:</p>  
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
    <p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>

JS

function generateTable() {
    var data = $('textarea[name=excel_data]').val();
    console.log(data);
    var rows = data.split("\n");

    var table = $('<table />');

    for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);
}

How to stop app that node.js express 'npm start'

If you've already tried ctrl + c and it still doesn't work, you might want to try this. This has worked for me.

  1. Run command-line as an Administrator. Then run the command below to find the processID (PID) you want to kill. Type your port number in <yourPortNumber>

    netstat -ano | findstr :<yourPortNumber>

enter image description here

  1. Then you execute this command after you have identified the PID.

    taskkill /PID <typeYourPIDhere> /F

enter image description here

Kudos to @mit $ingh from http://www.callstack.in/tech/blog/windows-kill-process-by-port-number-157

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

How can I put a database under git (version control)?

I say don't. Data can change at any given time. Instead you should only commit data models in your code, schema and table definitions (create database and create table statements) and sample data for unit tests. This is kinda the way that Laravel does it, committing database migrations and seeds.

TypeError: unsupported operand type(s) for -: 'list' and 'list'

You can't subtract a list from a list.

>>> [3, 7] - [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

Simple way to do it is using numpy:

>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])

You can also use list comprehension, but it will require changing code in the function:

>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]

>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
...     n = len(Array)
...     for column in xrange(n-1):
...         for row in xrange(column+1, n):
...             xmult = Array[row][column] / Array[column][column]
...             Array[row][column] = xmult
...             #print Array[row][col]
...             for col in xrange(0, n):
...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
...             b[row] = b[row]-xmult*b[column]
...     print Array
...     print b
...     return Array, b  # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
...                   np.array([[6],[7]]))
[[ 2  3]
 [-2 -1]]
[[ 6]
 [-5]]
(array([[ 2,  3],
       [-2, -1]]), array([[ 6],
       [-5]]))

gcc-arm-linux-gnueabi command not found

fixed, using:

sudo apt-get install gcc-arm*

How do I use Wget to download all images into a single folder, from a URL?

wget utility retrieves files from World Wide Web (WWW) using widely used protocols like HTTP, HTTPS and FTP. Wget utility is freely available package and license is under GNU GPL License. This utility can be install any Unix-like Operating system including Windows and MAC OS. It’s a non-interactive command line tool. Main feature of Wget is it’s robustness. It’s designed in such way so that it works in slow or unstable network connections. Wget automatically start download where it was left off in case of network problem. Also downloads file recursively. It’ll keep trying until file has be retrieved completely.

Install wget in linux machine sudo apt-get install wget

Create a folder where you want to download files . sudo mkdir myimages cd myimages

Right click on the webpage and for example if you want image location right click on image and copy image location. If there are multiple images then follow the below:

If there are 20 images to download from web all at once, range starts from 0 to 19.

wget http://joindiaspora.com/img{0..19}.jpg

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

How to restrict SSH users to a predefined set of commands after login?

What you are looking for is called Restricted Shell. Bash provides such a mode in which users can only execute commands present in their home directories (and they cannot move to other directories), which might be good enough for you.

I've found this thread to be very illustrative, if a bit dated.

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(use find_or_initialize_by if you don't want to save the record right away)

Edit: The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

and

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

Example

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

became

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Formatting a number with exactly two decimals in JavaScript

Here's a TypeScript implementation of https://stackoverflow.com/a/21323330/916734. It also dries things up with functions, and allows for a optional digit offset.

export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
  const value = Number(rawValue);
  if (isNaN(value)) return rawValue;

  precision = Number(precision);
  if (precision % 1 !== 0) return NaN;

  let [ stringValue, exponent ] = scientificNotationToParts(value);

  let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
  const enlargedValue = toScientificNotation(stringValue, shiftExponent);
  const roundedValue = Math.round(enlargedValue);

  [ stringValue, exponent ] = scientificNotationToParts(roundedValue);
  const precisionWithOffset = precision + fractionDigitOffset;
  shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);

  return toScientificNotation(stringValue, shiftExponent);
}

enum Shift {
  Left = -1,
  Right = 1,
}

function scientificNotationToParts(value: number): Array<string> {
  const [ stringValue, exponent ] = value.toString().split('e');
  return [ stringValue, exponent ];
}

function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
  precision = shift * precision;
  return exponent ? (Number(exponent) + precision) : precision;
}

function toScientificNotation(value: string, exponent: number): number {
  return Number(`${value}e${exponent}`);
}

CSS: How to align vertically a "label" and "input" inside a "div"?

_x000D_
_x000D_
div {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    height: 50px;_x000D_
    border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <label for='name'>Name:</label>_x000D_
    <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

Creating an instance using the class name and calling constructor

If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");

// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();

// Since it is private, make it accessible.
cons.setAccessible(true);

// Create new object. 
Object obj = cons.newInstance();

This only works for classes that implement singleton pattern using a private constructor.

GIT vs. Perforce- Two VCS will enter... one will leave

We have been using Git for sometime, recently our Git server's harddrive crashed and we could not revert back to the latest state. We managed to get back to few days old state. When the server was back up. Everyone in the team pulled/pushed their changes and voila, the server is back to current state.

Java finished with non-zero exit value 2 - Android Gradle

In my case, the problem was that the new library (gradle dependency) that I had added was relying on some other dependencies and two of those underlying dependencies were conflicting/clashing with some dependencies of other libraries/dependencies in my build script. Specifically, I added Apache Commons Validator (for email validation), and two of its dependencies (Apache Commons Logging and Apache Commons Collections) were conflicting with those used by Robolectric (because different versions of same libraries were present in my build path). So I excluded those conflicting versions of dependencies (modules) when adding the new dependency (the Validator):

compile ('commons-validator:commons-validator:1.4.1') {
    exclude module: 'commons-logging'
    exclude module: 'commons-collections'
}

You can see the dependencies of your gradle module(s) (you might have only one module in your project) using the following gradle command (I use the gradle wrapper that gets created for you if you have created your project in Android Studio/Intellij Idea). Run this command in your project's root directory:

./gradlew :YOUR-MODULE-NAME:dependencies

After adding those exclude directives and retrying to run, I got a duplicate file error for NOTICE.txtthat is used by some apache commons libraries like Logging and Collections. I had to exclude that text file when packaging. In my build.gradle, I added:

packagingOptions {
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/NOTICE.txt'
}

It turned out that the new library (the Validator) can work with slightly older versions of its dependencies/modules (which are already imported into my build path by another library (Robolectric)). This was the case with this specific library, but other libraries might be using the latest API of the underlying dependencies (in which case you have to try to see if the other libraries that rely on the conflicting module/dependency are able to work with the newer version (by excluding the older version of the module/dependecy under those libraries's entries)).

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

You will want to use a CONVERT() statement.

Try the following;

SELECT CONVERT(VARCHAR(10), SA.[RequestStartDate], 103) as 'Service Start Date', CONVERT(VARCHAR(10), SA.[RequestEndDate], 103) as 'Service End Date', FROM (......) SA WHERE.....

See MSDN Cast and Convert for more information.

Renaming files using node.js

For linux/unix OS, you can use the shell syntax

const shell = require('child_process').execSync ; 

const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;

shell(`mv ${currentPath} ${newPath}`);

That's it!

Method with a bool return

I'm sure neither of these options were available in C# when you asked the question but nowadays you can do it like the following:

// Return with ternary conditional operator.
private bool CheckAll()
{
    return (your_condition) ? true : false;
}

// Alternatively as an expression bodied method.
private bool CheckAll() => (your_condition) ? true : false;

How do I get a value of a <span> using jQuery?

     $('span id').text(); worked with me

How to describe "object" arguments in jsdoc?

If a parameter is expected to have a specific property, you can document that property by providing an additional @param tag. For example, if an employee parameter is expected to have name and department properties, you can document it as follows:

/**
 * Assign the project to a list of employees.
 * @param {Object[]} employees - The employees who are responsible for the project.
 * @param {string} employees[].name - The name of an employee.
 * @param {string} employees[].department - The employee's department.
 */
function(employees) {
    // ...
}

If a parameter is destructured without an explicit name, you can give the object an appropriate one and document its properties.

/**
 * Assign the project to an employee.
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */
Project.prototype.assign = function({ name, department }) {
    // ...
};

Source: JSDoc

Download an SVN repository?

If you have proxy i suggest using SVNGITDownloader it is under .NET Framework and its source code is available

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I call ::CreateProcess in c++ to launch a Windows executable?

Bear in mind that using WaitForSingleObject can get you into trouble in this scenario. The following is snipped from a tip on my website:

The problem arises because your application has a window but isn't pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST), then the SendMessage won't return to the new application until all applications have handled the message - but your app can't handle the message because it isn't pumping messages.... so the new app locks up, so your wait never succeeds.... DEADLOCK.

If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.

The only safe ways round this are:

  1. split off the Wait into a separate thread, or
  2. use a timeout on the Wait and use PeekMessage in your Wait loop to ensure that you pump messages, or
  3. use the MsgWaitForMultipleObjects API.

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

java.lang.ClassNotFoundException: HttpServletRequest

I do have same problem when i was trying out with first Spring MVC webapp . What i had done was downloaded the jar files given from the link(Download spring framework). Among the jars on the zip extracted folder,the jar files I was expected to use were

  • org.springframework.asm-3.0.1.RELEASE-A.jar

  • org.springframework.beans-3.0.1.RELEASE-A.jar

  • org.springframework.context-3.0.1.RELEASE-A.jar

  • org.springframework.core-3.0.1.RELEASE-A.jar

  • org.springframework.expression-3.0.1.RELEASE-A.jar

  • org.springframework.web.servlet-3.0.1.RELEASE-A.jar

  • org.springframework.web-3.0.1.RELEASE-A.jar

But as I get the Error, looking out for solution, I figured out that I also need the following jar too.

  • commons-logging-1.0.4.jar

  • jstl-1.2.jar

Then I searched and downloaded the two jar files separately and include them in /WEB-INF/lib folder. And finally I was able to get my webapp running using the Tomcat server. :)

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

How do I evenly add space between a label and the input field regardless of length of text?

This can be accomplished using the brand new CSS display: grid (browser support)

HTML:

<div class='container'>
  <label for="dummy1">title for dummy1:</label>
  <input id="dummy1" name="dummy1" value="dummy1">
  <label for="dummy2">longer title for dummy2:</label>
  <input id="dummy2" name="dummy2" value="dummy2">
  <label for="dummy3">even longer title for dummy3:</label>
  <input id="dummy3" name="dummy3" value="dummy3">
</div>

CSS:

.container {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.

grid

JS-FIDDLE

Remove HTML tags from a String

Remove HTML tags from string. Somewhere we need to parse some string which is received by some responses like Httpresponse from the server.

So we need to parse it.

Here I will show how to remove html tags from string.

    // sample text with tags

    string str = "<html><head>sdfkashf sdf</head><body>sdfasdf</body></html>";



    // regex which match tags

    System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");



    // replace all matches with empty strin

    str = rx.Replace(str, "");



    //now str contains string without html tags

Meaning of "[: too many arguments" error from if [] (square brackets)

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).

How to use z-index in svg elements?

You can use use.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
    <use xlink:href="#one" />
</svg>

The green circle appears on top.
jsFiddle

What is a CSRF token? What is its importance and how does it work?

Cross-Site Request Forgery (CSRF) in simple words

  • Assume you are currently logged into your online banking at www.mybank.com
  • Assume a money transfer from mybank.com will result in a request of (conceptually) the form http://www.mybank.com/transfer?to=<SomeAccountnumber>;amount=<SomeAmount>. (Your account number is not needed, because it is implied by your login.)
  • You visit www.cute-cat-pictures.org, not knowing that it is a malicious site.
  • If the owner of that site knows the form of the above request (easy!) and correctly guesses you are logged into mybank.com (requires some luck!), they could include on their page a request like http://www.mybank.com/transfer?to=123456;amount=10000 (where 123456 is the number of their Cayman Islands account and 10000 is an amount that you previously thought you were glad to possess).
  • You retrieved that www.cute-cat-pictures.org page, so your browser will make that request.
  • Your bank cannot recognize this origin of the request: Your web browser will send the request along with your www.mybank.com cookie and it will look perfectly legitimate. There goes your money!

This is the world without CSRF tokens.

Now for the better one with CSRF tokens:

  • The transfer request is extended with a third argument: http://www.mybank.com/transfer?to=123456;amount=10000;token=31415926535897932384626433832795028841971.
  • That token is a huge, impossible-to-guess random number that mybank.com will include on their own web page when they serve it to you. It is different each time they serve any page to anybody.
  • The attacker is not able to guess the token, is not able to convince your web browser to surrender it (if the browser works correctly...), and so the attacker will not be able to create a valid request, because requests with the wrong token (or no token) will be refused by www.mybank.com.

Result: You keep your 10000 monetary units. I suggest you donate some of that to Wikipedia.

(Your mileage may vary.)

EDIT from comment worth reading:

It would be worthy to note that script from www.cute-cat-pictures.org normally does not have access to your anti-CSRF token from www.mybank.com because of HTTP access control. This note is important for some people who unreasonably send a header Access-Control-Allow-Origin: * for every website response without knowing what it is for, just because they can't use the API from another website.

Remove object from a list of objects in python

del array[0]

where 0 is the index of the object in the list (there is no array in python)

How to remove unused C/C++ symbols with GCC and ld?

You can use strip binary on object file(eg. executable) to strip all symbols from it.

Note: it changes file itself and don't create copy.

Reading entire html file to String?

As Jean mentioned, using a StringBuilder instead of += would be better. But if you're looking for something simpler, Guava, IOUtils, and Jsoup are all good options.

Example with Guava:

String content = Files.asCharSource(new File("/path/to/mypage.html"), StandardCharsets.UTF_8).read();

Example with IOUtils:

InputStream in = new URL("/path/to/mypage.html").openStream();
String content;

try {
   content = IOUtils.toString(in, StandardCharsets.UTF_8);
 } finally {
   IOUtils.closeQuietly(in);
 }

Example with Jsoup:

String content = Jsoup.parse(new File("/path/to/mypage.html"), "UTF-8").toString();

or

String content = Jsoup.parse(new File("/path/to/mypage.html"), "UTF-8").outerHtml();

NOTES:

Files.readLines() and Files.toString()

These are now deprecated as of Guava release version 22.0 (May 22, 2017). Files.asCharSource() should be used instead as seen in the example above. (version 22.0 release diffs)

IOUtils.toString(InputStream) and Charsets.UTF_8

Deprecated as of Apache Commons-IO version 2.5 (May 6, 2016). IOUtils.toString should now be passed the InputStream and the Charset as seen in the example above. Java 7's StandardCharsets should be used instead of Charsets as seen in the example above. (deprecated Charsets.UTF_8)

Java 32-bit vs 64-bit compatibility

Yes to the first question and no to the second question; it's a virtual machine. Your problems are probably related to unspecified changes in library implementation between versions. Although it could be, say, a race condition.

There are some hoops the VM has to go through. Notably references are treated in class files as if they took the same space as ints on the stack. double and long take up two reference slots. For instance fields, there's some rearrangement the VM usually goes through anyway. This is all done (relatively) transparently.

Also some 64-bit JVMs use "compressed oops". Because data is aligned to around every 8 or 16 bytes, three or four bits of the address are useless (although a "mark" bit may be stolen for some algorithms). This allows 32-bit address data (therefore using half as much bandwidth, and therefore faster) to use heap sizes of 35- or 36-bits on a 64-bit platform.

Pythonic way to find maximum value and its index in a list?

Here is a complete solution to your question using Python's built-in functions:

# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",") 

# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers] 

# Loop through the list with a for-loop

for elements in numberL:
    maxEle = max(numberL)
    indexMax = numberL.index(maxEle)

print(maxEle)
print(indexMax)

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How to set an environment variable from a Gradle build?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.

enter image description here

Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.

How do I get user IP address in django?

Alexander's answer is great, but lacks the handling of proxies that sometimes return multiple IP's in the HTTP_X_FORWARDED_FOR header.

The real IP is usually at the end of the list, as explained here: http://en.wikipedia.org/wiki/X-Forwarded-For

The solution is a simple modification of Alexander's code:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

In general I would recommend against calling the event handlers 'manually'.

  • It's unclear what gets executed because of multiple registered listeners
  • Danger to get into a recursive and infinite event-loop (click A triggering Click B, triggering click A, etc.)
  • Redundant updates to the DOM
  • Hard to distinguish actual changes in the view caused by the user from changes made as initialisation code (which should be run only once).

Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.

How to check if a file is a valid image file?

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

sed command with -i option failing on Mac, but works on Linux

Insead of calling sed with sed, I do ./bin/sed

And this is the wrapper script in my ~/project/bin/sed

#!/bin/bash

if [[ "$OSTYPE" == "darwin"* ]]; then
  exec "gsed" "$@"
else
  exec "sed" "$@"
fi

Don't forget to chmod 755 the wrapper script.

OpenSSL Command to check if a server is presenting a certificate

15841:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:
...
SSL handshake has read 0 bytes and written 121 bytes

This is a handshake failure. The other side closes the connection without sending any data ("read 0 bytes"). It might be, that the other side does not speak SSL at all. But I've seen similar errors on broken SSL implementation, which do not understand newer SSL version. Try if you get a SSL connection by adding -ssl3 to the command line of s_client.

bootstrap 3 navbar collapse button not working

I had a similar problem. Looked over the html several times and was sure it was correct. Then I started playing around with the order of jquery and bootstrap javascript.

Originally I had bootstrap.min.js loading BEFORE jquery.min.js. In this state, the menu would not expand when clicking on the menu icon.

Then I changed the order so that bootstrap.min.js came after jquery.min.js, and this solved the problem. I don't know enough about javascript to explain why this caused the problem (or fixed it), but that is what worked for me.

Additional info:

Both scripts are located at the bottom of the page, just before the tag. Both scripts are hosted on CDNs, not locally hosted.

If you're pretty sure your code is correct, give this a try.

Data-frame Object has no Attribute

I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.

Double precision floating values in Python?

For some applications you can use Fraction instead of floating-point numbers.

>>> from fractions import Fraction
>>> Fraction(1, 3**54)
Fraction(1, 58149737003040059690390169)

(For other applications, there's decimal, as suggested out by the other responses.)

Scroll to element on click in Angular 4

You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.

On the view(html file)

<div id="target"> </div>
<button (click)="scroll()">Button</button>
 

  

on the .ts file,

scroll() {
   document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

Export to csv/excel from kibana

To export data to csv/excel from Kibana follow the following steps:-

  1. Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.

  2. Click on caret symbol (^) which is present at the bottom of the visualization.

  3. Then you will get an option of Export:Raw Formatted as the bottom of the page.

Please find below attached image showing Export option after clicking on caret symbol.

Please find below attached image showing Export option after clicking on caret symbol.

What's the best way to calculate the size of a directory in .NET?

Multi thread example to calculate directory size from Microsoft Docs, which would be faster

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      long totalSize = 0;

      String[] args = Environment.GetCommandLineArgs();
      if (args.Length == 1) {
         Console.WriteLine("There are no command line arguments.");
         return;
      }
      if (! Directory.Exists(args[1])) {
         Console.WriteLine("The directory does not exist.");
         return;
      }

      String[] files = Directory.GetFiles(args[1]);
      Parallel.For(0, files.Length,
                   index => { FileInfo fi = new FileInfo(files[index]);
                              long size = fi.Length;
                              Interlocked.Add(ref totalSize, size);
                   } );
      Console.WriteLine("Directory '{0}':", args[1]);
      Console.WriteLine("{0:N0} files, {1:N0} bytes", files.Length, totalSize);
   }
}
// The example displaysoutput like the following:
//       Directory 'c:\windows\':
//       32 files, 6,587,222 bytes

This example only calculate the files in current folder, so if you want to calculate all the files recursively, you can change the

String[] files = Directory.GetFiles(args[1]);

to

String[] files = Directory.GetFiles(args[1], "*", SearchOption.AllDirectories);

How to add System.Windows.Interactivity to project?

Sometimes, when you add a new library, in introduces a clashing version of System.Windows.Interactivity.dll.

For example, the NuGet package MVVM light might require v4.2 of System.Windows.Interactivity.dll, but the NuGet package Rx-XAML might require v4.5 of System.Windows.Interactivity.dll. This will prevent the the project from working, because no matter which version of System.Windows.Interactivity.dll you include, one of the libraries will refuse to compile.

To fix, add an Assembly Binding Redirect by editing your app.config to look something like this:

<?xml version="1.0"?>
<configuration>
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Windows.Interactivity"
                        publicKeyToken="31bf3856ad364e35"
                        culture="neutral"/>
      <bindingRedirect oldVersion="4.0.0.0"
                       newVersion="4.5.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
<appSettings>
  <add key="TestKey" value="true"/>
</appSettings>

Don't worry about changing the PublicKeyToken, that's constant across all versions, as it depends on the name of the .dll, not the version.

Ensure that you match the newVersion in your appConfig to the actual version that you end up pointing at:

enter image description here

How to draw a dotted line with css?

To do this, you simple need to add a border-top or border-bottom to your <hr/> tag as the following:

<hr style="border-top: 2px dotted navy" />

with any line type or color you want

Gradle task - pass arguments to Java application

Sorry for answering so late.

I figured an answer alike to @xlm 's:

task run (type: JavaExec, dependsOn: classes){
    if(project.hasProperty('myargs')){
        args(myargs.split(','))
    }
    description = "Secure algorythm testing"
    main = "main.Test"
    classpath = sourceSets.main.runtimeClasspath
}

And invoke like:

gradle run -Pmyargs=-d,s

Set background image according to screen resolution

I've had this same issue but have now found the resolution for it.

The trick is to create a wallpaper image of 1920*1200. When you then apply this wallpaper to the different machines, Windows 7 automatically resizes for best fit.

Hope this helps you all

Access parent's parent from javascript object

JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example:

var Bobby = {name: "Bobby"};
var Dad = {name: "Dad", children: [ Bobby ]};
var Mom = {name: "Mom", children: [ Bobby ]};

Who does Bobby belong to?

how to use concatenate a fixed string and a variable in Python

I'm guessing that you meant to do this:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use       ^ 

Count Rows in Doctrine QueryBuilder

You can also get the number of data by using the count function.

$query = $this->dm->createQueryBuilder('AppBundle:Items')
                    ->field('isDeleted')->equals(false)
                    ->getQuery()->count();

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

I am just adding this answer for an awkward situation from DB provider.

what happened in our case is the primary and secondary db shifted reversely (primary to secondary and vice versa) and we are getting the same error.

so please check in the configuration settings for database status which may help you.

"Please try running this command again as Root/Administrator" error when trying to install LESS

npm has an official page about fixing npm permissions when you get the EACCES (Error: Access) error. The page even has a video.

You can fix this problem using one of two options:

  1. Change the permission to npm's default directory.
  2. Change npm's default directory to another directory.

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

C# equivalent of C++ map<string,double>

Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection

Logging levels - Logback - rule-of-thumb to assign log levels

I mostly build large scale, high availability type systems, so my answer is biased towards looking at it from a production support standpoint; that said, we assign roughly as follows:

  • error: the system is in distress, customers are probably being affected (or will soon be) and the fix probably requires human intervention. The "2AM rule" applies here- if you're on call, do you want to be woken up at 2AM if this condition happens? If yes, then log it as "error".

  • warn: an unexpected technical or business event happened, customers may be affected, but probably no immediate human intervention is required. On call people won't be called immediately, but support personnel will want to review these issues asap to understand what the impact is. Basically any issue that needs to be tracked but may not require immediate intervention.

  • info: things we want to see at high volume in case we need to forensically analyze an issue. System lifecycle events (system start, stop) go here. "Session" lifecycle events (login, logout, etc.) go here. Significant boundary events should be considered as well (e.g. database calls, remote API calls). Typical business exceptions can go here (e.g. login failed due to bad credentials). Any other event you think you'll need to see in production at high volume goes here.

  • debug: just about everything that doesn't make the "info" cut... any message that is helpful in tracking the flow through the system and isolating issues, especially during the development and QA phases. We use "debug" level logs for entry/exit of most non-trivial methods and marking interesting events and decision points inside methods.

  • trace: we don't use this often, but this would be for extremely detailed and potentially high volume logs that you don't typically want enabled even during normal development. Examples include dumping a full object hierarchy, logging some state during every iteration of a large loop, etc.

As or more important than choosing the right log levels is ensuring that the logs are meaningful and have the needed context. For example, you'll almost always want to include the thread ID in the logs so you can follow a single thread if needed. You may also want to employ a mechanism to associate business info (e.g. user ID) to the thread so it gets logged as well. In your log message, you'll want to include enough info to ensure the message can be actionable. A log like " FileNotFound exception caught" is not very helpful. A better message is "FileNotFound exception caught while attempting to open config file: /usr/local/app/somefile.txt. userId=12344."

There are also a number of good logging guides out there... for example, here's an edited snippet from JCL (Jakarta Commons Logging):

  • error - Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
  • warn - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
  • info - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
  • debug - detailed information on the flow through the system. Expect these to be written to logs only.
  • trace - more detailed information. Expect these to be written to logs only.

How to check if curl is enabled or disabled

Hope this helps.

<?php
    function _iscurl() {
        return function_exists('curl_version');
    }
?>

What does it mean by select 1 from table?

Although it is not widely known, a query can have a HAVING clause without a GROUP BY clause.

In such circumstances, the HAVING clause is applied to the entire set. Clearly, the SELECT clause cannot refer to any column, otherwise you would (correct) get the error, "Column is invalid in select because it is not contained in the GROUP BY" etc.

Therefore, a literal value must be used (because SQL doesn't allow a resultset with zero columns -- why?!) and the literal value 1 (INTEGER) is commonly used: if the HAVING clause evaluates TRUE then the resultset will be one row with one column showing the value 1, otherwise you get the empty set.

Example: to find whether a column has more than one distinct value:

SELECT 1
  FROM tableA
HAVING MIN(colA) < MAX(colA);

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

Dive right it, make it a hobby, and have fun :)

Coming from an electronics background myself I can tell you that you should pick it up pretty quickly. And having an electronics background will give you a deeper understanding of the underlying hardware.

IMHO the root of information technology is electronics.

For example..

Think of objects as components.

The .NET framework is essentially drawers full of standard components.

For example you know what a 7400 (NAND gate) is capable of doing. You have a data sheet showing the pin outs and sample configurations. You don't typically care about the circuitry inside. Software objects are the same way. We have inputs and we have methods that do something to the inputs to produce predictable outputs. As developers we typically don't care how the object was written... just that it does what it says it will do.

You also know that you can build additional logic circuits by using two or more NAND gates. This of this as instantiation.

You also know that you can take a NAND gate and place it inside a circuit where you can modify the input signals coming in so the outputs have different behaviors. This is a crude example but you can think of this as inheritance.

I have also learned it helps to have a project to work on. It could be a hobbyist project or a work project. Start small, get something very basic working, and work up from there.

To answer your specific question on "what should I learn first".

1) Take your project you have in mind and break it into steps. For example... get a number from the user, add one to the number, display the result. Think of this as your design.

2) Learn basic C#. Write a simple console application that does something. Learn what an if statement is (this is all boolean logic so it should be somewhat familiar), learn about loops, learn about mathematical operations, learn about functions (subroutines). Play with simple file i/o (reading and writing text files). The basic C# can be thought of as your wiring and discrete components (resistors, caps, transistors, etc) to your chips (object).

3) Learn how to instantiate and use objects from the framework. You have already been doing this but now it's time to delve in further. For example... play with System.Console some more... try making the speaker beep. Also start looking for objects that you may want to use for database work.

4) Learn basic SQL. Lots of help and examples online. Pick a database you want to work with. I personally think MS Access is a great beginners database. I would not use it for multi-user or cross platform desktop applications... but it is a great single user database for Windows users... and it is a great way to learn the basics of SQL. There are other simple free databases available (Open Office has one for example) if you don't want to shell out $ for Access.

5) Expand your app to do something with a database.

Remove row lines in twitter bootstrap

Add this to your main CSS:

table td {
    border-top: none !important;
}

Use this for newer versions of bootstrap:

.table th, .table td { 
     border-top: none !important; 
 }

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Array functions in jQuery

Look into the jQuery functions .grep() and .map()

How to test an Oracle Stored Procedure with RefCursor return type?

create or replace procedure my_proc(  v_number IN number,p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
     from dual;
 end;
 /

and then write a function lie this which calls your stored procedure

 create or replace function my_proc_test(v_number IN NUMBER) RETURN sys_refcursor
 as
 p_rc sys_refcursor;
 begin
 my_proc(v_number,p_rc);
 return p_rc;
 end
 /

then you can run this SQL query in the SQLDeveloper editor.

 SELECT my_proc_test(3) FROM DUAL;

you will see the result in the console right click on it and cilck on single record view and edit the result you can see the all the records that were returned by the ref cursor.

Table 'performance_schema.session_variables' doesn't exist

As sixty4bit question, if your mysql root user looks to be misconfigured, try to install the configurator extension from mysql official source:

https://dev.mysql.com/downloads/repo/apt/

It will help you to set up a new root user password.

Make sure to update your repository (debian/ubuntu) :

apt-get update

Validation of file extension before uploading file

<script type="text/javascript">

        function file_upload() {
            var imgpath = document.getElementById("<%=FileUpload1.ClientID %>").value;
            if (imgpath == "") {
                alert("Upload your Photo...");
                document.file.word.focus();
                return false;
            }
            else {
                // code to get File Extension..

                var arr1 = new Array;
                arr1 = imgpath.split("\\");
                var len = arr1.length;
                var img1 = arr1[len - 1];
                var filext = img1.substring(img1.lastIndexOf(".") + 1);
                // Checking Extension
                if (filext == "bmp" || filext == "gif" || filext == "png" || filext == "jpg" || filext == "jpeg" ) {
                    alert("Successfully Uploaded...")
                    return false;
                }
                else {
                    alert("Upload Photo with Extension ' bmp , gif, png , jpg , jpeg '");
                    document.form.word.focus();
                    return false;
                }
            }
        }

        function Doc_upload() {
            var imgpath = document.getElementById("<%=FileUpload2.ClientID %>").value;
            if (imgpath == "") {
                alert("Upload Agreement...");
                document.file.word.focus();
                return false;
            }
            else {
                // code to get File Extension..

                var arr1 = new Array;
                arr1 = imgpath.split("\\");
                var len = arr1.length;
                var img1 = arr1[len - 1];
                var filext = img1.substring(img1.lastIndexOf(".") + 1);
                // Checking Extension
                if (filext == "txt" || filext == "pdf" || filext == "doc") {
                    alert("Successfully Uploaded...")
                    return false;
                }
                else {
                    alert("Upload File with Extension ' txt , pdf , doc '");
                    document.form.word.focus();
                    return false;
                }
            }
        }
</script>

How to clear jQuery validation error messages?

I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate.

Here is what I came up with:

  • Clear errors by indicating validation success
  • Call handler for error display
  • Clear all storage of success or errors
  • Reset entire form validation

    Here is what it looks like in code:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
     $('[name]',formElement).each(function(){
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     });
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    }
    //used
    var myForm = document.getElementById("myFormId");
    clearValidation(myForm);
    

    minified as a jQuery extension:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
    //used:
    $("#formId").clearValidation();
    
  • Is ASCII code 7-bit or 8-bit?

    ASCII was indeed originally conceived as a 7-bit code. This was done well before 8-bit bytes became ubiquitous, and even into the 1990s you could find software that assumed it could use the 8th bit of each byte of text for its own purposes ("not 8-bit clean"). Nowadays people think of it as an 8-bit coding in which bytes 0x80 through 0xFF have no defined meaning, but that's a retcon.

    There are dozens of text encodings that make use of the 8th bit; they can be classified as ASCII-compatible or not, and fixed- or variable-width. ASCII-compatible means that regardless of context, single bytes with values from 0x00 through 0x7F encode the same characters that they would in ASCII. You don't want to have anything to do with a non-ASCII-compatible text encoding if you can possibly avoid it; naive programs expecting ASCII tend to misinterpret them in catastrophic, often security-breaking fashion. They are so deprecated nowadays that (for instance) HTML5 forbids their use on the public Web, with the unfortunate exception of UTF-16. I'm not going to talk about them any more.

    A fixed-width encoding means what it sounds like: all characters are encoded using the same number of bytes. To be ASCII-compatible, a fixed-with encoding must encode all its characters using only one byte, so it can have no more than 256 characters. The most common such encoding nowadays is Windows-1252, an extension of ISO 8859-1.

    There's only one variable-width ASCII-compatible encoding worth knowing about nowadays, but it's very important: UTF-8, which packs all of Unicode into an ASCII-compatible encoding. You really want to be using this if you can manage it.

    As a final note, "ASCII" nowadays takes its practical definition from Unicode, not its original standard (ANSI X3.4-1968), because historically there were several dozen variations on the ASCII 127-character repertoire -- for instance, some of the punctuation might be replaced with accented letters to facilitate the transmission of French text. Nowadays all of those variations are obsolescent, and when people say "ASCII" they mean that the bytes with value 0x00 through 0x7F encode Unicode codepoints U+0000 through U+007F. This will probably only matter to you if you ever find yourself writing a technical standard.

    If you're interested in the history of ASCII and the encodings that preceded it, start with the paper "The Evolution of Character Codes, 1874-1968" (samizdat copy at http://falsedoor.com/doc/ascii_evolution-of-character-codes.pdf) and then chase its references (many of which are not available online and may be hard to find even with access to a university library, I regret to say).

    How to list the properties of a JavaScript object?

    Object.getOwnPropertyNames(obj)

    This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

    In JS, every property has a few properties, including a boolean enumerable.

    In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

    Example:

    var o = Object.create({base:0})
    Object.defineProperty(o, 'yes', {enumerable: true})
    Object.defineProperty(o, 'not', {enumerable: false})
    
    console.log(Object.getOwnPropertyNames(o))
    // [ 'yes', 'not' ]
    
    console.log(Object.keys(o))
    // [ 'yes' ]
    
    for (var x in o)
        console.log(x)
    // yes, base
    

    Also note how:

    • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
    • for in does

    More about the prototype chain here: https://stackoverflow.com/a/23877420/895245

    CSS to make table 100% of max-width

    You need to use:

        table{
            width:100%;
            table-layout: fixed;
            overflow-wrap: break-word;
        }
    

    Demo

    INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

    I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.

    Despite the checked answer being correct:

    Mike M wrote-

    "The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table."

    What is missing from this answer is simply;

    You must build the table containing the Primary Key first.

    Another way to say it is;

    You must Insert Data into the parent table, containing the Primary Key, before attempting to insert data into the child table containing the Foreign Key.

    In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.

    If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.

    get dataframe row count based on conditions

    For increased performance you should not evaluate the dataframe using your predicate. You can just use the outcome of your predicate directly as illustrated below:

    In [1]: import pandas as pd
            import numpy as np
            df = pd.DataFrame(np.random.randn(20,4),columns=list('ABCD'))
    
    
    In [2]: df.head()
    Out[2]:
              A         B         C         D
    0 -2.019868  1.227246 -0.489257  0.149053
    1  0.223285 -0.087784 -0.053048 -0.108584
    2 -0.140556 -0.299735 -1.765956  0.517803
    3 -0.589489  0.400487  0.107856  0.194890
    4  1.309088 -0.596996 -0.623519  0.020400
    
    In [3]: %time sum((df['A']>0) & (df['B']>0))
    CPU times: user 1.11 ms, sys: 53 µs, total: 1.16 ms
    Wall time: 1.12 ms
    Out[3]: 4
    
    In [4]: %time len(df[(df['A']>0) & (df['B']>0)])
    CPU times: user 1.38 ms, sys: 78 µs, total: 1.46 ms
    Wall time: 1.42 ms
    Out[4]: 4
    

    Keep in mind that this technique only works for counting the number of rows that comply with your predicate.

    Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

    To replace with dashes, do the following:

    text.replace(/[\W_-]/g,' ');
    

    Windows could not start the Apache2 on Local Computer - problem

    if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the "Show processes from all users" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.

    What's the best way to break from nested loops in JavaScript?

    Just like Perl,

    loop1:
        for (var i in set1) {
    loop2:
            for (var j in set2) {
    loop3:
                for (var k in set3) {
                    break loop2;  // breaks out of loop3 and loop2
                }
            }
        }
    

    as defined in EMCA-262 section 12.12. [MDN Docs]

    Unlike C, these labels can only be used for continue and break, as Javascript does not have goto.

    ProgressDialog in AsyncTask

    It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.

    compilation error: identifier expected

    only variable/object declaration statement are written outside of method

    public class details{
        public static void main(String arg[]){
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What is your name?");
            String name = in.readLine(); ;
            System.out.println("Hello " + name);
        }
    }
    

    here is example try to learn java book and see the syntax then try to develop the program

    jQuery: Best practice to populate drop down?

    I hope it helps. I usually use functions instead write all code everytime.

        $("#action_selector").change(function () {
    
            ajaxObj = $.ajax({
                url: 'YourURL',
                type: 'POST', // You can use GET
                data: 'parameter1=value1',
                dataType: "json",
                context: this,                
                success: function (data) {
                    json: data              
                },
                error: function (request) {
                    $(".return-json").html("Some error!");
                }
            });
    
            json_obj = $.parseJSON(ajaxObj.responseText);            
    
            var options = $("#selector");
            options.empty();
            options.append(new Option("-- Select --", 0));
            $.each(ajx_obj, function () {
                options.append(new Option(this.text, this.value));
            });
        });
    });
    

    How to modify a text file?

    If you know some unix you could try the following:

    Notes: $ means the command prompt

    Say you have a file my_data.txt with content as such:

    $ cat my_data.txt
    This is a data file
    with all of my data in it.
    

    Then using the os module you can use the usual sed commands

    import os
    
    # Identifiers used are:
    my_data_file = "my_data.txt"
    command = "sed -i 's/all/none/' my_data.txt"
    
    # Execute the command
    os.system(command)
    

    If you aren't aware of sed, check it out, it is extremely useful.

    How to kill zombie process

    I tried

    kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')
    

    and it works for me.

    Scale image to fit a bounding box

    Note: Even though this is the accepted answer, the answer below is more accurate and is currently supported in all browsers if you have the option of using a background image.

    No, there is no CSS only way to do this in both directions. You could add

    .fillwidth {
        min-width: 100%;
        height: auto;
    }
    

    To the an element to always have it 100% width and automatically scale the height to the aspect ratio, or the inverse:

    .fillheight {
        min-height: 100%; 
        width: auto;
    }
    

    to always scale to max height and relative width. To do both, you will need to determine if the aspect ratio is higher or lower than it's container, and CSS can't do this.

    The reason is that CSS does not know what the page looks like. It sets rules beforehand, but only after that it is that the elements get rendered and you know exactly what sizes and ratios you're dealing with. The only way to detect that is with JavaScript.


    Although you're not looking for a JS solution I'll add one anyway if someone might need it. The easiest way to handle this with JavaScript is to add a class based on the difference in ratio. If the width-to-height ratio of the box is greater than that of the image, add the class "fillwidth", else add the class "fillheight".

    _x000D_
    _x000D_
    $('div').each(function() {_x000D_
      var fillClass = ($(this).height() > $(this).width()) _x000D_
        ? 'fillheight'_x000D_
        : 'fillwidth';_x000D_
      $(this).find('img').addClass(fillClass);_x000D_
    });
    _x000D_
    .fillwidth { _x000D_
      width: 100%; _x000D_
      height: auto; _x000D_
    }_x000D_
    .fillheight { _x000D_
      height: 100%; _x000D_
      width: auto; _x000D_
    }_x000D_
    _x000D_
    div {_x000D_
      border: 1px solid black;_x000D_
      overflow: hidden;_x000D_
    }_x000D_
    _x000D_
    .tower {_x000D_
      width: 100px;_x000D_
      height: 200px;_x000D_
    }_x000D_
    _x000D_
    .trailer {_x000D_
      width: 200px;_x000D_
      height: 100px;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <div class="tower">_x000D_
      <img src="http://placekitten.com/150/150" />_x000D_
    </div>_x000D_
    <div class="trailer">_x000D_
      <img src="http://placekitten.com/150/150" />_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    how to include js file in php?

    PHP is completely irrelevant for what you are doing. The generated HTML is what counts.

    In your case, you are missing the src attribute. Use

     <script type="text/javascript" src="file.js"></script>