Programs & Examples On #Panic

A condition of the the operating system when its state is so broken that imminent shutdown is preferred.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Mount remount the /
Eg.

  1. mount -o remount,rw /dev/xyz /
  2. sed -i 's/1 1/0 0/' /etc/fstab
  3. sed -i 's/1 2/0 0/' /etc/fstab
  4. reboot

How to secure MongoDB with username and password

Here is a javascript code to add users.

  1. Start mongod with --auth = true

  2. Access admin database from mongo shell and pass the javascript file.

    mongo admin "Filename.js"

    "Filename.js"

    // Adding admin user
    db.addUser("admin_username", " admin_password");
    // Authenticate admin user
    db.auth("admin_username ", " admin_password ");
    // use  database code from java script
    db = db.getSiblingDB("newDatabase");
    // Adding newDatabase database user  
    db.addUser("database_username ", " database_ password ");
    
  3. Now user addition is complete, we can verify accessing the database from mongo shell

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray jsonArray = new JSONArray();

for (loop) {
    JSONObject jsonObj= new JSONObject();
    jsonObj.put("srcOfPhoto", srcOfPhoto);
    jsonObj.put("username", "name"+count);
    jsonObj.put("userid", "userid"+count);

    jsonArray.put(jsonObj.valueToString());
}

JSONObject parameters = new JSONObject();

parameters.put("action", "remove");

parameters.put("datatable", jsonArray );

parameters.put(Constant.MSG_TYPE , Constant.SUCCESS);

Why were you using an Hashmap if what you wanted was to put it into a JSONObject?

EDIT: As per http://www.json.org/javadoc/org/json/JSONArray.html

EDIT2: On the JSONObject method used, I'm following the code available at: https://github.com/stleary/JSON-java/blob/master/JSONObject.java#L2327 , that method is not deprecated.

We're storing a string representation of the JSONObject, not the JSONObject itself

"Too many characters in character literal error"

I faced the same issue. String.Replace('\\.','') is not valid statement and throws the same error. Thanks to C# we can use double quotes instead of single quotes and following works String.Replace("\\.","")

How to install latest version of Node using Brew

  1. node -v will show you the current version.
  2. npm -v will show you the current version.
  3. brew link --overwrite --dry-run node will force the link and overwrite all conflicting files.
  4. brew install node do a fresh installation.
  5. brew update
  6. brew upgrade node
  7. brew link --overwrite node

    or

    brew link node

Node Upgrade Procedure are below

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

Forward declaring an enum in C++

You can wrap the enum in a struct, adding in some constructors and type conversions, and forward declare the struct instead.

#define ENUM_CLASS(NAME, TYPE, VALUES...) \
struct NAME { \
    enum e { VALUES }; \
    explicit NAME(TYPE v) : val(v) {} \
    NAME(e v) : val(v) {} \
    operator e() const { return e(val); } \
    private:\
        TYPE val; \
}

This appears to work: http://ideone.com/TYtP2

How can I get (query string) parameters from the URL in Next.js?

Use router-hook.

You can use the useRouter hook in any component in your application.

https://nextjs.org/docs/api-reference/next/router#userouter

pass Param

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
Or
import Router from 'next/router'

Router.push({
    pathname: '/search',
    query: { keyword: 'this way' },
})

In Component

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()
  console.log(router.query);

  ...
}

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

How to send control+c from a bash script?

You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql

This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.

Can you force Vue.js to reload/re-render?

sorry guys, except page reload method(flickering), none of them works for me (:key didn't worked).

and i found this method from old vue.js forum which is works for me:

https://github.com/vuejs/Discussion/issues/356

<template>
    <div v-if="show">
       <button @click="rerender">re-render</button>
    </div>
</template>
<script>
    export default {
        data(){
            return {show:true}
        },
        methods:{
            rerender(){
                this.show = false
                this.$nextTick(() => {
                    this.show = true
                    console.log('re-render start')
                    this.$nextTick(() => {
                        console.log('re-render end')
                    })
                })
            }
        }
    }
</script>

How to create nonexistent subdirectories recursively using Bash?

$ mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I have solved this issue,

login to server computer where SQL Server is installed get you csv file on server computer and execute your query it will insert the records.

If you will give datatype compatibility issue change the datatype for that column

Send message to specific client with socket.io and node.js

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);
io.clients[sessionID].send()

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

How to fix syntax error, unexpected T_IF error in php?

add semi-colon the line before:

$total_pages = ceil($total_result / $per_page);

How to loop over directories in Linux?

find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"

Select rows having 2 columns equal value

For question 1:

SELECT DISTINCT a.*
  FROM [Table] a
  INNER JOIN
  [Table] b
  ON
  a.C1 <> b.C1 AND a.C2 = b.C2 AND a.C3 = b.C3 AND a.C4 = b.C4

Using an inner join is much more efficient than a subquery because it requires fewer operations, and maintains the use of indexes when comparing the values, allowing the SQL server to better optimize the query before its run. Using appropriate indexes with this query can bring your query down to only n * log(n) rows to compare.

Using a subquery with your where clause or only doing a standard join where C1 does not equal C2 results in a table that has roughly 2 to the power of n rows to compare, where n is the number of rows in the table.

So by using proper indexing with an Inner Join, which only returns records which met the join criteria, we're able to drastically improve the performance. Also note that we return DISTINCT a.*, because this will only return the columns for table a where the join criteria was met. Returning * would return the columns for both a and b where the criteria was met, and not including DISTINCT would result in a duplicate of each row for each time that row row matched another row more than once.

A similar approach could also be performed using CROSS APPLY, which still uses a subquery, but makes use of indexes more efficiently.

An implementation with the keyword USING instead of ON could also work, but the syntax is more complicated to make work because your want to match on rows where C1 does not match, so you would need an additional where clause to filter out matching each row with itself. Also, USING is not compatible/allowed in conjunction with table values in all implementations of SQL, so it's best to stick with ON.

Similarly, for question 2:

SELECT DISTINCT a.*
  FROM [Table] a
  INNER JOIN
  [Table] b
  ON
  a.C1 <> b.C1 AND a.C4 = b.C4

This is essentially the same query as for 1, but because it only wants to know which rows match for C4, we only compare on the rows for C4.

php implode (101) with quotes

Don't know if it's quicker, but, you could save a line of code with your method:

From

$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";

To:

$array = array('lastname', 'email', 'phone');
$comma_separated = "'".implode("','", $array)."'";

Getting CheckBoxList Item values

Try to use this.

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
        {
            if (chBoxListTables.Items[i].Selected)
            {
                string str = chBoxListTables.Items[i].Text;
                MessageBox.Show(str);

                var itemValue = chBoxListTables.Items[i].Value;
            }
        }

The "V" should be in CAPS in Value.

Here is another code example used in WinForm app and runs properly.

        var chBoxList= new CheckedListBox();
        chBoxList.Items.Add(new ListItem("One", "1"));
        chBoxList.Items.Add(new ListItem("Two", "2"));
        chBoxList.SetItemChecked(1, true);

        var checkedItems = chBoxList.CheckedItems;
        var chkText = ((ListItem)checkedItems[0]).Text;
        var chkValue = ((ListItem)checkedItems[0]).Value;
        MessageBox.Show(chkText);
        MessageBox.Show(chkValue);

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

How do I change the default application icon in Java?

Try This write after

initcomponents();

setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));

Convert List to Pandas Dataframe Column

Example:

['Thanks You',
 'Its fine no problem',
 'Are you sure']

code block:

import pandas as pd
df = pd.DataFrame(lst)

Output:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:

df = pd.DataFrame(lst)    
df.columns = ['']

Output will be like this:

0   Thanks You
1   Its fine no problem
2   Are you sure

or

df = pd.DataFrame(lst).to_string(header=False)

But the output will be a list instead of a dataframe:

0           Thanks You
1  Its fine no problem
2         Are you sure

Hope this helps!!

How to get the server path to the web directory in Symfony2 from inside the controller?

My solution is to add this code to the app.php

define('WEB_DIRECTORY', __DIR__);

The problem is that in command line code that uses the constant will break. You can also add the constant to app/console file and the other environment front controllers

Another solution may be add an static method at AppKernel that returns DIR.'/../web/' So you can access everywhere

Windows Bat file optional argument parsing

If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.

REM Get argument values.  If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )

REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name   = %DatabaseName%

How to animate the change of image in an UIImageView?

Vladimir's answer is perfect, but anyone like me who is looking for swift solution

This Solution is Worked for swift version 4.2

var i = 0
    func animation(){
        let name = (i % 2 == 0) ? "1.png" : "2.png"
        myImageView.image = UIImage.init(named: name)
        let transition: CATransition = CATransition.init()
        transition.duration = 1.0
        transition.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
        transition.type = .fade
        myImageView.layer.add(transition, forKey: nil)
        i += 1
    }

You can call this method from anywhere. It will change the image to next one(image) with animation.

For Swift Version 4.0 Use bellow solution

var i = 0
    func animationVersion4(){
        let name = (i % 2 == 0) ? "1.png" : "2.png"
        uiImage.image = UIImage.init(named: name)
        let transition: CATransition = CATransition.init()
        transition.duration = 1.0
        transition.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = kCATransitionFade
        uiImage.layer.add(transition, forKey: nil)
        i += 1
    }

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

AWS EFS vs EBS vs S3 (differences & when to use?)

EBS is simple - block level storage which can be attached to an instance from same AZ, and can survive irrespective of instance life.

However, interesting difference is between EFS and S3, and to identify proper use cases for it.

Cost: EFS is approximately 10 times costly than S3.

Usecases:

  • Whenever we have thousands of instances who needs to process file simultaneously EFS is recommended over S3.
  • Also note that S3 is object based storage while EFS is file based it implies that whenever we have requirement that files are updated continuously (refreshed) we should use EFS.
  • S3 is eventually consistent while EFS is strong consistent. In case you can't afford eventual consistency, you should use EFS

How to select only the first rows for each unique value of a column?

A very simple answer if you say you don't care which address is used.

SELECT
    CName, MIN(AddressLine)
FROM
    MyTable
GROUP BY
    CName

If you want the first according to, say, an "inserted" column then it's a different query

SELECT
    M.CName, M.AddressLine,
FROM
    (
    SELECT
        CName, MIN(Inserted) AS First
    FROM
        MyTable
    GROUP BY
        CName
    ) foo
    JOIN
    MyTable M ON foo.CName = M.CName AND foo.First = M.Inserted

Is Ruby pass by reference or by value?

Is Ruby pass by reference or by value?

Ruby is pass-by-reference. Always. No exceptions. No ifs. No buts.

Here is a simple program which demonstrates that fact:

def foo(bar)
  bar.object_id
end

baz = 'value'

puts "#{baz.object_id} Ruby is pass-by-reference #{foo(baz)} because object_id's (memory addresses) are always the same ;)"

=> 2279146940 Ruby is pass-by-reference 2279146940 because object_id's (memory addresses) are always the same ;)

def bar(babar)
  babar.replace("reference")
end

bar(baz)

puts "some people don't realize it's reference because local assignment can take precedence, but it's clearly pass-by-#{baz}"

=> some people don't realize it's reference because local assignment can take precedence, but it's clearly pass-by-reference

Replacing instances of a character in a string

Turn the string into a list; then you can change the characters individually. Then you can put it back together with .join:

s = 'a;b;c;d'
slist = list(s)
for i, c in enumerate(slist):
    if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text
        slist[i] = ':'
s = ''.join(slist)
print s # prints a:b:c;d

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How to update a single pod without touching other dependencies

You can never get 100% isolation. Because a pod may have some shared dependencies and if you attempt to update your single pod, then it would update the dependencies of other pods as well. If that is ok then:

tl;dr use:

pod update podName

Why? Read below.

  • pod update will NOT respect the podfile.lock. It will override it — pertaining to that single pod
  • pod install will respect the podfile.lock, but will try installing every pod mentioned in the podfile based on the versions its locked to (in the Podfile.lock).

This diagram helps better understand the differences:

enter image description here


The major problem comes from the ~> aka optimistic operator.

Using exact versions in the Podfile is not enough

Some might think that specifying exact versions of their pods in their Podfile, like pod 'A', '1.0.0', is enough to guarantee that every user will have the same version as other people on the team.

Then they might even use pod update, even when just adding a new pod, thinking it would never risk updating other pods because they are fixed to a specific version in the Podfile.

But in fact, that is not enough to guarantee that user1 and user2 in our above scenario will always get the exact same version of all their pods.

One typical example is if the pod A has a dependency on pod A2 — declared in A.podspec as dependency 'A2', '~> 3.0'. In such case, using pod 'A', '1.0.0' in your Podfile will indeed force user1 and user2 to both always use version 1.0.0 of the pod A, but:

  • user1 might end up with pod A2 in version 3.4 (because that was A2's latest version at that time)
  • while when user2 runs pod install when joining the project later, they might get pod A2 in version 3.5 (because the maintainer of A2 might have released a new version in the meantime). That's why the only way to ensure every team member work with the same versions of all the pod on each's the computer is to use the Podfile.lock and properly use pod install vs. pod update.

The above excerpt was all derived from pod install vs. pod update

I also highly recommend watching what does a podfile.lock do

Header set Access-Control-Allow-Origin in .htaccess doesn't work

This should work:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Reusing a PreparedStatement multiple times

The second way is a tad more efficient, but a much better way is to execute them in batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
        }

        statement.executeBatch();
    }
}

You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.

If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (Connection connection = dataSource.getConnection()) {
        connection.setAutoCommit(false);

        try (PreparedStatement statement = connection.prepareStatement(SQL)) {
            // ...

            try {
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    }
}

Difference between Divide and Conquer Algo and Dynamic Programming

The other difference between divide and conquer and dynamic programming could be:

Divide and conquer:

  1. Does more work on the sub-problems and hence has more time consumption.
  2. In divide and conquer the sub-problems are independent of each other.

Dynamic programming:

  1. Solves the sub-problems only once and then stores it in the table.
  2. In dynamic programming the sub-problem are not independent.

Formatting doubles for output in C#

i tried to reproduce your findings, but when I watched 'i' in the debugger it showed up as '6.8999999999999995' not as '6.89999999999999946709' as you wrote in the question. Can you provide steps to reproduce what you saw?

To see what the debugger shows you, you can use a DoubleConverter as in the following line of code:

Console.WriteLine(TypeDescriptor.GetConverter(i).ConvertTo(i, typeof(string)));

Hope this helps!

Edit: I guess I'm more tired than I thought, of course this is the same as formatting to the roundtrip value (as mentioned before).

How to download/upload files from/to SharePoint 2013 using CSOM?

Upload a file

Upload a file to a SharePoint site (including SharePoint Online) using File.SaveBinaryDirect Method:

using (var clientContext = new ClientContext(url))
{
     using (var fs = new FileStream(fileName, FileMode.Open))
     {
         var fi = new FileInfo(fileName);
         var list = clientContext.Web.Lists.GetByTitle(listTitle);
         clientContext.Load(list.RootFolder);
         clientContext.ExecuteQuery();
         var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);

         Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);
     }
}

Download file

Download file from a SharePoint site (including SharePoint Online) using File.OpenBinaryDirect Method:

using (var clientContext = new ClientContext(url))
{

     var list = clientContext.Web.Lists.GetByTitle(listTitle);
     var listItem = list.GetItemById(listItemId);
     clientContext.Load(list);
     clientContext.Load(listItem, i => i.File);
     clientContext.ExecuteQuery();

     var fileRef = listItem.File.ServerRelativeUrl;
     var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
     var fileName = Path.Combine(filePath,(string)listItem.File.Name);
     using (var fileStream = System.IO.File.Create(fileName))
     {                  
          fileInfo.Stream.CopyTo(fileStream);
     }
}

How to error handle 1004 Error with WorksheetFunction.VLookup?

Instead of WorksheetFunction.Vlookup, you can use Application.Vlookup. If you set a Variant equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum in this case - with IsError:

Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant

'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
    MsgBox "no match"
Else
    MsgBox cellNum
End If
End Sub

The Application versions of the VLOOKUP and MATCH functions allow you to test for errors without raising the error. If you use the WorksheetFunction version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application functions, you can avoid that mess.

The above could be further simplified using the IIF function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:

cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)

Consider those methods instead of On Error ... statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo and Resume statements.

Java Loop every minute

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

Docker container will automatically stop after "docker run -d"

if you want to operate on the container, you need to run it in foreground to keep it alive.

Is there a simple way to increment a datetime object one month in Python?

Note: This answer shows how to achieve this using only the datetime and calendar standard library (stdlib) modules - which is what was explicitly asked for. The accepted answer shows how to better achieve this with one of the many dedicated non-stdlib libraries. If you can use non-stdlib libraries, by all means do so for these kinds of date/time manipulations!

How about this?

def add_one_month(orig_date):
    # advance year and month by one month
    new_year = orig_date.year
    new_month = orig_date.month + 1
    # note: in datetime.date, months go from 1 to 12
    if new_month > 12:
        new_year += 1
        new_month -= 12

    new_day = orig_date.day
    # while day is out of range for month, reduce by one
    while True:
        try:
            new_date = datetime.date(new_year, new_month, new_day)
        except ValueError as e:
            new_day -= 1
        else:
            break

    return new_date

EDIT:

Improved version which:

  1. keeps the time information if given a datetime.datetime object
  2. doesn't use try/catch, instead using calendar.monthrange from the calendar module in the stdlib:
import datetime
import calendar

def add_one_month(orig_date):
    # advance year and month by one month
    new_year = orig_date.year
    new_month = orig_date.month + 1
    # note: in datetime.date, months go from 1 to 12
    if new_month > 12:
        new_year += 1
        new_month -= 12

    last_day_of_month = calendar.monthrange(new_year, new_month)[1]
    new_day = min(orig_date.day, last_day_of_month)

    return orig_date.replace(year=new_year, month=new_month, day=new_day)

How to use PHP's password_hash to hash and verify passwords

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

Let's say we have the following input:

$password = $_POST['password'];

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

Then see the output:

var_dump($hashed_password);

As you can see it's hashed. (I assume you did those steps).

Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

Official Reference

IntelliJ - show where errors are

In IntelliJ Idea 2019 you can find scope "Problems" under the "Project" view. Default scope is "Project".

"Problems" scope

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

How to remove components created with Angular-CLI

I tried ng remove component Comp_Name also ng distroy component but it is not yet supported by angular so the best option for now is to manually remove it from the folder structure.

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

If there is not ISNULL() method, you can use this expression instead:

CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END

This works the same as ISNULL(fieldname, 0).

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Why is a div with "display: table-cell;" not affected by margin?

Cause

From the MDN documentation:

[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

In other words, the margin property is not applicable to display:table-cell elements.

Solution

Consider using the border-spacing property instead.

Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

For example:

HTML

<div class="table">
    <div class="row">
        <div class="cell">123</div>
        <div class="cell">456</div>
        <div class="cell">879</div>
    </div>
</div>

CSS

.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}

See jsFiddle demo


Different margin horizontally and vertically

As mentioned by Diego Quirós, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

For example

.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */

How to git commit a single file/directory

If you are in the folder which contains the file

git commit -m 'my notes' ./name_of_file.ext

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

Create thumbnail image

Here is a version based on the accepted answer. It fixes two problems...

  1. Improper disposing of the images.
  2. Maintaining the aspect ratio of the image.

I found this tool to be fast and effective for both JPG and PNG files.

private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
    const int thumbnailSize = 150;
    using (var image = Image.FromFile(imageFileName))
    {
        var imageHeight = image.Height;
        var imageWidth = image.Width;
        if (imageHeight > imageWidth)
        {
            imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
            imageHeight = thumbnailSize;
        }
        else
        {
            imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
            imageWidth = thumbnailSize;
        }

        using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
            //Save off the new thumbnail
            thumb.Save(thumbnailFileName);
    }

    return new FileInfo(thumbnailFileName);
}

How to get cumulative sum

Late answer but showing one more possibility...

Cumulative Sum generation can be more optimized with the CROSS APPLY logic.

Works better than the INNER JOIN & OVER Clause when analyzed the actual query plan ...

/* Create table & populate data */
IF OBJECT_ID('tempdb..#TMP') IS NOT NULL
DROP TABLE #TMP 

SELECT * INTO #TMP 
FROM (
SELECT 1 AS id
UNION 
SELECT 2 AS id
UNION 
SELECT 3 AS id
UNION 
SELECT 4 AS id
UNION 
SELECT 5 AS id
) Tab


/* Using CROSS APPLY 
Query cost relative to the batch 17%
*/    
SELECT   T1.id, 
         T2.CumSum 
FROM     #TMP T1 
         CROSS APPLY ( 
         SELECT   SUM(T2.id) AS CumSum 
         FROM     #TMP T2 
         WHERE    T1.id >= T2.id
         ) T2

/* Using INNER JOIN 
Query cost relative to the batch 46%
*/
SELECT   T1.id, 
         SUM(T2.id) CumSum
FROM     #TMP T1
         INNER JOIN #TMP T2
                 ON T1.id > = T2.id
GROUP BY T1.id

/* Using OVER clause
Query cost relative to the batch 37%
*/
SELECT   T1.id, 
         SUM(T1.id) OVER( PARTITION BY id)
FROM     #TMP T1

Output:-
  id       CumSum
-------   ------- 
   1         1
   2         3
   3         6
   4         10
   5         15

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

How can I add a new column and data to a datatable that already contains data?

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

Is there a way to return a list of all the image file names from a folder using only Javascript?

No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.

If you want to use AJAX, the easiest way will be to utilise jQuery:

$.post("someScript.php", function(data) {
   console.log(data); //"data" contains whatever someScript.php returned
});

How to do a redirect to another route with react-router?

The simplest solution is:

import { Redirect } from 'react-router';

<Redirect to='/componentURL' />

Regex to match string containing two names in any order

You can do:

\bjack\b.*\bjames\b|\bjames\b.*\bjack\b

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Add an image in a WPF button

I found that I also had to set the Access Modifier in the Resources tab to 'Public' - by default it was set to Internal and my icon only appeared in design mode but not when I ran the application.

What is the difference between JSF, Servlet and JSP?

Jsp is also having in built servlet code which don't need any external compilation it can be run directly run. Changes will take effect in jsp directly in a browser.

Servlet need to be compiled (i.e it will have specific class creation)

Jsf is a view component of MVC Framework

Is there any way to change input type="date" format?

As said, the <input type=date ... > is not fully implemented in most browsers, so let's talk about webkit like browsers (chrome).

Using linux, you can change it by changing the environment variable LANG, LC_TIME don't seems to work(for me at least).

You can type locale in a terminal to see your current values. I think the same concept can be applied to IOS.

eg: Using:

LANG=en_US.UTF-8 /opt/google/chrome/chrome

The date is showed as mm/dd/yyyy

Using:

LANG=pt_BR /opt/google/chrome/chrome

The date is showed as dd/mm/yyyy

You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR by your locale) to create you own custom locale and format your dates as you want.

A nice more advanced reference on how change default system date is: https://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/ and https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale

You can see you real current date format using date:

$ date +%x
01-06-2015

But as LC_TIME and d_fmt seems to be rejected by chrome ( and I think it's a bug in webkit or chrome ), sadly it don't work. :'(

So, unfortunately the response, is IF LANG environment variable do not solve your problem, there is no way yet.

scipy.misc module has no attribute imread?

In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0

$ pip uninstall scipy

$ pip install scipy==1.1.0

No module named Image

It is changed to : from PIL.Image import core as image for new versions.

How can I "reset" an Arduino board?

I had this issue as well. I tried the above methods and none seemed to work, however something that did work (somehow, not sure if it was just a freak thing or it is actually a way to do it) was:

  1. Unplug USB from the Arduino
  2. Press and hold the reset button
  3. Plug in USB and power up
  4. Continue holding and upload the sketch. Once it's done uploading, release the reset button.

Javascript - How to extract filename from a file input control

var pieces = str.split('\\');
var filename = pieces[pieces.length-1];

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

java.nio.file.Path for a classpath resource

You can not create URI from resources inside of the jar file. You can simply write it to the temp file and then use it (java8):

Path path = File.createTempFile("some", "address").toPath();
Files.copy(ClassLoader.getSystemResourceAsStream("/path/to/resource"), path, StandardCopyOption.REPLACE_EXISTING);

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

Capture HTML Canvas as gif/jpg/png/pdf?

if you want to emebed the canvas you can use this snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id=canvas width=200 height=200></canvas>
    <iframe id='img' width=200 height=200></iframe>
    <script>
        window.onload = function() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            context.fillStyle = "green";
            context.fillRect(50, 50, 100, 100);
            document.getElementById('img').src = canvas.toDataURL("image/jpeg");
            console.log(canvas.toDataURL("image/jpeg"));
        }
    </script>
</body>
</html>

Update React component every second

@Waisky suggested:

You need to use setInterval to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

If you'd like to do the same thing, using Hooks:

const [time, setTime] = useState(Date.now());

useEffect(() => {
  const interval = setInterval(() => setTime(Date.now()), 1000);
  return () => {
    clearInterval(interval);
  };
}, []);

Regarding the comments:

You don't need to pass anything inside []. If you pass time in the brackets, it means run the effect every time the value of time changes, i.e., it invokes a new setInterval every time, time changes, which is not what we're looking for. We want to only invoke setInterval once when the component gets mounted and then setInterval calls setTime(Date.now()) every 1000 seconds. Finally, we invoke clearInterval when the component is unmounted.

Note that the component gets updated, based on how you've used time in it, every time the value of time changes. That has nothing to do with putting time in [] of useEffect.

How to build minified and uncompressed bundle with webpack?

You can define two entry points in your webpack configuration, one for your normal js and the other one for minified js. Then you should output your bundle with its name, and configure UglifyJS plugin to include min.js files. See the example webpack configuration for more details:

module.exports = {
 entry: {
   'bundle': './src/index.js',
   'bundle.min': './src/index.js',
 },

 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: "[name].js"
 },

 plugins: [
   new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      minimize: true
   })
 ]
};

After running webpack, you will get bundle.js and bundle.min.js in your dist folder, no need for extra plugin.

SQL Error: ORA-00933: SQL command not properly ended

Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:

update users set dismissal_reason='he can't and don't want' where userid=123

Single quotes in words can't and don't broke the string. In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.

Summary: check your query for double single quotes.

How to sort a dataFrame in python pandas by two or more columns?

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

You need to add a reference to the .NET assembly System.Data.Entity.dll.

Illegal mix of collations error in MySql

Here's how to check which columns are the wrong collation:

SELECT table_schema, table_name, column_name, character_set_name, collation_name

FROM information_schema.columns

WHERE collation_name = 'latin1_general_ci'

ORDER BY table_schema, table_name,ordinal_position; 

And here's the query to fix it:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET latin1 COLLATE 'latin1_swedish_ci';

Link

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.

So they should be exactly equivalent performance wise.

http://dev.mysql.com/doc/refman/5.6/en/insert.html says:

INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.

A more useful statusline in vim?

I currently use this statusbar settings:

set laststatus=2
set statusline=\ %f%m%r%h%w\ %=%({%{&ff}\|%{(&fenc==\"\"?&enc:&fenc).((exists(\"+bomb\")\ &&\ &bomb)?\",B\":\"\")}%k\|%Y}%)\ %([%l,%v][%p%%]\ %)

My complete .vimrc file: http://gabriev82.altervista.org/projects/vim-configuration/

Difference between array_push() and $array[] =

You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.

C++/CLI Converting from System::String^ to std::string

Don't roll your own, use these handy (and extensible) wrappers provided by Microsoft.

For example:

#include <msclr\marshal_cppstd.h>

System::String^ managed = "test";
std::string unmanaged = msclr::interop::marshal_as<std::string>(managed);

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

Type or namespace name does not exist

Delete the .refresh.dll file if you are under source control. Then rebuild. It should work. This worked for me

ROW_NUMBER() in MySQL

I would define a function:

delimiter $$
DROP FUNCTION IF EXISTS `getFakeId`$$
CREATE FUNCTION `getFakeId`() RETURNS int(11)
    DETERMINISTIC
begin
return if(@fakeId, @fakeId:=@fakeId+1, @fakeId:=1);
end$$

then I could do:

select getFakeId() as id, t.* from table t, (select @fakeId:=0) as t2;

Now you don't have a subquery, which you can't have in views.

Can I specify multiple users for myself in .gitconfig?

git aliases (and sections in git configs) to the rescue!

add an alias (from command line):

git config --global alias.identity '! git config user.name "$(git config user.$1.name)"; git config user.email "$(git config user.$1.email)"; :'

then, set, for example

git config --global user.github.name "your github username"
git config --global user.github.email [email protected]

and in a new or cloned repo you can run this command:

git identity github

This solution isn't automatic, but unsetting user and email in your global ~/.gitconfig and setting user.useConfigOnly to true would force git to remind you to set them manually in each new or cloned repo.

git config --global --unset user.name
git config --global --unset user.email
git config --global user.useConfigOnly true

summing two columns in a pandas dataframe

Same think can be done using lambda function. Here I am reading the data from a xlsx file.

import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df

Output:

  cluster Unnamed: 1      date  budget  actual
0       a 2014-01-01  00:00:00   11000   10000
1       a 2014-02-01  00:00:00    1200    1000
2       a 2014-03-01  00:00:00     200     100
3       b 2014-04-01  00:00:00     200     300
4       b 2014-05-01  00:00:00     400     450
5       c 2014-06-01  00:00:00     700    1000
6       c 2014-07-01  00:00:00    1200    1000
7       c 2014-08-01  00:00:00     200     100
8       c 2014-09-01  00:00:00     200     300

Sum two columns into 3rd new one.

df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df

Output:

  cluster Unnamed: 1      date  budget  actual  variance
0       a 2014-01-01  00:00:00   11000   10000     21000
1       a 2014-02-01  00:00:00    1200    1000      2200
2       a 2014-03-01  00:00:00     200     100       300
3       b 2014-04-01  00:00:00     200     300       500
4       b 2014-05-01  00:00:00     400     450       850
5       c 2014-06-01  00:00:00     700    1000      1700
6       c 2014-07-01  00:00:00    1200    1000      2200
7       c 2014-08-01  00:00:00     200     100       300
8       c 2014-09-01  00:00:00     200     300       500

The developers of this app have not set up this app properly for Facebook Login?

after a lot of tries, I've read in other topics which someone said "delete all your apps and create it again". I did that but, as you can imagine, a new App will create a new Application ID on Facebook's page.

So, even after all the "set public things" it didn't work because the application ID was wrong in my code due to the creation of a new App on Facebook developer page.

So, as AndrewSmiley said above, you should remeber to update that in your app @strings

How do I format XML in Notepad++?

OK, here is how I did it in Notepad++:

  • Plugins
  • Plugin manager
  • Show plugin manager
  • Check XML tools
  • Install
  • Restart Notepad++
  • Open XML file
  • Plugins
  • XML tools
  • Pretty print (XML only -- with line breaks)

How the single threaded non blocking IO model works in Node.js

Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.

However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

on ubuntu 18.04 in etc/phpmyadmin/config.inc.php comment all the block

Optional: User for advanced features

sudo echo "something" >> /etc/privilegedFile doesn't work

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

base64 encode in MySQL

I was looking for the same thing and I've just seen that MySQL 5.6 has a couple of new string functions supporting this functionality: TO_BASE64 and FROM_BASE64.

how to get all child list from Firebase android

as Frank said Firebase stores sequence of values in the format of "key": "Value" which is a Map structure

to get List from this sequence you have to

  1. initialize GenericTypeIndicator with HashMap of String and your Object.
  2. get value of DataSnapShot as GenericTypeIndicator into Map.
  3. initialize ArrayList with HashMap values.

GenericTypeIndicator<HashMap<String, Object>> objectsGTypeInd = new GenericTypeIndicator<HashMap<String, Object>>() {};
Map<String, Object> objectHashMap = dataSnapShot.getValue(objectsGTypeInd);
ArrayList<Object> objectArrayList = new ArrayList<Object>(objectHashMap.values());

Works fine for me, Hope it helps.

Copy and paste content from one file to another file in vi

These remaps work like a charm for me:

vmap <C-c> "*y     " Yank current selection into system clipboard
nmap <C-c> "*Y     " Yank current line into system clipboard (if nothing is selected)
nmap <C-v> "*p     " Paste from system clipboard

So, when I'm at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use "*y as well, but I think this is hard to remember sometimes.

This is also useful to copy text from Vim to clipboard.

Source: Copy and paste between sessions using a temporary file

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

How to create custom button in Android using XML Styles

<gradient android:startColor="#ffdd00"
    android:endColor="@color/colorPrimary"
    android:centerColor="#ffff" />

<corners android:radius="33dp"/>

<padding
    android:bottom="7dp"
    android:left="7dp"
    android:right="7dp"
    android:top="7dp"
    />

Is there a MySQL option/feature to track history of changes to records?

You could create triggers to solve this. Here is a tutorial to do so (archived link).

Setting constraints and rules in the database is better than writing special code to handle the same task since it will prevent another developer from writing a different query that bypasses all of the special code and could leave your database with poor data integrity.

For a long time I was copying info to another table using a script since MySQL didn’t support triggers at the time. I have now found this trigger to be more effective at keeping track of everything.

This trigger will copy an old value to a history table if it is changed when someone edits a row. Editor ID and last mod are stored in the original table every time someone edits that row; the time corresponds to when it was changed to its current form.

DROP TRIGGER IF EXISTS history_trigger $$

CREATE TRIGGER history_trigger
BEFORE UPDATE ON clients
    FOR EACH ROW
    BEGIN
        IF OLD.first_name != NEW.first_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'first_name',
                        NEW.first_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

        IF OLD.last_name != NEW.last_name
        THEN
                INSERT INTO history_clients
                    (
                        client_id    ,
                        col          ,
                        value        ,
                        user_id      ,
                        edit_time
                    )
                    VALUES
                    (
                        NEW.client_id,
                        'last_name',
                        NEW.last_name,
                        NEW.editor_id,
                        NEW.last_mod
                    );
        END IF;

    END;
$$

Another solution would be to keep an Revision field and update this field on save. You could decide that the max is the newest revision, or that 0 is the most recent row. That's up to you.

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

Upload folder with subfolders using S3 and the AWS console

Normally I use the Enhanced Uploader available via the AWS management console. However, since that requires Java it can cause problems. I found s3cmd to be a great command-line replacement. Here's how I used it:

s3cmd --configure   # enter access keys, enable HTTPS, etc.
s3cmd sync <path-to-folder> s3://<path-to-s3-bucket>/

How to get last 7 days data from current datetime to last 7 days in sql server

Hope this will help,

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on      
from News    
WHERE CreatedDate >= cast(dateadd(day, -7, GETDATE()) as date)
and CreatedDate < cast(GETDATE()+1 as date) order by CreatedDate desc

Powershell: count members of a AD group

How about this?

Get-ADGroupMember 'Group name' | measure-object | select count

Creating a div element in jQuery

If you are using Jquery > 1.4, you are best of with Ian's answer. Otherwise, I would use this method:

This is very similar to celoron's answer, but I don't know why they used document.createElement instead of Jquery notation.

$("body").append(function(){
        return $("<div/>").html("I'm a freshly created div. I also contain some Ps!")
            .attr("id","myDivId")
            .addClass("myDivClass")
            .css("border", "solid")                 
            .append($("<p/>").html("I think, therefore I am."))
            .append($("<p/>").html("The die is cast."))
});

//Some style, for better demonstration if you want to try it out. Don't use this approach for actual design and layout!
$("body").append($("<style/>").html("p{background-color:blue;}div{background-color:yellow;}div>p{color:white;}"));

I also think using append() with a callback function is in this case more readable, because you now immediately that something is going to be appended to the body. But that is a matter of taste, as always when writing any code or text.

In general, use as less HTML as possible in JQuery code, since this is mostly spaghetti code. It is error prone and hard to maintain, because the HTML-String can easily contain typos. Also, it mixes a markup language (HTML) with a programming language (Javascript/Jquery), which is usually a bad Idea.

Recyclerview and handling different type of row inflation

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

enter image description here

How to do it ?

You can create a RecyclerView with any number of different Views(ViewHolders). But for better readability lets take an example of RecyclerView with two Viewholders.
Remember these 3 simple steps and you will be good to go.

  • Override public int getItemViewType(int position)
  • Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  • Populate View based on the itemViewType in onBindViewHolder() method

    Here is a code snippet for you

    public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    
        private static final int LAYOUT_ONE= 0;
        private static final int LAYOUT_TWO= 1;
    
        @Override
        public int getItemViewType(int position)
        {
            if(position==0)
               return LAYOUT_ONE;
            else
               return LAYOUT_TWO;
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View view =null;
            RecyclerView.ViewHolder viewHolder = null;
    
            if(viewType==LAYOUT_ONE)
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
               viewHolder = new ViewHolderOne(view);
            }
            else
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
               viewHolder= new ViewHolderTwo(view);
            }
    
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    
           if(holder.getItemViewType()== LAYOUT_ONE)
           {
               // Typecast Viewholder 
               // Set Viewholder properties 
               // Add any click listener if any 
           }
           else {
    
               ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
               vaultItemHolder.name.setText(displayText);
               vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       .......
                   }
               });
    
           }
    
       }
    
       /****************  VIEW HOLDER 1 ******************//
    
       public class ViewHolderOne extends RecyclerView.ViewHolder {
    
           public TextView name;
    
           public ViewHolderOne(View itemView) {
           super(itemView);
           name = (TextView)itemView.findViewById(R.id.displayName);
           }
       }
    
    
      //****************  VIEW HOLDER 2 ******************//
    
      public class ViewHolderTwo extends RecyclerView.ViewHolder{
    
           public ViewHolderTwo(View itemView) {
           super(itemView);
    
               ..... Do something
           }
      }
    }
    

GitHub Code:

Here is a project where I have implemented a RecyclerView with multiple ViewHolders.

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

C++ int to byte array

Int to byte and vice versa.

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);


int num = 0;
for(int i = 0; i < 4; i++)
 {
 num <<= 8;
 num |= bytes[i];
 }


printf("number %d",num);

How can I switch to another branch in git?

[git checkout "branch_name"]

is another way to say:

[git checkout -b branch_name origin/branch_name]

in case "branch_name" exists only remotely.

[git checkout -b branch_name origin/branch_name] is useful in case you have multiple remotes.

Regarding [git checkout origin 'another_branch'] I'm not sure this is possible, AFAK you can do this using "fetch" command -- [git fetch origin 'another_branch']

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)

Maven 3 warnings about build.plugins.plugin.version

It's great answer in here. And I want to add 'Why Add a element in Maven3'.
In Maven 3.x Compatibility Notes

Plugin Metaversion Resolution
Internally, Maven 2.x used the special version markers RELEASE and LATEST to support automatic plugin version resolution. These metaversions were also recognized in the element for a declaration. For the sake of reproducible builds, Maven 3.x no longer supports usage of these metaversions in the POM. As a result, users will need to replace occurrences of these metaversions with a concrete version.

And I also find in maven-compiler-plugin - usage

Note: Maven 3.0 will issue warnings if you do not specify the version of a plugin.

PDOException SQLSTATE[HY000] [2002] No such file or directory

I ran into this problem when running PHPUnit in Elixir/Gulp, and Homestead as my Vagrant enviroment.

In my case I edited the .env file from DB_HOST=localhost to DB_HOST=192.168.10.10 where 192.168.10.10 is the IP of my Vagrant/Homestead host.

Where to place and how to read configuration resource files in servlet based application?

You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.

Instead of using properties file, use XML file.

If the data is too small, you can even use web.xml for accessing the properties.

Please note that any of these approach will require app server restart for changes to be reflected.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

OK, this is the problem I had, and, what fixed it, seems very relevant to the above.

I am using Visual Studio 2010 Express. I wrote a test service that didn't really do anything. It was just practice for the real thing later.

I wrote the service and tried to install it using installutil.exe and got the following error:

System.BadImageFormatException: Could not load file or assembly '{filename.exe}' or one of its dependencies. An attempt was made to load a program with an incorrect format.

So far the same as the original author.

Ruben's observation above about the 32 bit output of Visual Studio 2010 was the saviour here.

I used the 64-bit version of the installutil.exe and sure enough, the output of the Visual Studio 2010 build was 32-bit. Just to add a little extra value here, you can find the 32-bit version of the latest .NET framework and the associated installutil.exe in the C:\Windows\Microsoft.NET\framework folder. Using this version of the installutil.exe fixed my problem; the service installed without a hitch!

I hope this helps someone else out there.

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

Raising a number to a power in Java

^ is not the operator you want. You are looking for the pow function of java.lang.Math.

You can use Math.pow(value, power).

Example:

Math.pow(23, 5); // 23 to the fifth power

What's the C++ version of Java's ArrayList

A couple of additional points re use of vector here.

Unlike ArrayList and Array in Java, you don't need to do anything special to treat a vector as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.

Unlike ArrayList, a vector can efficiently hold primitive types without encapsulation as a full-fledged object.

When removing items from a vector, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.

Make sure if you store complex objects in the vector that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.

Advice about reserve()ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.

Questions every good PHP Developer should be able to answer

"Why aren't you using something else?"

Sorry, someone had to say it :)

How to subtract/add days from/to a date?

There is of course a lubridate solution for this:

library(lubridate)
date <- "2009-10-01"

ymd(date) - 5
# [1] "2009-09-26"

is the same as

ymd(date) - days(5)
# [1] "2009-09-26"

Other time formats could be:

ymd(date) - months(5)
# [1] "2009-05-01"

ymd(date) - years(5)
# [1] "2004-10-01"

ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"

How to check type of variable in Java?

I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.

//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);

// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);

// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);

Here is a method:

public static void checkClass (Object obj) {
    Class cls = obj.getClass();
    System.out.println("The type of the object is: " + cls.getSimpleName());       
}

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

Using Laravel Homestead: 'no input file specified'

If your using a new version of larval 7 >= you can use from your homested directory vagrant provision

How to use RecyclerView inside NestedScrollView?

if you want to use RecyclerView in NestedScrollView this is a simple tricky, just set :

RecyclerView

  • recyclerView.setHasFixedSize(false) (java/kt)

  • android:nestedScrollingEnabled="false"

  • android:layout_height="wrap_content"

  • android:overScrollMode="never"

NestedScrollView

  • android:fillViewport="true"

this is work for me, and you can use many RecyclerView in NestedScrollView with this too.

ld.exe: cannot open output file ... : Permission denied

The Best solution is go to console in eclipse IDE and click the red button to terminate the program. You will see the your program is running and output can be seen there. :) !!

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

Adding an item to an associative array

You can simply do this

$data += array($category => $question);

If your're running on php 5.4+

$data += [$category => $question];

How to concatenate strings with padding in sqlite

Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...

SELECT 
  (
    col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
  ) AS my_column 
FROM
  mytable;

Tested on SQLite 3.8.8.3, Thanks!

Bootstrap 3 offset on right not left

Here is the same solution than Rukshan but in sass (in order to keep your grid configuration) for special case that don't work with Ross Allen solution (when you can't have a parent div.row)

@mixin make-grid-offset-right($class) {
    @for $index from 0 through $grid-columns {
        .col-#{$class}-offset-right-#{$index} {
            margin-right: percentage(($index / $grid-columns));
        }
    }
}

@include make-grid-offset-right(xs);

@media (min-width: $screen-sm-min) {
  @include make-grid-offset-right(sm);
}

@media (min-width: $screen-md-min) {
  @include make-grid-offset-right(md);
}

@media (min-width: $screen-lg-min) {
  @include make-grid-offset-right(lg);
}

How to add a named sheet at the end of all Excel sheets?

Try this:

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = "Tempo"
End Sub

Or use a With clause to avoid repeatedly calling out your object

Private Sub CreateSheet()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.Name = "Tempo"
    End With
End Sub

Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.

Sub CreateSheet()
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
    End With
End Sub

Address already in use: JVM_Bind java

Address already in use: JVM_Bind

means that some other application is already listening on the port your current application is trying to bind.

what you need to do is, either change the port for your current application or better; just find out the already running application and kill it.

on Linux you can find the application pid by using,

netstat -tulpn

How do I send a file in Android from a mobile device to server using http?

Easy, you can use a Post request and submit your file as binary (byte array).

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

Android Activity as a dialog

If you need Appcompat Version

style.xml

    <!-- Base application theme. -->
    <style name="AppDialogTheme" parent="Theme.AppCompat.Light.Dialog">
        <!-- Customize your theme here. -->
        <item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>

yourmanifest.xml

    <activity
          android:name=".MyActivity"
          android:label="@string/title"
          android:theme="@style/AppDialogTheme">
    </activity>

Add Facebook Share button to static HTML page

 <div class="fb_share">
     <a name="fb_share" type="box_count" share_url="<?php the_permalink() ?>"
       href="http://www.facebook.com/sharer.php">Partilhar</a>
     <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> </div> <?php }  }

 add_action('thesis_hook_byline_item','fb_share');

PHP: Get the key from an array in a foreach loop

Try this:

foreach($samplearr as $key => $item){
  print "<tr><td>" 
      . $key 
      . "</td><td>"  
      . $item['value1'] 
      . "</td><td>" 
      . $item['value2'] 
      . "</td></tr>";
}

Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

Program "make" not found in PATH

If you are using MinGW toolchain for CDT, make.exe is found at C:\MinGW\msys\1.0\bin

(or search the make.exe in MinGW folder.)

Add this path in eclipse window->preferences->environment

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I got a similar problem.

Due to timeout !

Timeout can be indicated like this :

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => "POST",
        'content' => http_build_query($data2),
        'timeout' => 30,
    ),
);
$context = stream_context_create($options); $retour =
$retour = @file_get_contents("http://xxxxx.xxx/xxxx", false, $context);

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

How to manage startActivityForResult on Android?

Example

To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Add a different request code for every activity you are starting from here
    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) { // Activity.RESULT_OK

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

File size exceeds configured limit (2560000), code insight features not available

Windows default install location for Webstorm:

C:\Program Files\JetBrains\WebStorm 2019.1.3\bin\idea.properties

I went x4 default for intellisense and x5 for file size

(my business workstation is a beast though: 8th gen i7, 32Gb RAM, NVMe PCIE3.0x4 SDD, gloat, etc, gloat, etc)

#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#--------------------------------------------------------------------- 
idea.max.intellisense.filesize=10000

    #---------------------------------------------------------------------
    # Maximum file size (kilobytes) IDE is able to open.
    #--------------------------------------------------------------------- 

idea.max.content.load.filesize=100000

simple HTTP server in Java using only Java SE API

checkout Simple. its a pretty simple embeddable server with built in support for quite a variety of operations. I particularly love its threading model..

Amazing!

Adding rows to tbody of a table using jQuery

I have never ever come across such a strange problem like this! o.O

Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent); and it works like a charm!

No idea why this strange problem occurs!

What is a mutex?

What is a Mutex?

The mutex (In fact, the term mutex is short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section (In critical section multi threads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.

What is a Race Condition?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Real life example:

When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don't hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk.

Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.

@Xetius

Usage in C#:

This example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.

using System;
using System.Threading;

class Example
{
    // Create a new Mutex. The creating thread does not own the mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread newThread = new Thread(new ThreadStart(ThreadProc));
            newThread.Name = String.Format("Thread{0}", i + 1);
            newThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void ThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        Console.WriteLine("{0} is requesting the mutex", 
                          Thread.CurrentThread.Name);
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
                          Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area", 
            Thread.CurrentThread.Name);

        // Release the Mutex.
        mut.ReleaseMutex();
        Console.WriteLine("{0} has released the mutex", 
            Thread.CurrentThread.Name);
    }
}
// The example displays output like the following:
//       Thread1 is requesting the mutex
//       Thread2 is requesting the mutex
//       Thread1 has entered the protected area
//       Thread3 is requesting the mutex
//       Thread1 is leaving the protected area
//       Thread1 has released the mutex
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
//       Thread3 has released the mutex
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       Thread2 has released the mutex

MSDN Reference Mutex

How to remove all .svn directories from my application directories

No need for pipes, xargs, exec, or anything:

find . -name .svn -delete

Edit: Just kidding, evidently -delete calls unlinkat() under the hood, so it behaves like unlink or rmdir and will refuse to operate on directories containing files.

Opening popup windows in HTML

I feel like this is the simplest way. (Feel free to change the width and height values).

<a href="http://www.google.com" 
target="popup" 
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>

adding css file with jquery

Try doing it the other way around.

$('<link rel="stylesheet" href="css/style2.css" type="text/css" />').appendTo('head');

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

Send attachments with PHP Mail()?

This works for me. It also attaches multiple attachments too. easily

<?php

if ($_POST && isset($_FILES['file'])) {
    $recipient_email = "[email protected]"; //recepient
    $from_email = "info@your_domain.com"; //from email using site domain.
    $subject = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if (strlen($sender_name) < 4) {
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email');
    }
    if (strlen($sender_message) < 4) {
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("specialToken$4332"); // boundary token to be used

    if ($file_count > 0) { //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:" . $from_email . "\r\n";
        $headers .= "Reply-To: " . $sender_email . "" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($sender_message));

        //attachments
        for ($x = 0; $x < $file_count; $x++) {
            if (!empty($attachments['name'][$x])) {

                if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                        3 => "The uploaded file was only partially uploaded",
                        4 => "No file was uploaded",
                        6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
                $body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
                $body .= "Content-Transfer-Encoding: base64\r\n";
                $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
                $body .= $encoded_content;
            }
        }
    } else { //send plain email otherwise
        $headers = "From:" . $from_email . "\r\n" .
                "Reply-To: " . $sender_email . "\n" .
                "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if ($sentMail) { //output success or failure messages
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');
    }
}
?>

How to remove undefined and null values from an object using lodash?

I like using _.pickBy, because you have full control over what you are removing:

var person = {"name":"bill","age":21,"sex":undefined,"height":null};

var cleanPerson = _.pickBy(person, function(value, key) {
  return !(value === undefined || value === null);
});

Source: https://www.codegrepper.com/?search_term=lodash+remove+undefined+values+from+object

Iterating through directories with Python

Another way of returning all files in subdirectories is to use the pathlib module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):

from pathlib import Path

rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]

# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]

Since Python 3.5, the glob module also supports recursive file finding:

import os
from glob import iglob

rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]

The file_list from either of the above approaches can be iterated over without the need for a nested loop:

for f in file_list:
    print(f) # Replace with desired operations

What is console.log?

In java scripts there is no input and output functions. So to debug the code console.log() method is used.It is a method for logging. It will be printed under console log (development tools).

Its is not present in IE8 and under until you open IE development tool.

Escape sequence \f - form feed - what exactly is it?

Although recently its use is undefined, a common and useful use for the form feed is to separate sections of code vertically, like so: enter image description here (from http://ergoemacs.org/emacs/emacs_form_feed_section_paging.html)

Can Powershell Run Commands in Parallel?

You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.

# Loop through the server list
Get-Content "ServerList.txt" | %{

  # Define what each job does
  $ScriptBlock = {
    param($pipelinePassIn) 
    Test-Path "\\$pipelinePassIn\c`$\Something"
    Start-Sleep 60
  }

  # Execute the jobs in parallel
  Start-Job $ScriptBlock -ArgumentList $_
}

Get-Job

# Wait for it all to complete
While (Get-Job -State "Running")
{
  Start-Sleep 10
}

# Getting the information back from the jobs
Get-Job | Receive-Job

Find out time it took for a python script to complete execution

import time 

startTime = time.time()
# Your code here !
print ('The script took {0} second !'.format(time.time() - startTime))

The previous code works for me with no problem !

Get event listeners attached to node using addEventListener

Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).

getEventListeners(document)

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

From Save (Not Permitted) Dialog Box on MSDN :

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column <<<<

To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box.

See Also Colt Kwong Blog Entry:
Saving changes is not permitted in SQL 2008 Management Studio

How to set UICollectionViewCell Width and Height programmatically

in Swift3 and Swift4 you can change cell size by adding UICollectionViewDelegateFlowLayout and implementing it's like this :

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }

or if create UICollectionView programmatically you can do it like this :

    let layout = UICollectionViewFlowLayout()
                    layout.scrollDirection = .horizontal //this is for direction
                    layout.minimumInteritemSpacing = 0 // this is for spacing between cells
                    layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height) //this is for cell size
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)

Executing Shell Scripts from the OS X Dock?

Someone wrote...

I just set all files that end in ".sh" to open with Terminal. It works fine and you don't have to change the name of each shell script you want to run.

how to add value to a tuple?

Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

Casting string to enum

Have a look at using something like

Enum.TryParse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

or

Enum.Parse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

How to change the time format (12/24 hours) of an <input>?

Simple HTML trick to get this :

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row" >_x000D_
                       _x000D_
                        <div class="col-md-6">_x000D_
                             <div class="row">_x000D_
                                <div class="col-md-4" >_x000D_
                                       <label for="hours">Hours</label>_x000D_
          <select class="form-control" required>_x000D_
                <option>  </option>_x000D_
                <option value="1"> 1 </option>_x000D_
                <option value="2"> 2 </option>_x000D_
                <option value="3"> 3 </option>_x000D_
                <option value="4"> 4 </option>_x000D_
                <option value="5"> 5 </option>_x000D_
                <option value="6"> 6 </option>_x000D_
                <option value="7"> 7 </option>_x000D_
                <option value="8"> 8 </option>_x000D_
                <option value="9"> 9 </option>_x000D_
                <option value="10"> 10 </option>_x000D_
                <option value="11"> 11 </option>_x000D_
                <option value="12"> 12 </option>_x000D_
              </select>_x000D_
             </div>_x000D_
                <div class="col-md-4" >_x000D_
                      <label for="minutes">Minutes</label>_x000D_
              <select class="form-control" required="">_x000D_
                <option selected disabled>  </option>_x000D_
                <option value="00"> 00 </option>_x000D_
                <option value="10"> 10 </option>_x000D_
                <option value="20"> 20 </option>_x000D_
                <option value="30"> 30 </option>_x000D_
                <option value="40"> 40 </option>_x000D_
                <option value="50"> 50 </option>_x000D_
              </select>_x000D_
             </div>_x000D_
                 <div class="col-md-4" >_x000D_
                       <label for="hours">Select Meridiem</label>_x000D_
              <select class="form-control" required="" >_x000D_
                <option selected="" value="AM"> AM </option>_x000D_
                <option value="PM"> PM </option>_x000D_
              </select>_x000D_
              </div>_x000D_
             </div></div>_x000D_
                    </div>
_x000D_
_x000D_
_x000D_

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

ImportError: No module named requests

If you are using Ubuntu, there is need to install requests

run this command:

pip install requests

if you face permission denied error, use sudo before command:

sudo pip install requests

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

Permission denied on CopyFile in VBS

I've only ever seen CopyFile fail with a "permission denied" error in one of these 3 scenarios:

  • An actual permission problem with either source or destination.
  • Destination path is a folder, but does not have a trailing backslash.
  • Source file is locked by an application.

Simple timeout in java

Use this line of code:

Thread.sleep(1000);

It will sleep for 1 second.

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I was facing the same problem. It works for me. Please check this.

json_encode($array,JSON_UNESCAPED_UNICODE);

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

Why do I always get the same sequence of random numbers with rand()?

You have to seed it. Seeding it with the time is a good idea:

srand()

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) );
  printf ("Random Number: %d\n", rand() %100);
  return 0;
}

You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().

Edit

Due to comments

rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

How do I echo and send console output to a file in a bat script?

If you don't need the output in real time (i.e. as the program is writing it) you could add

type windows-dir.txt

after that line.

How can I see function arguments in IPython Notebook Server 3?

Shift-Tab works for me to view the dcoumentation

Create Word Document using PHP in Linux

real Word documents

If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.

fake HTTP headers for tricking Word into opening raw HTML

A rather common (but unreliable) alternative is:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"

Make sure you don't use external stylesheets. Everything should be in the same file.

Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type header along does not constitute a real file format conversion.

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

Javascript - validation, numbers only

This one worked for me :

function validateForm(){

  var z = document.forms["myForm"]["num"].value;

  if(!/^[0-9]+$/.test(z)){
    alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
  }

}

Truncate Two decimal places without rounding

This is what i did:

        c1 = a1 - b1;
        d1 = Math.Ceiling(c1 * 100) / 100;

subtracting two inputted numbers without rounding up or down the decimals. because the other solutions does not work for me. don't know if it will work for others, i just want to share this :) Hope it works tho for those who's finding solution to a problem similar to mine. Thanks

PS: i'm a beginner so feel free to point out something on this. :D this is good if you're actually dealing with money, cause of the cents right? it only have 2 decimal places and rounding it is a no no.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

Check if password you are using is correct one by running below command

keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit

If you are getting below error then your password is wrong

keytool error: java.security.UnrecoverableKeyException: Cannot recover key

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

What can I use for good quality code coverage for C#/.NET?

C# Test Coverage Tool has very low overhead, handles huge systems of files, intuitive GUI showing coverage on specific files, and generated report with coverage breakdown at method, class, and package levels.

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

cannot open shared object file: No such file or directory

Your LD_LIBRARY_PATH doesn't include the path to libsvmlight.so.

$ export LD_LIBRARY_PATH=/home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PATH

Is there a max array length limit in C++?

i would go around this by making a 2d dynamic array:

long long** a = new long long*[x];
for (unsigned i = 0; i < x; i++) a[i] = new long long[y];

more on this here https://stackoverflow.com/a/936702/3517001

NGinx Default public www location?

The default web folder for nginx depends on how you installed it, but normally it's in these locations:

/usr/local/nginx/html
/usr/nginx/html

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

I've run into this issue when trying to build a fixed positioned sidebar with both vertically scrollable content and nested absolute positioned children to be displayed outside sidebar boundaries.

My approach consisted of separately apply:

  • an overflow: visible property to the sidebar element
  • an overflow-y: auto property to sidebar inner wrapper

Please check the example below or an online codepen.

_x000D_
_x000D_
html {_x000D_
  min-height: 100%;_x000D_
}_x000D_
body {_x000D_
  min-height: 100%;_x000D_
  background: linear-gradient(to bottom, white, DarkGray 80%);_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.sidebar {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  height: 100%;_x000D_
  width: 200px;_x000D_
  overflow: visible;  /* Just apply overflow-x */_x000D_
  background-color: DarkOrange;_x000D_
}_x000D_
_x000D_
.sidebarWrapper {_x000D_
  padding: 10px;_x000D_
  overflow-y: auto;   /* Just apply overflow-y */_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.element {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 100%;_x000D_
  background-color: CornflowerBlue;_x000D_
  padding: 10px;_x000D_
  width: 200px;_x000D_
}
_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
<div class="sidebar">_x000D_
  <div class="sidebarWrapper">_x000D_
    <div class="element">_x000D_
      I'm a sidebar child element but I'm able to horizontally overflow its boundaries._x000D_
    </div>_x000D_
    <p>This is a 200px width container with optional vertical scroll.</p>_x000D_
    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Receiving login prompt using integrated windows authentication

Can be browser related. If you are using IE, you can go to Advanced Settings and check you the "Enable Windows Integrated Authentication" checkbox is checked.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Fastest way to zero out a 2d array in C?

memset(array, 0, sizeof(array[0][0]) * m * n);

Where m and n are the width and height of the two-dimensional array (in your example, you have a square two-dimensional array, so m == n).

String to HashMap JAVA

Assuming no key contains either ',' or ':':

Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
    final String[] parts = entry.split(":");
    assert(parts.length == 2) : "Invalid entry: " + entry;
    map.put(parts[0], new Integer(parts[1]));
}

Defining static const integer members in class definition

Another way to do this, for integer types anyway, is to define constants as enums in the class:

class test
{
public:
    enum { N = 10 };
};

jQuery.each - Getting li elements inside an ul

$(function() {
    $('.phrase .items').each(function(i, items_list){
        var myText = "";

        $(items_list).find('li').each(function(j, li){
            alert(li.text());
        })

        alert(myText);

    });
};

Error: allowDefinition='MachineToApplication' beyond application level

My problem was I had accidentally published my webservice to a pre-completed location on a fresh install of VS2010.

I had published to a folder called PreCompiledWeb, and the presence of the web.config I suspect messed it up.

I simply nuked the folder, and refreshed the project.

When double-clicking this error - it took me to that erroneous web.config file, which tipped me off.

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

I believe the get() function immediately runs the select query and does not accept ORDER BY conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:

$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get(); 
return $query->result();

CodeIgniter Documentation order_by()

How to vertically align text in input type="text"?

IF vertical align won't work use padding. padding-top: 10px; it will shift the text to the bottom or padding-bottom: 10px; to shift the text in the text box to top

adjust the padding size till it suit the size you want. Thats the hack

IN Clause with NULL or IS NULL

I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0

SELECT *
FROM (SELECT CASE WHEN id_field IS NULL 
                THEN 0 
                ELSE id_field 
            END AS id_field
      FROM tbl_name) AS tbl
WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)

How do I ignore a directory with SVN?

Here's an example directory structure:

\project
    \source
    \cache
    \other

When in project you see that your cache directory is not added and shows up as such.

> svn st
M  source
?  cache

To set the ignore property, do

svn propset svn:ignore cache .

where svn:ignore is the name of the property you're setting, cache is the value of the property, and . is the directory you're setting this property on. It should be the parent directory of the cache directory that needs the property.

To check what properties are set:

> svn proplist
Properties on '.':
  svn:ignore

To see the value of svn:ignore:

> svn propget svn:ignore
cache

To delete properties previously set:

svn propdel svn:ignore