Programs & Examples On #Gcc4

Version 4.x of GCC (GNU Compiler Collection). It's the de facto standard C compiler on Linux and supports many other languages and platforms as well.

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

display data from SQL database into php/ html table

refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.

<?php
    $con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT * FROM employee");

    while($row = mysqli_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
      echo "<br />";
      }

    mysqli_close($con);
    ?>

You can similarly echo it inside your table

<?php
 echo "<table>";
 while($row = mysqli_fetch_array($result))
          {
          echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
          }
 echo "</table>";
 mysqli_close($con);
?>

How to Merge Two Eloquent Collections?

Merge two different eloquent collections into one and some objects happen to have the same id, one will overwrite the other. Use push() method instead or rethink your approach to the problem to avoid that. Refer to web

Return None if Dictionary key is not available

A one line solution would be:

item['key'] if 'key' in item else None

This is useful when trying to add dictionary values to a new list and want to provide a default:

eg.

row = [item['key'] if 'key' in item else 'default_value']

Difference between WebStorm and PHPStorm

PhpStorm supports all the features of WebStorm but some are not bundled so you might need to install the corresponding plugin for some framework via Settings > Plugins > Install JetBrains Plugin.

Official comment - jetbrains.com

Selenium C# WebDriver: Wait until element is present

Using the solution provided by Mike Kwan may have an impact in overall testing performance, since the implicit wait will be used in all FindElement calls.

Many times you'll want the FindElement to fail right away when an element is not present (you're testing for a malformed page, missing elements, etc.). With the implicit wait these operations would wait for the whole timeout to expire before throwing the exception. The default implicit wait is set to 0 seconds.

I've written a little extension method to IWebDriver that adds a timeout (in seconds) parameter to the FindElement() method. It's quite self-explanatory:

public static class WebDriverExtensions
{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
    {
        if (timeoutInSeconds > 0)
        {
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }
        return driver.FindElement(by);
    }
}

I didn't cache the WebDriverWait object as its creation is very cheap, this extension may be used simultaneously for different WebDriver objects, and I only do optimizations when ultimately needed.

Usage is straightforward:

var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost/mypage");
var btn = driver.FindElement(By.CssSelector("#login_button"));
btn.Click();
var employeeLabel = driver.FindElement(By.CssSelector("#VCC_VSL"), 10);
Assert.AreEqual("Employee", employeeLabel.Text);
driver.Close();

How can I extract substrings from a string in Perl?

String 1:

$input =~ /'^\S+'/;
$s1 = $&;

String 2:

$input =~ /\(.*\)/;
$s2 = $&;

String 3:

$input =~ /\*?$/;
$s3 = $&;

JUnit tests pass in Eclipse but fail in Maven Surefire

I have the similar problem, but with IntelliJ IDEA + Maven + TestNG + spring-test. (spring-test is essential of course :) ) It was fixed when I've change config of maven-surefire-plugin to disable run tests in parallel. Like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <skipTests>${maven.test.skip}</skipTests>
        <trimStackTrace>false</trimStackTrace>
        <!--<parallel>methods</parallel>-->
        <!-- to skip integration tests -->
        <excludes>
            <exclude>**/IT*Test.java</exclude>
            <exclude>**/integration/*Test.java</exclude>
        </excludes>
    </configuration>
    <executions>
        <execution>
            <id>integration-test</id>
            <phase>integration-test</phase>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <skipTests>${maven.integration-test.skip}</skipTests>
                <!-- Make sure to include this part, since otherwise it is excluding Integration tests -->
                <excludes>
                    <exclude>none</exclude>
                </excludes>
                <includes>
                    <include>**/IT*Test.java</include>
                    <include>**/integration/*Test.java</include>
                </includes>
            </configuration>
        </execution>
    </executions>
</plugin>

How to determine previous page URL in Angular?

@GünterZöchbauer also you can save it in localstorage but I not prefer it ) better to save in service and get this value from there

 constructor(
        private router: Router
      ) {
        this.router.events
          .subscribe((event) => {
            if (event instanceof NavigationEnd) {
              localStorage.setItem('previousUrl', event.url);
            }
          });
      }

How to beautify JSON in Python?

Use the indent argument of the dumps function in the json module.

From the docs:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

How can I build multiple submit buttons django form?

You can use self.data in the clean_email method to access the POST data before validation. It should contain a key called newsletter_sub or newsletter_unsub depending on which button was pressed.

# in the context of a django.forms form

def clean(self):
    if 'newsletter_sub' in self.data:
        # do subscribe
    elif 'newsletter_unsub' in self.data:
        # do unsubscribe

How do I select which GPU to run a job on?

In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.

I.e.:

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...

As saw here.

Button Width Match Parent

The correct solution would be to use the SizedBox.expand widget, which enforces its child to match its parent's size.

SizedBox.expand(
  child: RaisedButton(...),
)

There are many alternatives, which allows for more or less customization:

SizedBox(
  width: double.infinity,
  // height: double.infinity,
  child: RaisedButton(...),
)

or using a ConstrainedBox

ConstrainedBox(
    constraints: const BoxConstraints(minWidth: double.infinity),
    child: RaisedButton(...),
)

HTTP redirect: 301 (permanent) vs. 302 (temporary)

The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.

Its always better to use 302 if you are enabling the redirection for a short maintenance window.

Naming Conventions: What to name a boolean variable?

hasFollowingItems? or hasFollowingXXXXs where XXXX is whatever the item in your list is?

Add a CSS class to <%= f.submit %>

<%= f.submit 'name of button here', :class => 'submit_class_name_here' %>

This should do. If you're getting an error, chances are that you're not supplying the name.

Alternatively, you can style the button without a class:

form#form_id_here input[type=submit]

Try that, as well.

How to disable the ability to select in a DataGridView?

Enabled property to false

or

this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;

How to display and hide a div with CSS?

you can use any of the following five ways to hide element, depends upon your requirements.

Opacity

.hide {
  opacity: 0;
}

Visibility

.hide {
   visibility: hidden;
}

Display

.hide {
   display: none;
}

Position

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

clip-path

.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}

To show use any of the following: opacity: 1; visibility: visible; display: block;

Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/

How to get JSON object from Razor Model object in javascript

Pass the object from controller to view, convert it to markup without encoding, and parse it to json.

@model IEnumerable<CollegeInformationDTO>

@section Scripts{
    <script>
          var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
    </script>
}

Uninstalling an MSI file from the command line without using msiexec

Short answer: you can't. Use MSIEXEC /x

Long answer: When you run the MSI file directly at the command line, all that's happening is that it runs MSIEXEC for you. This association is stored in the registry. You can see a list of associations by (in Windows Explorer) going to Tools / Folder Options / File Types.

For example, you can run a .DOC file from the command line, and WordPad or WinWord will open it for you.

If you look in the registry under HKEY_CLASSES_ROOT\.msi, you'll see that .MSI files are associated with the ProgID "Msi.Package". If you look in HKEY_CLASSES_ROOT\Msi.Package\shell\Open\command, you'll see the command line that Windows actually uses when you "run" a .MSI file.

Android Notification Sound

Another way for the default sound

builder.setDefaults(Notification.DEFAULT_SOUND);

how to create a cookie and add to http response from inside my service layer?

In Spring MVC you get the HtppServletResponce object by default .

   @RequestMapping("/myPath.htm")
    public ModelAndView add(HttpServletRequest request,
         HttpServletResponse response) throws Exception{
            //Do service call passing the response
    return new ModelAndView("CustomerAddView");
    }

//Service code
Cookie myCookie =
  new Cookie("name", "val");
  response.addCookie(myCookie);

How To Remove Outline Border From Input Button

using outline:none; we can remove that border in chrome

<style>
input[type="button"]
{
    width:120px;
    height:60px;
    margin-left:35px;
    display:block;
    background-color:gray;
    color:white;
    border: none;
    outline:none;
}
</style>

How do I get monitor resolution in Python?

Utility script using pynput library. Posting here for ref.:

 
from pynput.mouse import Controller as MouseController

def get_screen_size():
    """Utility function to get screen resolution"""

    mouse = MouseController()

    width = height = 0

    def _reset_mouse_position():
        # Move the mouse to the top left of 
        # the screen
        mouse.position = (0, 0)

    # Reset mouse position
    _reset_mouse_position()

    count = 0
    while 1:
        count += 1
        mouse.move(count, 0)
        
        # Get the current position of the mouse
        left = mouse.position[0]

        # If the left doesn't change anymore, then
        # that's the screen resolution's width
        if width == left:
            # Add the last pixel
            width += 1

            # Reset count for use for height
            count = 0
            break

        # On each iteration, assign the left to 
        # the width
        width = left
    
    # Reset mouse position
    _reset_mouse_position()

    while 1:
        count += 1
        mouse.move(0, count)

        # Get the current position of the mouse
        right = mouse.position[1]

        # If the right doesn't change anymore, then
        # that's the screen resolution's height
        if height == right:
            # Add the last pixel
            height += 1
            break

        # On each iteration, assign the right to 
        # the height
        height = right

    return width, height

>>> get_screen_size()
(1920, 1080)

Can Google Chrome open local links?

It's not really an anwser but a workaround to open a local link in chrome using python.

Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.

import win32clipboard
import os

win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

os.system("start "+clipboard_data)

SELECT from nothing?

For DB2:

`VALUES('Hello world')`

You can do multiple "rows" as well:

`VALUES('Hello world'),('Goodbye world');`

You can even use them in joins as long as the types match:

VALUES(1,'Hello world')
UNION ALL
VALUES(2,'Goodbye world');

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

Had this issue with a cordova / ionic3 app, was caused by forking a main app and not selected again the legacy system in project settings. I selected legacy and the entitlements bs went away.

Popup window in PHP?

For a popup javascript is required. Put this in your header:

<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>

And this in your body:

<input type="button" onclick="myFunction()" value="Show alert box">

When the button is pressed a box pops up with the message set in the header.

This can be put in any html or php file without the php tags.

-----EDIT-----

To display it using php try this:

<?php echo '<script>myfunction()</script>'; ?>

It may not be 100% correct but the principle is the same.

To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.

jquery ui Dialog: cannot call methods on dialog prior to initialization

Try this instead

$(document).ready(function() {
  $("#divDialog").dialog(opt).dialog("open");
});

You can also do:

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

That's because the dialog is not stored in $('#divDialog'), but on a new div that is created on the fly and returned by the .dialog(opt) function.

Calculating how many minutes there are between two times

If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes; will always return (minutesDifference % 60). Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes(in different typecasts):

// Default value that is returned is of type *double* 
double double_minutes = endTime.Subtract(startTime).TotalMinutes; 
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes; 
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes; 
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes; 

What are file descriptors, explained in simple terms?

File Descriptors (FD) :

  • In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files. Every File has an associated number called File Descriptor (FD).
  • Your screen also has a File Descriptor. When a program is executed the output is sent to File Descriptor of the screen, and you see program output on your monitor. If the output is sent to File Descriptor of the printer, the program output would have been printed.

    Error Redirection :
    Whenever you execute a program/command at the terminal, 3 files are always open
    1. standard input
    2. standard output
    3. standard error.

    These files are always present whenever a program is run. As explained before a file descriptor, is associated with each of these files.
    File                                        File Descriptor
    Standard Input STDIN              0
    Standard Output STDOUT       1
    Standard Error STDERR          2

  • For instance, while searching for files, one typically gets permission denied errors or some other kind of errors. These errors can be saved to a particular file.
    Example 1

$ ls mydir 2>errorsfile.txt

The file descriptor for standard error is 2.
If there is no any directory named as mydir then the output of command will be save to file errorfile.txt
Using "2>" we re-direct the error output to a file named "errorfile.txt"
Thus, program output is not cluttered with errors.

I hope you got your answer.

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

How can I commit files with git?

It sounds as if the only problem here is that the default editor that is launched is vi or vim, with which you're not familiar. (As quick tip, to exit that editor without saving changes, hit Esc a few times and then type :, q, ! and Enter.)

There are several ways to set up your default editor, and you haven't indicated which operating system you're using, so it's difficult to recommend one in particular. I'd suggest using:

 git config --global core.editor "name-of-your-editor"

... which sets a global git preference for a particular editor. Alternatively you can set the $EDITOR environment variable.

Getting next element while cycling through a list

For strings list from 1(or whatever > 0) until end.

itens = ['car', 'house', 'moon', 'sun']

v = 0
for item in itens:
    b = itens[1 + v]
    print(b)
    print('any other command')
    if b == itens[-1]:
        print('End')
        break
    v += 1

Count number of columns in a table row

You could do

alert(document.getElementById('table1').rows[0].cells.length)

fiddle here http://jsfiddle.net/TEZ73/

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

Trying to check if username already exists in MySQL database using PHP

TRY THIS ONE

 mysql_connect('localhost','dbuser','dbpass');

$query = "SELECT username FROM Users WHERE username='".$username."'";
mysql_select_db('dbname');

    $result=mysql_query($query);

   if (mysql_num_rows($query) != 0)
   {
     echo "Username already exists";
    }

    else
   {
     ...
    }

How do I verify that a string only contains letters, numbers, underscores and dashes?

As an alternative to using regex you could do it in Sets:

from sets import Set

allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')

if Set(my_little_sting).issubset(allowed_chars):
    # your action
    print True

How to fill 100% of remaining height?

This can be done with tables:

<table cellpadding="0" cellspacing="0" width="100%" height="100%">
    <tr height="0%"><td>
        <div id="full">
            <!--contents of 1 -->
        </div>
    </td></tr>
    <tr><td>
        <div id="someid">
            <!--contents of 2 -->
        </div>
    </td></tr>
</table>

Then apply css to make someid fill the remaining space:

#someid {
    height: 100%;
}

Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.

Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.

But feel free to prove me wrong, of course! CSS is always better.

Import CSV to SQLite

As some websites and other article specifies, its simple have a look to this one. https://www.sqlitetutorial.net/sqlite-import-csv/

We don't need to specify the separator for csv file, becayse csv means comma separated. sqlite> .separator , no need of this line.

sqlite> create table cities(name, population);
sqlite> .mode csv
sqlite> .import c:/sqlite/city_no_header.csv cities

This will work flawlessly :)

PS: My cities.csv with header.


name,population
Abilene,115930
Akron,217074
Albany,93994
Albuquerque,448607
Alexandria,128283
Allentown,106632
Amarillo,173627
Anaheim,328014

How can I quickly delete a line in VIM starting at the cursor position?

D or dd deletes and copies the line to the register. You can use Vx which only deletes the line and stays in the normal mode.

How to Auto-start an Android Application?

You have to add a manifest permission entry:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

(of course you should list all other permissions that your app uses).

Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).

public class BootUpReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
    }
}

Then, add a Receiver class to your manifest file:

<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I had the same issue. And I tried to reset my keys as everyone said, but it still didn't worked. For was because I renamed the app.

So what I did was to reset my keys and also rename app from console. Check this question for more information: Heroku push app problem

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

Bootswatch is a good alternative, but you can also find multiple types of free templates made for ASP.NET MVC that use MDBootstrap (a front-end framework built on top of Bootstrap) here:

ASP.NET MVC MDB Templates

Add "Are you sure?" to my excel button, how can I?

Create a new sub with the following code and assign it to your button. Change the "DeleteProcess" to the name of your code to do the deletion. This will pop up a box with OK or Cancel and will call your delete sub if you hit ok and not if you hit cancel.

Sub AreYouSure()

Dim Sure As Integer

Sure = MsgBox("Are you sure?", vbOKCancel)
If Sure = 1 Then Call DeleteProcess

End Sub

Jesse

WPF chart controls

Also DevExpress have Charts (see DevExpress.Com).

VarBinary vs Image SQL Server Data Type to Store Binary Data?

varbinary(max) is the way to go (introduced in SQL Server 2005)

Adding an identity to an existing column

Basically there are four logical steps.

  1. Create a new Identity column. Turn on Insert Identity for this new column.

  2. Insert the data from the source column (the column you wished to convert to Identity) to this new column.

  3. Turn off the Insert Identity for the new column.

  4. Drop your source column & rename the new column to the name of the source column.

There may be some more complexities like working across multiple servers etc.

Please refer the following article for the steps (using ssms & T-sql). These steps are intended for beginners with less grip on T-SQL.

http://social.technet.microsoft.com/wiki/contents/articles/23816.how-to-convert-int-column-to-identity-in-the-ms-sql-server.aspx

Selected value for JSP drop down using JSTL

In HTML, the selected option is represented by the presence of the selected attribute on the <option> element like so:

<option ... selected>...</option>

Or if you're HTML/XHTML strict:

<option ... selected="selected">...</option>

Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:

request.setAttribute("selectedDept", selectedDept);

then this should do:

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
    </c:forEach>
</select>

See also:

How to create a directory in Java?

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));

How to stretch div height to fill parent div - CSS

I'd solve it with a javascript solution (jQUery) if the sizes can vary.

window.setTimeout(function () {
    $(document).ready(function () {
        var ResizeTarget = $('#B');

        ResizeTarget.resize(function () {
            var target = $('#B2');
            target.css('height', ResizeTarget.height());
        }).trigger('resize');
    }); 
}, 500);

Convert InputStream to BufferedReader

A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:

Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);

Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.

Decoding JSON String in Java

This is the JSON String we want to decode :

{ 
   "stats": { 
       "sdr": "aa:bb:cc:dd:ee:ff", 
       "rcv": "aa:bb:cc:dd:ee:ff", 
       "time": "UTC in millis", 
       "type": 1, 
       "subt": 1, 
       "argv": [
          {"1": 2}, 
          {"2": 3}
       ]}
}

I store this string under the variable name "sJSON" Now, this is how to decode it :)

// Creating a JSONObject from a String 
JSONObject nodeRoot  = new JSONObject(sJSON); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");

Encapsulation vs Abstraction?

Encapsulation - the process of hiding components of the class to prevent direct access from the outside. It is achieved by using "private" modifier to prevent direct access to some class members (data field or method) from other classes or objects meanwhile providing access to these private members by public members (Interface). That make the class members protected as human organs hidden/encapsulated under the skin or some shield.

Abstraction - A principle must be followed in writing OOP program that say "you must include in the class only components that are interesting in the task of the program". For example: the object student has a lot of characters as a human: name, age, weight, hair color, eye color, etc. But, when you create a class in OOP to work with students you should include only those characters that really matter for student database: name, age, specialty, level, marks ... etc. in C++ you can create abstract class by using the modifier "virtual" with any methods in the class and that will make it unusable in direct but you can derive other classes from it and create implementation for its members with adding required members based on the task.

how to set default main class in java?

As a comment, I had to allow a customer to execute a class in a jar which meant that the manifest file couldn't be modified (they couldn't be expected to do that). Thanks to the post by Anthony and samy-delux's comment, this is what the customer can now run to access the main of the specific class:

java -cp c:\path\to\jar\jarFile.jar com.utils.classpath -e -v textString

Printing 1 to 1000 without loop or conditionals

You can use System() to print 1 to 1000 (by using DOS Command)

 include <process.h>
 void main()
 {
     system("cmd.exe /c for /l %x in (1, 1, 1000) do echo %x" );
 }

Run .exe(executable) file of your program which displays 1 to 1000

NOTE: Tested in WINDOWS

Adding script tag to React/JSX

My favorite way is to use React Helmet – it's a component that allows for easy manipulation of the document head in a way you're probably already used to.

e.g.

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <script src="https://use.typekit.net/foobar.js"></script>
                <script>try{Typekit.load({ async: true });}catch(e){}</script>
            </Helmet>
            ...
        </div>
    );
  }
};

https://github.com/nfl/react-helmet

How do I install a color theme for IntelliJ IDEA 7.0.x

Themes downloaded from IntelliJ can be installed as a Plugin.

Take these steps:

Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE ->  Preferences -> Appearance -> Theme -> Select your theme.

#ifdef in C#

C# does have a preprocessor. It works just slightly differently than that of C++ and C.

Here is a MSDN links - the section on all preprocessor directives.

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

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

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

How to bind Events on Ajax loaded Content?

Important step for Event binding on Ajax loading content...

01. First of all unbind or off the event on selector

$(".SELECTOR").off();

02. Add event listener on document level

$(document).on("EVENT", '.SELECTOR', function(event) { 
    console.log("Selector event occurred");
});

Can not find module “@angular-devkit/build-angular”

npm install --save-dev @angular-devkit/build-angular

It's Install @angular-devkit/build-angular as dev dependency. This package is newly introduced in Angular 6.0

How to print a two dimensional array?

public static void printTwoDimensionalArray(int[][] a) {
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            System.out.printf("%d ", a[i][j]);
        }
        System.out.println();
    }
}

just for int array

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Encrypt and Decrypt text with RSA in PHP

If you are using PHP >= 7.2 consider using inbuilt sodium core extension for encrption.

It is modern and more secure. You can find more information here - http://php.net/manual/en/intro.sodium.php. and here - https://paragonie.com/book/pecl-libsodium/read/00-intro.md

Example PHP 7.2 sodium encryption class -

<?php

/**
 * Simple sodium crypto class for PHP >= 7.2
 * @author MRK
 */
class crypto {

    /**
     * 
     * @return type
     */
    static public function create_encryption_key() {
        return base64_encode(sodium_crypto_secretbox_keygen());
    }

    /**
     * Encrypt a message
     * 
     * @param string $message - message to encrypt
     * @param string $key - encryption key created using create_encryption_key()
     * @return string
     */
    static function encrypt($message, $key) {
        $key_decoded = base64_decode($key);
        $nonce = random_bytes(
                SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
        );

        $cipher = base64_encode(
                $nonce .
                sodium_crypto_secretbox(
                        $message, $nonce, $key_decoded
                )
        );
        sodium_memzero($message);
        sodium_memzero($key_decoded);
        return $cipher;
    }

    /**
     * Decrypt a message
     * @param string $encrypted - message encrypted with safeEncrypt()
     * @param string $key - key used for encryption
     * @return string
     */
    static function decrypt($encrypted, $key) {
        $decoded = base64_decode($encrypted);
        $key_decoded = base64_decode($key);
        if ($decoded === false) {
            throw new Exception('Decryption error : the encoding failed');
        }
        if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
            throw new Exception('Decryption error : the message was truncated');
        }
        $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
        $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

        $plain = sodium_crypto_secretbox_open(
                $ciphertext, $nonce, $key_decoded
        );
        if ($plain === false) {
            throw new Exception('Decryption error : the message was tampered with in transit');
        }
        sodium_memzero($ciphertext);
        sodium_memzero($key_decoded);
        return $plain;
    }

}

Sample Usage -

<?php 

$key = crypto::create_encryption_key();

$string = 'Sri Lanka is a beautiful country !';

echo $enc = crypto::encrypt($string, $key); 
echo crypto::decrypt($enc, $key);

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

Simple way to create matrix of random numbers

An answer using map-reduce:-

map(lambda x: map(lambda y: ran(),range(len(inputs[0]))),range(hiden_neurons))

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

How to define a List bean in Spring?

Import the spring util namespace. Then you can define a list bean as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/util
                    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.

Basic example for sharing text or image with UIActivityViewController in Swift

I found this to work flawlessly if you want to share whole screen.

@IBAction func shareButton(_ sender: Any) {

    let bounds = UIScreen.main.bounds
    UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
    self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

how to draw directed graphs using networkx in python?

I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

G = nx.DiGraph()

G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)


val_map = {'A': 1.0,
                   'D': 0.5714285714285714,
                              'H': 0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
                 for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()

enter image description here

embedding image in html email

Try to resolve that with Context.Request:

<img width="150" height="60" src="@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.PathBase}/images/logo.png")" />

In my situation, when I used Content-ID I had that image as an attachment as well, and that was not the best solution.

How to convert byte array to string and vice versa?

Why was the problem: As someone already specified: If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

I was observing this problem when I was trying to create byte[] from a pdf file and then converting it to String and then taking the String as input and converting back to file.

So make sure your encoding and decoding logic is same as I did. I explicitly encoded the byte[] to Base64 and decoded it to create the file again.

Use-case: Due to some limitation I was trying to sent byte[] in request(POST) and the process was as follows:

PDF File >> Base64.encodeBase64(byte[]) >> String >> Send in request(POST) >> receive String >> Base64.decodeBase64(byte[]) >> create binary

Try this and this worked for me..

File file = new File("filePath");

        byte[] byteArray = new byte[(int) file.length()];

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(byteArray);

            String byteArrayStr= new String(Base64.encodeBase64(byteArray));

            FileOutputStream fos = new FileOutputStream("newFilePath");
            fos.write(Base64.decodeBase64(byteArrayStr.getBytes()));
            fos.close();
        } 
        catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
            e.printStackTrace();
        }
        catch (IOException e1) {
            System.out.println("Error Reading The File.");
            e1.printStackTrace();
        }

Why does Oracle not find oci.dll?

I just installed Oracle Instant Client 18_3 with the SDK. The PATH and ENV variable is set as instructed on the install page but I get the OCl.dll not found error. I searched the entire drive recursively and no such DLL exists.

So now what?

With the install instructions (not updated for 18_3) and downloads there are MISTAKES at step 13, so watch out for that.

When you create the folder structure for the downloads just write them the old way "c:\oraclient". Then when you unzip the basic, SDK and instant Client install for Windows 10_x64 extract them to "C:\oraclient\", because they all write to the same default folder. Then, when you set the ENV variable (which is no longer ORACLE_HOME, but now is OCI_LIB64) and the PATH, you will point to "C:\oraclient\instantclient_18_3".

To be sure you got it all right drill down and look for any duplicate "instantclient_18_3" folders. If you do have those cut and paste the CONTENTS to the root folder "C:\oraclient\instantclient_18_3\" folder.

Whoever works on the documentation at Oracle needs to troubleshoot better. I've seen "C:\oreclient_dir_install", "c:\oracle", "c:\oreclient" and "c:\oraclient" all mentioned as install directories, all for Windows x64 installs

BTW, install the C++ redist it helps. The 18.3 Basic package requires the Microsoft Visual Studio 2013 Redistributable.

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

Position DIV relative to another DIV?

you can use position:relative; inside #one div and position:absolute inside #two div. you can see it

Difference between "and" and && in Ruby?

and has lower precedence than &&.

But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator:

def happy?() true; end
def know_it?() true; end

todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"

todo
# => "Clap your hands"

todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"

todo
# => true

Embedding DLLs in a compiled executable

Yes, it is possible to merge .NET executables with libraries. There are multiple tools available to get the job done:

  • ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly.
  • Mono mkbundle, packages an exe and all assemblies with libmono into a single binary package.
  • IL-Repack is a FLOSS alterantive to ILMerge, with some additional features.

In addition this can be combined with the Mono Linker, which does remove unused code and therefor makes the resulting assembly smaller.

Another possibility is to use .NETZ, which does not only allow compressing of an assembly, but also can pack the dlls straight into the exe. The difference to the above mentioned solutions is that .NETZ does not merge them, they stay separate assemblies but are packed into one package.

.NETZ is a open source tool that compresses and packs the Microsoft .NET Framework executable (EXE, DLL) files in order to make them smaller.

How do I include a Perl module that's in a different directory?

I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.

#!/usr/bin/perl
use FindBin::libs;
use <your lib>;

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

Create a HTML table where each TR is a FORM

Tables are not meant for this, why don't you use <div>'s and CSS?

Short IF - ELSE statement

The ternary operator can only be the right side of an assignment and not a statement of its own.

http://www.devdaily.com/java/edu/pj/pj010018/

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

If you use version 26 then inside dependencies version should be 1.0.1 and 3.0.1 i.e., as follows

  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

If you use version 27 then inside dependencies version should be 1.0.2 and 3.0.2 i.e., as follows

  androidTestImplementation 'com.android.support.test:runner:1.0.2'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

How to align texts inside of an input?

Use the text-align property in your CSS:

input { 
    text-align: right; 
}

This will take effect in all the inputs of the page.
Otherwise, if you want to align the text of just one input, set the style inline:

<input type="text" style="text-align:right;"/> 

MySQL Multiple Where Clause

SELECT a.image_id 
FROM list a
INNER JOIN list b
   ON a.image_id = b.image_id
   AND b.style_id = 25
   AND b.style_value = 'big'
INNER JOIN list c
   ON a.image_id = c.image_id
   AND c.style_id = 27
   AND c.style_value = 'round'
WHERE a.style_id = 24 
   AND a.style_value = 'red'

How can one tell the version of React running at runtime in the browser?

With the React Devtools installed you can run this from the browser console:

__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.forEach(r => console.log(`${r.rendererPackageName}: ${r.version}`))

Which outputs something like:

react-dom: 16.12.0

How do I insert datetime value into a SQLite database?

This may not be the most popular or efficient method, but I tend to forgo strong datatypes in SQLite since they are all essentially dumped in as strings anyway.

I've written a thin C# wrapper around the SQLite library before (when using SQLite with C#, of course) to handle insertions and extractions to and from SQLite as if I were dealing with DateTime objects.

What is “2's Complement”?

In simple term 2's Complement is a way to store negative number in Computer Memory. Whereas Positive Numbers are stored as Normal Binary Number.

Let's consider this example,

Computer uses Binary Number System to represent any number.

x = 5;

This is represented as 0101.

x = -5;

When the computer encouters - sign, it computes it's 2's complement and stores it. i.e 5 = 0101 and it's 2's complement is 1011.

Important rules computer uses to process numbers are,

  1. If the first bit is 1 then it must be negative number.
  2. If all the bits except first bit are 0 then it is a positive number because there is no -0 in number system.(1000 is not -0 instead it is positive 8)
  3. If all the bits are 0 then it is 0.
  4. Else it is a positive number.

How do I get the time of day in javascript/Node.js?

For my instance i used it as a global and then called its for a time check of when hours of operation.

Below is from my index.js

global.globalDay = new Date().getDay(); 

global.globalHours = new Date().getHours();

To call the global's value from another file

    /*
     Days of the Week.
     Sunday = 0, Monday = 1, Tuesday = 2, Wensday = 3, Thursday = 4, Friday = 5, Saturday = 6

     Hours of the Day.
     0 = Midnight, 1 = 1am, 12 = Noon, 18 = 6pm, 23 = 11pm
     */

if (global.globalDay === 6 || global.globalDay === 0) {
     console.log('Its the weekend.');
} else if (global.globalDay > 0 && global.globalDay < 6 && global.globalHours > 8 && global.globalHours < 18) {
     console.log('During Business Hours!');
} else {
     console.log("Outside of Business hours!");
}

Filter an array using a formula (without VBA)

=VLOOKUP(A2,IF(B1:B3="B",A1:C3,""),1,FALSE)

Ctrl+Shift+Enter to enter.

How do I install a plugin for vim?

Those two commands will create a ~/.vim/vim-haml/ directory with the ftplugin, syntax, etc directories in it. Those directories need to be immediately in the ~/.vim directory proper or ~/.vim/vim-haml needs to be added to the list of paths that vim searches for plugins.

Edit:

I recently decided to tweak my vim config and in the process wound up writing the following rakefile. It only works on Mac/Linux, but the advantage over cp versions is that it's completely safe (symlinks don't overwrite existing files, uninstall only deletes symlinks) and easy to keep things updated.

# Easily install vim plugins from a source control checkout (e.g. Github)
#
# alias vim-install=rake -f ~/.vim/rakefile-vim-install
# vim-install
# vim-install uninstall

require 'ftools'
require 'fileutils'

task :default => :install
desc "Install a vim plugin the lazy way"
task :install do
  vim_dir      = File.expand_path("~/.vim")
  plugin_dir   = Dir.pwd

  if not (FileTest.exists? File.join(plugin_dir,".git") or
          FileTest.exists? File.join(plugin_dir,".svn") or
          FileTest.exists? File.join(plugin_dir,".hg"))
      puts "#{plugin_dir} isn't a source controlled directory. Aborting."
      exit 1
  end

  Dir['**/'].each do |d|
    FileUtils.mkdir_p File.join(vim_dir, d)
  end

  Dir["**/*.{txt,snippet,snippets,vim,js,wsf}"].each do |f|
    ln File.join(plugin_dir, f), File.join(vim_dir,f)
  end

  boldred = "\033[1;31m"
  clear = "\033[0m"
  puts "\nDone. Remember to #{boldred}:helptags ~/.vim/doc#{clear}"
end

task :uninstall do
  vim_dir      = File.expand_path("~/.vim")
  plugin_dir   = Dir.pwd
  Dir["**/*.{txt,snippet,snippets,vim}"].each do |f|
    safe_rm File.join(vim_dir, f)
  end
end

def nicename(path)
    boldgreen = "\033[1;32m"
    clear = "\033[0m"
    return "#{boldgreen}#{File.join(path.split('/')[-2..-1])}#{clear}\t"
end

def ln(src, dst)
    begin
        FileUtils.ln_s src, dst
        puts "    Symlink #{nicename src}\t => #{nicename dst}"
    rescue Errno::EEXIST
        puts "  #{nicename dst} exists! Skipping."
    end
end

def cp(src, dst)
  puts "    Copying #{nicename src}\t=> #{nicename dst}"
  FileUtils.cp src, dst
end

def safe_rm(target)
    if FileTest.exists? target and FileTest.symlink? target
        puts "    #{nicename target} removed."
        File.delete target
    else
        puts "  #{nicename target} is not a symlink. Skipping"
    end
end

django - get() returned more than one topic

get() returned more than one topic -- it returned 2!

The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get() such as

Model.objects.get(field_name=some_param)

To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.

So instead of using get() you should use filter() which will return multiple records. Such as

Model.objects.filter(field_name=some_param)

Please read about how to make queries in django here.

Print multiple arguments in Python

Just follow this

idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))

OR

idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))

And forget all others, else the brain won't be able to map all the formats.

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

MySQLi count(*) always returns 1

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

How to convert integer into date object python?

I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

unique() for more than one variable

How about using unique() itself?

df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
                 per = c("AYLIK",  "AYLIK",  "2 AYLIK", "2 AYLIK"),
                 hmm = 1:4)

df
#       yad     per hmm
# 1  BARBIE   AYLIK   1
# 2  BARBIE   AYLIK   2
# 3 BAKUGAN 2 AYLIK   3
# 4 BAKUGAN 2 AYLIK   4

unique(df[c("yad", "per")])
#       yad     per
# 1  BARBIE   AYLIK
# 3 BAKUGAN 2 AYLIK

Angular 2: Get Values of Multiple Checked Checkboxes

I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

Here are the 3 objects I'm using:

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

And there are 3 useful methods:

1. To initiate optionsMap:

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2. to update the optionsMap:

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3. to convert optionsMap into optionsChecked and store it in options before sending the POST request:

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

Extract specific columns from delimited file using Awk

As mentioned by @Tom, the cut and awk approaches actually don't work for CSVs with quoted strings. An alternative is a module for python that provides the command line tool csvfilter. It works like cut, but properly handles CSV column quoting:

csvfilter -f 1,3,5 in.csv > out.csv

If you have python (and you should), you can install it simply like this:

pip install csvfilter

Please take note that the column indexing in csvfilter starts with 0 (unlike awk, which starts with $1). More info at https://github.com/codeinthehole/csvfilter/

What does void* mean and how to use it?

C11 standard (n1570) §6.2.2.3 al1 p55 says :

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

You can use this generic pointer to store a pointer to any object type, but you can't use usual arithmetic operations with it and you can't deference it.

What to do about Eclipse's "No repository found containing: ..." error messages?

2019 Eclipse/CCS

After trying many of the above techniques described here I noticed this post by Edwin landwealths

The long and short of it is to add the infamous tail "/" and ALSO change "http" to "https". This fixed my issue immediately.

Running sites on "localhost" is extremely slow

Run the Process Monitor to see what resources(Network, File, Registry, Threads) are being consumed and see any unnecessary resource(remote https, costly file reads) are being consumed

I had similar problem. When I run the process monitor I found that my fusion log is enabled so there are many into the disk which delayed the loading of dll after disabling fusion log IIS Express it is faster.

enter image description here

how to display full stored procedure code?

\ef <function_name> in psql. It will give the whole function with editable text.

How can I copy a Python string?

You can copy a string in python via string formatting :

>>> a = 'foo'  
>>> b = '%s' % a  
>>> id(a), id(b)  
(140595444686784, 140595444726400)  

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.

btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

Let's First look at MVC

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.

How to open an Excel file in C#?

FileInfo fi = new FileInfo("C:\\test\\report.xlsx");
if(fi.Exists)
{
    System.Diagnostics.Process.Start(@"C:\test\report.xlsx");
}
else
{
    //file doesn't exist
}

Callback to a Fragment from a DialogFragment

Activity involved is completely unaware of the DialogFragment.

Fragment class:

public class MyFragment extends Fragment {
int mStackLevel = 0;
public static final int DIALOG_FRAGMENT = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        mStackLevel = savedInstanceState.getInt("level");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("level", mStackLevel);
}

void showDialog(int type) {

    mStackLevel++;

    FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
    Fragment prev = getActivity().getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    switch (type) {

        case DIALOG_FRAGMENT:

            DialogFragment dialogFrag = MyDialogFragment.newInstance(123);
            dialogFrag.setTargetFragment(this, DIALOG_FRAGMENT);
            dialogFrag.show(getFragmentManager().beginTransaction(), "dialog");

            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case DIALOG_FRAGMENT:

                if (resultCode == Activity.RESULT_OK) {
                    // After Ok code.
                } else if (resultCode == Activity.RESULT_CANCELED){
                    // After Cancel code.
                }

                break;
        }
    }
}

}

DialogFragment class:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(int num){

    MyDialogFragment dialogFragment = new MyDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("num", num);
    dialogFragment.setArguments(bundle);

    return dialogFragment;

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.ERROR)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton(R.string.ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                        }
                    }
            )
            .setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                }
            })
            .create();
}
}

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

How to select all the columns of a table except one column?

Try the following query:

DECLARE @Temp NVARCHAR(MAX); 
DECLARE @SQL NVARCHAR(MAX);

SET @Temp = '';
SELECT @Temp = @Temp + COLUMN_NAME + ', ' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='Person' AND COLUMN_NAME NOT IN ('Id')  

SET @SQL = 'SELECT ' + SUBSTRING(@Temp, 0, LEN(@Temp)) +' FROM [Person]';
EXECUTE SP_EXECUTESQL @SQL;

How to take screenshot of a div with JavaScript?

<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation

How do I center a Bootstrap div with a 'spanX' class?

Update

As of BS3 there's a .center-block helper class. From the docs:

// Classes
.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

// Usage as mixins
.element {
  .center-block();
}

There is hidden complexity in this seemingly simple problem. All the answers given have some issues.

1. Create a Custom Class (Major Gotcha)

Create .col-centred class, but there is a major gotcha.

.col-centred {
   float: none !important;
   margin: 0 auto;
}

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
  Centred content.
</div>

The Gotcha

Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.

The Fixes

You can resolve this issue by using a clearfix element. Using z-index to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.

<div class="row">
  <div class="col-lg-12">
    I get overlapped by `col-lg-7 centered` unless there's a clearfix.
  </div>
  <div class="clearfix"></div>
  <div class="col-lg-7 centred">
  </div>
</div>

Or you can isolate the centred column in its own row.

<div class="row">
  <div class="col-lg-12">
  </div>
</div>
<div class="row">
  <div class="col-lg-7 centred">
    Look I am in my own row.
  </div>
</div>

2. Use col-lg-offset-x or spanx-offset (Major Gotcha)

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
  Centred content.
</div>

The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).

Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.

3. Create an Inner Centred Column

This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.

.col-centred {
   margin: 0 auto;
}

<div class="row">
  <div class="col-lg-12">
    <div class="centred">
        Look I am in my own row.
    </div>
  </div>
</div>

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

ProgressDialog is deprecated.What is the alternate one to use?

You can use this class I wrote. It offers only the basic functions. If you want a fully functional ProgressDialog, then use this lightweight library.

Gradle Setup

Add the following dependency to module/build.gradle:

compile 'com.lmntrx.android.library.livin.missme:missme:0.1.5'

How to use it?

Usage is similar to original ProgressDialog

ProgressDialog progressDialog = new 
progressDialog(YourActivity.this);
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.dismiss();

NB: You must override activity's onBackPressed()

Java8 Implementation:

@Override
public void onBackPressed() {
    progressDialog.onBackPressed(
            () -> {
                super.onBackPressed();
                return null;
            }
    );
}

Kotlin Implementation:

override fun onBackPressed() {
   progressDialog.onBackPressed { super.onBackPressed() }
}
  • Refer Sample App for the full implementation
  • Full documentation can be found here

ESLint - "window" is not defined. How to allow global variables in package.json

I found it on this page: http://eslint.org/docs/user-guide/configuring

In package.json, this works:

"eslintConfig": {
  "globals": {
    "window": true
  }
}

How can I get the name of an object in Python?

Use a reverse dict.

fun_dict = {'fun1': fun1,
            'fun2': fun2,
            'fun3': fun3}

r_dict = dict(zip(fun_dict.values(), fun_dict.keys()))

The reverse dict will map each function reference to the exact name you gave it in fun_dict, which may or may not be the name you used when you defined the function. And, this technique generalizes to other objects, including integers.

For extra fun and insanity, you can store the forward and reverse values in the same dict. I wouldn't do that if you were mapping strings to strings, but if you are doing something like function references and strings, it's not too crazy.

Iterating over a 2 dimensional python list

>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

internal/modules/cjs/loader.js:582 throw err

I was having the same error because I had a space at the end of my filename(not the reference but the actual filename). Once I changed 'app.js ' to 'app.js' it worked fine.

How do I align spans or divs horizontally?

My answer:

<style>
 #whatever div {
  display: inline;
  margin: 0 1em 0 1em;
  width: 30%;
}
</style>

<div id="whatever">
 <div>content</div>
 <div>content</div>
 <div>content</div>
</div>

Why?

Technically, a Span is an inline element, however it can have width, you just need to set their display property to block first. However, in this context, a div is probably more appropriate, as I'm guessing you want to fill these divs with content.

One thing you definitely don't want to do is have clear:both set on the divs. Setting it like that will mean that the browser will not allow any elements to sit on the same line as them. The result, your elements will stack up.

Note, the use of display:inline. This deals with the ie6 margin-doubling bug. You could tackle this in other ways if necessary, for example conditional stylesheets.

I've added a wrapper (#whatever) as I'm guessing these won't be the only elements on page, so you'll almost certainly need to segregate them from the other page elements.

Anyway, I hope that's helpful.

Convert pandas data frame to series

Another way -

Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows

# label your columns by passing a list of names
myResult.columns = ['firstCol']

# fetch the column in this way, which will return you a series
myResult = myResult['firstCol']

print(type(myResult))

In similar fashion, you can get series from Dataframe with multiple columns.

Why does Eclipse Java Package Explorer show question mark on some classes?

those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:

image describing Eclipse icons for Egit

  • dirty (folder) - At least one file below the folder is dirty; that means that it has changes in the working tree that are neither in the index nor in the repository.
  • tracked - The resource is known to the Git repository. untracked - The resource is not known to the Git repository.
  • ignored - The resource is ignored by the Git team provider. Here only the preference settings under Team -> Ignored Resources and the "derived" flag are relevant. The .gitignore file is not taken into account.
  • dirty - The resource has changes in the working tree that are neither in the index nor in the repository.
  • staged - The resource has changes which are added to the index. Not that adding to the index is possible at the moment only on the commit dialog on the context menu of a resource.
  • partially-staged - The resource has changes which are added to the index and additionally changes in the working tree that are neither in the index nor in the repository.
  • added - The resource is not yet tracked by but added to the Git repository.
  • removed - The resource is staged for removal from the Git repository.
  • conflict - A merge conflict exists for the file.
  • assume-valid - The resource has the "assume unchanged" flag. This means that Git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell Git when you change the working tree file. This setting can be switched on with the menu action Team->Assume unchanged (or on the command line with git update-index--assume-unchanged).

Spring jUnit Testing properties file

Firstly, application.properties in the @PropertySource should read application-test.properties if that's what the file is named (matching these things up matters):

@PropertySource("classpath:application-test.properties ")

That file should be under your /src/test/resources classpath (at the root).

I don't understand why you'd specify a dependency hard coded to a file called application-test.properties. Is that component only to be used in the test environment?

The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.

In a typically laid out application, you'd have:

src/test/resources/application.properties

and

src/main/resources/application.properties

And then inject it like this:

@PropertySource("classpath:application.properties")

The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?

Xcode 6 iPhone Simulator Application Support location

  1. With Swift 4, you can use the code below to get your app's home directory. Your app's document directory is in there.

    print(NSHomeDirectory())

  2. I think you already know that your app's home directory is changeable, so if you don't want to add additional code to your codebase, SimPholder is a nice tool for you.

  3. And further more, you may wonder is there a tool, that can help you save time from closing and reopening same SQLite database every time after your app's home directory be changed. And the answer is yes, a tool I know is SQLiteFlow. From it's document, it says that:

    Handle database file name or directory changes. This makes SQLiteFlow can work friendly with your SQLite database in iOS simulator.

Delete multiple rows by selecting checkboxes using PHP

You should treat it as an array like this,

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">

Then only, you can take its count and loop it for deletion.

You also need to pass the database connection to the query.

$result = mysqli_query($dbc, $sql);

Yours did not include it:

$result = mysqli_query($sql);

MySQL: Get column name or alias from query

cursor.description will give you a tuple of tuples where [0] for each is the column header.

num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]

Does functional programming replace GoF design patterns?

I think that each paradigm serves a different purpose and as such cannot be compared in this way.

I have not heard that the GoF design patterns are applicable to every language. I have heard that they are applicable to all OOP languages. If you use functional programming then the domain of problems that you solve is different from OO languages.

I wouldn't use functional language to write a user interface, but one of the OO languages like C# or Java would make this job easier. If I were writing a functional language then I wouldn't consider using OO design patterns.

Arduino error: does not name a type?

Usually Header file syntax start with capital letter.I found that code written all in smaller letter

#ifndef DIAG_H
#define DIAG_H

#endif

How do I use InputFilter to limit characters in an EditText in Android?

This is an old thread, but the purposed solutions all have issues (depending on device / Android version / Keyboard).

DIFFERENT APPROACH

So eventually I went with a different approach, instead of using the InputFilter problematic implementation, I am using TextWatcher and the TextChangedListener of the EditText.

FULL CODE (EXAMPLE)

editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable editable) {
        super.afterTextChanged(editable);

        String originalText = editable.toString();
        int originalTextLength = originalText.length();
        int currentSelection = editText.getSelectionStart();

        // Create the filtered text
        StringBuilder sb = new StringBuilder();
        boolean hasChanged = false;
        for (int i = 0; i < originalTextLength; i++) {
            char currentChar = originalText.charAt(i);
            if (isAllowed(currentChar)) {
                sb.append(currentChar);
            } else {
                hasChanged = true;
                if (currentSelection >= i) {
                    currentSelection--;
                }
            }
        }

        // If we filtered something, update the text and the cursor location
        if (hasChanged) {
            String newText = sb.toString();
            editText.setText(newText);
            editText.setSelection(currentSelection);
        }
    }

    private boolean isAllowed(char c) {
        // TODO: Add the filter logic here
        return Character.isLetter(c) || Character.isSpaceChar(c);
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Do Nothing
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // Do Nothing
    }
});

The reason InputFilter is not a good solution in Android is since it depends on the keyboard implementation. The Keyboard input is being filtered before the input is passed to the EditText. But, because some keyboards have different implementations for the InputFilter.filter() invocation, this is problematic.

On the other hand TextWatcher does not care about the keyboard implementation, it allows us to create a simple solution and be sure it will work on all devices.

What is the purpose of the : (colon) GNU Bash builtin?

Another way, not yet mentioned here is the initialisation of parameters in infinite while-loops. Below is not the cleanest example, but it serves it's purpose.

#!/usr/bin/env bash
[ "$1" ] && foo=0 && bar="baz"
while : "${foo=2}" "${bar:=qux}"; do
    echo "$foo"
    (( foo == 3 )) && echo "$bar" && break
    (( foo=foo+1 ))
done

What is PECS (Producer Extends Consumer Super)?

In a nutshell, three easy rules to remember PECS:

  1. Use the <? extends T> wildcard if you need to retrieve object of type T from a collection.
  2. Use the <? super T> wildcard if you need to put objects of type T in a collection.
  3. If you need to satisfy both things, well, don’t use any wildcard. As simple as that.

Changing the "tick frequency" on x or y axis in matplotlib?

This is an old topic, but I stumble over this every now and then and made this function. It's very convenient:

import matplotlib.pyplot as pp
import numpy as np

def resadjust(ax, xres=None, yres=None):
    """
    Send in an axis and I fix the resolution as desired.
    """

    if xres:
        start, stop = ax.get_xlim()
        ticks = np.arange(start, stop + xres, xres)
        ax.set_xticks(ticks)
    if yres:
        start, stop = ax.get_ylim()
        ticks = np.arange(start, stop + yres, yres)
        ax.set_yticks(ticks)

One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. Then do

gca().set_ylim(top=new_top) # for example

and run the resadjust function again.

jQuery scroll to ID from different page

On the link put a hash:

<a href="otherpage.html#elementID">Jump</a>

And on other page, you can do:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

On other page, you should have element with id set to elementID to scroll to. Of course you can change the name of it.

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

jquery, domain, get URL

You don't need jQuery for this, as simple javascript will suffice:

alert(document.domain);

See it in action:

_x000D_
_x000D_
console.log("Output;");  _x000D_
console.log(location.hostname);_x000D_
console.log(document.domain);_x000D_
alert(window.location.hostname)_x000D_
_x000D_
console.log("document.URL : "+document.URL);_x000D_
console.log("document.location.href : "+document.location.href);_x000D_
console.log("document.location.origin : "+document.location.origin);_x000D_
console.log("document.location.hostname : "+document.location.hostname);_x000D_
console.log("document.location.host : "+document.location.host);_x000D_
console.log("document.location.pathname : "+document.location.pathname);
_x000D_
_x000D_
_x000D_

For further domain-related values, check out the properties of window.location online. You may find that location.host is a better option, as its content could differ from document.domain. For instance, the url http://192.168.1.80:8080 will have only the ipaddress in document.domain, but both the ipaddress and port number in location.host.

How to add to the end of lines containing a pattern with sed or awk?

In bash:

while read -r line ; do
    [[ $line == all:* ]] && line+=" anotherthing"
    echo "$line"
done < filename

Scrollbar without fixed height/Dynamic height with scrollbar

I have Similar issue with PrimeNG p_Dialog content and i fixed by below style for the contentStyle

height: 'calc(100vh - 127px)'

How do I clear all options in a dropdown box?

If you wish to have a lightweight script, then go for jQuery. In jQuery, the solution for removing all options will be like:

$("#droplist").empty();

pip broke. how to fix DistributionNotFound error?

In my case (sam problem, but other packages) there was no version dependency. A sequence of pip uninstall and pip insstall did help.

How to get the current date and time

java.lang.System.currentTimeMillis(); will return the datetime since the epoch

how to call an ASP.NET c# method using javascript

You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.

in markup:

 var $Username = $("#txtUsername").val();
            var $Password = $("#txtPassword").val();

            //Call the approve method on the code behind
            $.ajax({
                type: "POST",
                url: "Pages/Mobile/Login.aspx/LoginUser",
                data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) },
                success: function (msg) {
                    if (msg.d == true) {
                        window.location.href = "Pages/Mobile/Basic/Index.aspx";
                    }
                    else {
                        //show error
                        alert('login failed');
                    }
                }
            });

In Code Behind:

/// <summary>
/// Logs in the user
/// </summary>
/// <param name="Username">The username</param>
/// <param name="Password">The password</param>
/// <returns>true if login successful</returns>
[WebMethod, ScriptMethod]
public static bool LoginUser( string Username, string Password )
{
    try
    {
        StaticStore.CurrentUser = new User( Username, Password );

        //check the login details were correct
        if ( StaticStore.CurrentUser.IsAuthentiacted )
        {
            //change the status to logged in
            StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn;

            //Store the user ID in the list of active users
            ( HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int> )[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID;

            return true;
        }
        else
        {
            return false;
        }
    }
    catch ( Exception ex )
    {
        return false;
    }
}

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

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

Convert Rows to columns using 'Pivot' in SQL Server

If you are using SQL Server 2005+, then you can use the PIVOT function to transform the data from rows into columns.

It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.

First up, here are some quick table definitions and data for use:

CREATE TABLE #yt 
(
  [Store] int, 
  [Week] int, 
  [xCount] int
);

INSERT INTO #yt
(
  [Store], 
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);

If your values are known, then you will hard-code the query:

select *
from 
(
  select store, week, xCount
  from yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;

See SQL Demo

Then if you need to generate the week number dynamically, your code will be:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Week) 
                    from yt
                    group by Week
                    order by Week
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT store,' + @cols + ' from 
             (
                select store, week, xCount
                from yt
            ) x
            pivot 
            (
                sum(xCount)
                for week in (' + @cols + ')
            ) p '

execute(@query);

See SQL Demo.

The dynamic version, generates the list of week numbers that should be converted to columns. Both give the same result:

| STORE |   1 |   2 |   3 |
---------------------------
|   101 | 138 | 282 | 220 |
|   102 |  96 | 212 | 123 |
|   105 |  37 |  78 |  60 |
|   109 |  59 |  97 |  87 |

mysql extract year from date format

Since your subdateshow is a VARCHAR column instead of the proper DATE, TIMESTAMP or DATETIME column you have to convert the string to date before you can use YEAR on it:

SELECT YEAR(STR_TO_DATE(subdateshow, "%m/%d/%Y")) from table

See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

How to fluently build JSON in Java?

I am using the org.json library and found it to be nice and friendly.

Example:

String jsonString = new JSONObject()
                  .put("JSON1", "Hello World!")
                  .put("JSON2", "Hello my World!")
                  .put("JSON3", new JSONObject().put("key1", "value1"))
                  .toString();

System.out.println(jsonString);

OUTPUT:

{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}

How to create a file with a given size in Linux?

dd if=/dev/zero of=my_file.txt count=12345

PHP - Indirect modification of overloaded property

Nice you gave me something to play around with

Run

class Sample extends Creator {

}

$a = new Sample ();
$a->role->rolename = 'test';
echo  $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo  $a->role->rolename  , PHP_EOL;
echo  $a->role->rolename->am->love->php   , PHP_EOL;

Output

test
test
w00

Class Used

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        $this->{$name} = new Value ( $name, $value );
    }



}

class Value extends Creator {
    private $name;
    private $value;
    function __construct($name, $value) {
        $this->name = $name;
        $this->value = $value;
    }

    function __toString()
    {
        return (string) $this->value ;
    }
}      

Edit : New Array Support as requested

class Sample extends Creator {

}

$a = new Sample ();
$a->role = array (
        "A",
        "B",
        "C" 
);


$a->role[0]->nice = "OK" ;

print ($a->role[0]->nice  . PHP_EOL);

$a->role[1]->nice->ok = array("foo","bar","die");

print ($a->role[1]->nice->ok[2]  . PHP_EOL);


$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;

print ($a->role[2]->nice->raw->name. PHP_EOL);

Output

 Ok die baba

Modified Class

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;

    }

}

class Value {
    private $name ;
    function __construct($name, $value) {
        $this->{$name} = $value;
        $this->name = $value ;
    }

    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }

        if ($name == $this->name) {
            return $this->value;
        }

        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;
    }

    public function __toString() {
        return (string) $this->name ;
    }   
}

Compare given date with today

That format is perfectly appropriate for a standard string comparison e.g.

if ($date1 > $date2){
  //Action
}

To get today's date in that format, simply use: date("Y-m-d H:i:s").

So:

$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";

if ($date < $today) {}

That's the beauty of that format: it orders nicely. Of course, that may be less efficient, depending on your exact circumstances, but it might also be a whole lot more convenient and lead to more maintainable code - we'd need to know more to truly make that judgement call.

For the correct timezone, you can use, for example,

date_default_timezone_set('America/New_York');

Click here to refer to the available PHP Timezones.

sys.argv[1] meaning in script

To pass arguments to your python script while running a script via command line

python create_thumbnail.py test1.jpg test2.jpg

here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg

With in the create_thumbnail.py script i use

sys.argv[1:]

which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']

AngularJS: Can't I set a variable value on ng-click?

While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:

ng-click="hidePrefs()"

and then in your controller:

$scope.hidePrefs = function() {  
  $scope.prefs = false;
}

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

Solution 1: Remove ONLY_FULL_GROUP_BY from mysql console

mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

you can read more here

Solution 2: Remove ONLY_FULL_GROUP_BY from phpmyadmin

Open phpmyadmin & select localhost
Click on menu Variables & scroll down for sql mode
Click on edit button to change the values & remove ONLY_FULL_GROUP_BY & click on save. 

click here to see image

How to send email from Terminal?

in the terminal on your mac os or linux os type this code

mail -s (subject) (receiversEmailAddress)  <<< "how are you?"

for an example try this

mail -s "hi" [email protected] <<< "how are you?"<br>

How can I have grep not print out 'No such file or directory' errors?

Errors like that are usually sent to the "standard error" stream, which you can pipe to a file or just make disappear on most commands:

grep pattern * -R -n 2>/dev/null

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

Difference between Inheritance and Composition

They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".

You do composition by having an instance of another class C as a field of your class, instead of extending C. A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.

Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack used composition instead of inheritance, it can always be modified to use another data structure without violating the API.

I highly recommend Josh Bloch's book Effective Java 2nd Edition

  • Item 16: Favor composition over inheritance
  • Item 17: Design and document for inheritance or else prohibit it

Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.


See also:

How do I URl encode something in Node.js?

You can use JavaScript's encodeURIComponent:

encodeURIComponent('select * from table where i()')

giving

'select%20*%20from%20table%20where%20i()'

Razor MVC Populating Javascript array with Model Array

This would be better approach as I have implemented :)

@model ObjectUser
@using System.Web.Script.Serialization
@{ 
    var javaScriptSearilizer = new JavaScriptSerializer();
    var searializedObject = javaScriptSearilizer.Serialize(Model);
 }

<script>
    var searializedObject = @Html.Raw(searializedObject )
    console.log(searializedObject);
    alert(searializedObject);
</script>

Hope this will help you to prevent you from iterating model ( happy coding )

Error when trying vagrant up

well, actually you have to do:

vagrant up laravel/homestead

because according to homestead walkthrough you've just downloaded it: http://laravel.com/docs/5.0/homestead by:

vagrant box add laravel/homestead

so you have to launch the box you mean to use - not some random ubuntu image ;)

View contents of database file in Android Studio

I know the question is rather old but I believe this issue is still present.

Viewing databases from your browser

I created a development tool that you can integrate as a lib into your android app project. The tool opens a server socket in your app to communicate via web browser. You can browse through your whole database and download the database file directly through the browser.

enter image description here

Integration can be done via jitpack.io:

project build.gradle:

//...
allprojects {
    repositories {
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}
//...

app build.gradle:

//...
dependencies {
    //...
    debugCompile 'com.github.sanidgmbh:debugghost:v1.1'
    //...
}
//...

Setup Application class

In order to only compile DebugGhostLib in certain build-types or product-flavours we need an abstract Application class which will be derived in the special flavours. Put the following class in your main folder (under java > your.app.package):

public class AbstractDebugGhostExampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Do your general application stuff
    }
}

Now, for your release build type (or product flavour), you add the following Application class to your release (or product-flavour) folder (also under java > your.app.package):

public class MyApp extends AbstractDebugGhostExampleApplication {
    @Override
    public void onCreate() {
        super.onCreate();
    }
}

This is the application class that will not reference DebugGhostLib.

Also tell your AndroidManifest.xml that you're using your own application class. This will be done in your main folder:

<manifest package="demo.app.android.sanid.com.debugghostexample" xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- permissions go here -->
    <application android:name=".MyApp"> <!-- register your own application class -->
        <!-- your activities go here -->
    </application>
</manifest>

Now, for your debug build type (or product flavour), you add the following Application class to your debug (or product-flavour) folder (also under java > your.app.package):

public class MyApp extends AbstractDebugGhostExampleApplication {
    private DebugGhostBridge mDebugGhostBridge;

    @Override
    public void onCreate() {
        super.onCreate();

        mDebugGhostBridge = new DebugGhostBridge(this, MyDatabaseHelper.DATABASE_NAME, MyDatabaseHelper.DATABASE_VERSION);
        mDebugGhostBridge.startDebugGhost();
    }
}

You can get the tool here.

C# DataTable.Select() - How do I format the filter criteria to include null?

The way to check for null is to check for it:

DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");

You can use and and or in the Select statement.

CMD: Export all the screen content to a text file

If you want to append a file instead of constantly making a new one/deleting the old one's content, use double > marks. A single > mark will overwrite all the file's content.

Overwrite file

MyCommand.exe>file.txt

^This will open file.txt if it already exists and overwrite the data, or create a new file and fill it with your output

Append file from its end-point

MyCommand.exe>>file.txt

^This will append file.txt from its current end of file if it already exists, or create a new file and fill it with your output.


Update #1 (advanced):

My batch-fu has improved over time, so here's some minor updates.

If you want to differentiate between error output and normal output for a program that correctly uses Standard streams, STDOUT/STDERR, you can do this with minor changes to the syntax. I'll just use > for overwriting for these examples, but they work perfectly fine with >> for append, in regards to file-piping output re-direction.

The 1 before the >> or > is the flag for STDOUT. If you need to actually output the number one or two before the re-direction symbols, this can lead to strange, unintuitive errors if you don't know about this mechanism. That's especially relevant when outputting a single result number into a file. 2 before the re-direction symbols is for STDERR.

Now that you know that you have more than one stream available, this is a good time to show the benefits of outputting to nul. Now, outputting to nul works the same way conceptually as outputting to a file. You don't see the content in your console. Instead of it going to file or your console output, it goes into the void.

STDERR to file and suppress STDOUT

MyCommand.exe 1>nul 2>errors.txt

STDERR to file to only log errors. Will keep STDOUT in console

MyCommand.exe 2>errors.txt

STDOUT to file and suppress STDERR

MyCommand.exe 1>file.txt 2>nul

STDOUT only to file. Will keep STDERR in console

MyCommand.exe 1>file.txt

STDOUT to one file and STDERR to another file

MyCommand.exe 1>stdout.txt 2>errors.txt

The only caveat I have here is that it can create a 0-byte file for an unused stream if one of the streams never gets used. Basically, if no errors occurred, you might end up with a 0-byte errors.txt file.

Update #2

I started noticing weird behavior when writing console apps that wrote directly to STDERR, and realized that if I wanted my error output to go to the same file when using basic piping, I either had to combine streams 1 and 2 or just use STDOUT. The problem with that problem is I didn't know about the correct way to combine streams, which is this:

%command% > outputfile 2>&1

Therefore, if you want all STDOUT and STDERR piped into the same stream, make sure to use that like so:

MyCommand.exe > file.txt 2>&1

The redirector actually defaults to 1> or 1>>, even if you don't explicitly use 1 in front of it if you don't use a number in front of it, and the 2>&1 combines the streams.

Update #3 (simple)

Null for Everything

If you want to completely suppress STDOUT and STDERR you can do it this way. As a warning not all text pipes use STDOUT and STDERR but it will work for a vast majority of use cases.

STD* to null MyCommand.exe>nul 2>&1

Copying a CMD or Powershell session's command output

If all you want is the command output from a CMD or Powershell session that you just finished up, or any other shell for that matter you can usually just select that console from that session, CTRL + A to select all content, then CTRL + C to copy the content. Then you can do whatever you like with the copied content while it's in your clipboard.

What does %s and %d mean in printf in the C language?

"%s%d%s%d\n" is the format string; it tells the printf function how to format and display the output. Anything in the format string that doesn't have a % immediately in front of it is displayed as is.

%s and %d are conversion specifiers; they tell printf how to interpret the remaining arguments. %s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char); the type of the corresponding argument must be char *. %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int. Since you're coming from a Java background, it's important to note that printf (like other variadic functions) is relying on you to tell it what the types of the remaining arguments are. If the format string were "%d%s%d%s\n", printf would attempt to treat "Length of string" as an integer value and i as a string, with tragic results.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

In SQL Server Management Studio you can just right click the table in the object explorer and select "View Dependencies". This would give a you a good starting point. It shows tables, views, and procedures that reference the table.

Controller not a function, got undefined, while defining controllers globally

I had this problem when I accidentally redeclared myApp:

var myApp = angular.module('myApp',[...]);
myApp.controller('Controller1', ...);

var myApp = angular.module('myApp',[...]);
myApp.controller('Controller2', ...);

After the redeclare, Controller1 stops working and raises the OP error.

Why not use tables for layout in HTML?

See this duplicate question.

One item you're forgetting there is accessibility. Table-based layouts don't translate as well if you need to use a screen reader, for example. And if you do work for the government, supporting accessible browsers like screen readers may be required.

I also think you underestimate the impact of some of the things you mentioned in the question. For example, if you are both the designer and the programmer, you may not have a full appreciation of how well it separates presentation from content. But once you get into a shop where they are two distinct roles the advantages start to become clearer.

If you know what you're doing and have good tools, CSS really does have significant advantages over tables for layout. And while each item by itself may not justify abandoning tables, taken together it's generally worth it.

Count indexes using "for" in Python

In additon to other answers - very often, you do not have to iterate using the index but you can simply use a for-each expression:

my_list = ['a', 'b', 'c']
for item in my_list:
    print item

Is there a way to get the source code from an APK file?

This site https://www.apkdecompilers.com/ did it automatically.

I tried the site mentioned in the accepted answer first but that didn't work for me.

How to delete columns that contain ONLY NAs?

Because performance was really important for me, I benchmarked all the functions above.

NOTE: Data from @Simon O'Hanlon's post. Only with size 15000 instead of 10.

library(tidyverse)
library(microbenchmark)

set.seed(123)
df <- data.frame(id = 1:15000,
                 nas = rep(NA, 15000), 
                 vals = sample(c(1:3, NA), 15000,
                               repl = TRUE))
df

MadSconeF1 <- function(x) x[, colSums(is.na(x)) != nrow(x)]

MadSconeF2 <- function(x) x[colSums(!is.na(x)) > 0]

BradCannell <- function(x) x %>% select_if(~sum(!is.na(.)) > 0)

SimonOHanlon <- function(x) x[ , !apply(x, 2 ,function(y) all(is.na(y)))]

jsta <- function(x) janitor::remove_empty(x)

SiboJiang <- function(x) x %>% dplyr::select_if(~!all(is.na(.)))

akrun <- function(x) Filter(function(y) !all(is.na(y)), x)

mbm <- microbenchmark(
  "MadSconeF1" = {MadSconeF1(df)},
  "MadSconeF2" = {MadSconeF2(df)},
  "BradCannell" = {BradCannell(df)},
  "SimonOHanlon" = {SimonOHanlon(df)},
  "SiboJiang" = {SiboJiang(df)},
  "jsta" = {jsta(df)}, 
  "akrun" = {akrun(df)},
  times = 1000)

mbm

Results:

Unit: microseconds
         expr    min      lq      mean  median      uq      max neval  cld
   MadSconeF1  154.5  178.35  257.9396  196.05  219.25   5001.0  1000 a   
   MadSconeF2  180.4  209.75  281.2541  226.40  251.05   6322.1  1000 a   
  BradCannell 2579.4 2884.90 3330.3700 3059.45 3379.30  33667.3  1000    d
 SimonOHanlon  511.0  565.00  943.3089  586.45  623.65 210338.4  1000  b  
    SiboJiang 2558.1 2853.05 3377.6702 3010.30 3310.00  89718.0  1000    d
         jsta 1544.8 1652.45 2031.5065 1706.05 1872.65  11594.9  1000   c 
        akrun   93.8  111.60  139.9482  121.90  135.45   3851.2  1000 a


autoplot(mbm)

enter image description here

mbm %>% 
  tbl_df() %>%
  ggplot(aes(sample = time)) + 
  stat_qq() + 
  stat_qq_line() +
  facet_wrap(~expr, scales = "free")

enter image description here

How can I select item with class within a DIV?

If you want to select every element that has class attribute "myclass" use

$('#mydiv .myclass');

If you want to select only div elements that has class attribute "myclass" use

$("div#mydiv div.myclass");

find more about jquery selectors refer these articles

Catch Ctrl-C in C

With a signal handler.

Here is a simple example flipping a bool used in main():

#include <signal.h>

static volatile int keepRunning = 1;

void intHandler(int dummy) {
    keepRunning = 0;
}

// ...

int main(void) {

   signal(SIGINT, intHandler);

   while (keepRunning) { 
      // ...

Edit in June 2017: To whom it may concern, particularly those with an insatiable urge to edit this answer. Look, I wrote this answer seven years ago. Yes, language standards change. If you really must better the world, please add your new answer but leave mine as is. As the answer has my name on it, I'd prefer it to contain my words too. Thank you.

How to read a line from a text file in c/c++?

In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:

#include <string>
#include <iostream>
#include <fstream>

int main() {
    std::ifstream input("filename.txt");
    std::string line;

    while( std::getline( input, line ) ) {
        std::cout<<line<<'\n';
    }

    return 0;
}

This program reads each line from a file and echos it to the console.

For C you're probably looking at using fgets, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:

#include <stdio.h>

int main() {
    char line[1024];
    FILE *fp = fopen("filename.txt","r");

    //Checks if file is empty
    if( fp == NULL ) {                       
        return 1;
    }

    while( fgets(line,1024,fp) ) {
        printf("%s\n",line);
    }

    return 0;
}

With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.

The view didn't return an HttpResponse object. It returned None instead

Because the view must return render, not just call it. Change the last line to

return render(request, 'auth_lifecycle/user_profile.html',
           context_instance=RequestContext(request))

How to log Apache CXF Soap Request and Soap Response using Log4j?

Procedure for global setting of client/server logging of SOAP/REST requests/ responses with log4j logger. This way you set up logging for the whole application without having to change the code, war, jar files, etc.

  1. install file cxf-rt-features-logging-X.Y.Z.jar to your CLASS_PATH

  2. create file (path for example: /opt/cxf/cxf-logging.xml):

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <cxf:bus>
     <cxf:features>
     <bean class="org.apache.cxf.ext.logging.LoggingFeature">
     <property name="prettyLogging" value="true"/>
     </bean>
     </cxf:features>
     </cxf:bus>
     </beans>
    
  3. set logging for org.apache.cxf (log4j 1.x) log4j.logger.org.apache.cxf=INFO,YOUR_APPENDER

  4. set these properties on java start-up

java ... -Dcxf.config.file.url=file:///opt/cxf/cxf-logging.xml -Dorg.apache.cxf.Logger=org.apache.cxf.common.logging.Log4jLogger -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true -Dcom.sun.xml.internal.ws.transport.http.HttpAdapter.dump=true ...

I don't know why, but it is necessary to set variables as well com.sun.xml.*

Clear Cache in Android Application programmatically

I think you're supposed to place clearApplicationData() before the super.OnDestroy().

Your app can't process any methods when it has been shut down.

What does a circled plus mean?

This is not an plus, but the sign for the binary operator XOR

a   b   a XOR b
0   0   0
0   1   1
1   0   1
1   1   0

SQLiteDatabase.query method

tableColumns

  • null for all columns as in SELECT * FROM ...
  • new String[] { "column1", "column2", ... } for specific columns as in SELECT column1, column2 FROM ... - you can also put complex expressions here:
    new String[] { "(SELECT max(column1) FROM table1) AS max" } would give you a column named max holding the max value of column1

whereClause

  • the part you put after WHERE without that keyword, e.g. "column1 > 5"
  • should include ? for things that are dynamic, e.g. "column1=?" -> see whereArgs

whereArgs

  • specify the content that fills each ? in whereClause in the order they appear

the others

  • just like whereClause the statement after the keyword or null if you don't use it.

Example

String[] tableColumns = new String[] {
    "column1",
    "(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
    "value1",
    "value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
        null, null, orderBy);

// since we have a named column we can do
int idx = c.getColumnIndex("max");

is equivalent to the following raw query

String queryString =
    "SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
    "WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);

By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '.

Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";

because if value contains a ' your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--" might even drop your table since the statement would become two statements and a comment:

SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'

using the args version XYZ'; DROP TABLE table1;-- would be escaped to 'XYZ''; DROP TABLE table1;--' and would only be treated as a value. Even if the ' is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int and other primitives directly into whereClause though)

Where do I find the definition of size_t?

In minimalistic programs where a size_t definition was not loaded "by chance" in some include but I still need it in some context (for example to access std::vector<double>), then I use that context to extract the correct type. For example typedef std::vector<double>::size_type size_t.

(Surround with namespace {...} if necessary to make the scope limited.)

Comparing double values in C#

To compare floating point, double or float types, use the specific method of CSharp:

if (double1.CompareTo(double2) > 0)
{
    // double1 is greater than double2
}
if (double1.CompareTo(double2) < 0)
{
    // double1 is less than double2
}
if (double1.CompareTo(double2) == 0)
{
    // double1 equals double2
}

https://docs.microsoft.com/en-us/dotnet/api/system.double.compareto?view=netcore-3.1

How to set an environment variable in a running docker container

Here's how you can modify a running container to update its environment variables. This assumes you're running on Linux. I tested it with Docker 19.03.8

Live Restore

First, ensure that your Docker daemon is set to leave containers running when it's shut down. Edit your /etc/docker/daemon.json, and add "live-restore": true as a top-level key.

sudo vim /etc/docker/daemon.json

My file looks like this:

{
    "default-runtime": "nvidia",
    "runtimes": {
        "nvidia": {
            "path": "nvidia-container-runtime",
            "runtimeArgs": []
        }
    },
    "live-restore": true
}

Taken from here.

Get the Container ID

Save the ID of the container you want to edit for easier access to the files.

export CONTAINER_ID=`docker inspect --format="{{.Id}}" <YOUR CONTAINER NAME>`

Edit Container Configuration

Edit the configuration file, go to the "Env" section, and add your key.

sudo vim /var/lib/docker/containers/$CONTAINER_ID/config.v2.json

My file looks like this:

...,"Env":["TEST=1",...

Stop and Start Docker

I found that restarting Docker didn't work, I had to stop and then start Docker with two separate commands.

sudo systemctl stop docker
sudo systemctl start docker

Because of live-restore, your containers should stay up.

Verify That It Worked

docker exec <YOUR CONTAINER NAME> bash -c 'echo $TEST'

Single quotes are important here.

You can also verify that the uptime of your container hasn't changed:

docker ps

How to unapply a migration in ASP.NET Core with EF Core

To "unapply" the most (recent?) migration after it has already been applied to the database:

  1. Open the SQL Server Object Explorer (View -> "SQL Server Object Explorer")
  2. Navigate to the database that is linked to your project by expanding the small triangles to the side.
  3. Expand "Tables"
  4. Find the table named "dbo._EFMigrationsHistory".
  5. Right click on it and select "View Data" to see the table entries in Visual Studio.
  6. Delete the row corresponding to your migration that you want to unapply (Say "yes" to the warning, if prompted).
  7. Run "dotnet ef migrations remove" again in the command window in the directory that has the project.json file. Alternatively, run "Remove-Migration" command in the package manager console.

Hope this helps and is applicable to any migration in the project... I tested this out only to the most recent migration...

Happy coding!

Using Mockito to mock classes with generic parameters

One other way around this is to use @Mock annotation instead. Doesn't work in all cases, but looks much sexier :)

Here's an example:

@RunWith(MockitoJUnitRunner.class)
public class FooTests {

    @Mock
    public Foo<Bar> fooMock;

    @Test
    public void testFoo() {
        when(fooMock.getValue()).thenReturn(new Bar());
    }
}

The MockitoJUnitRunner initializes the fields annotated with @Mock.

Django - filtering on foreign key properties

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

Convert Enumeration to a Set/List

There is a simple example of convert enumeration to list. for this i used Collections.list(enum) method.

public class EnumerationToList {

    public static void main(String[] args) {
        Vector<String> vt = new Vector<String>();
        vt.add("java");
        vt.add("php");
        vt.add("array");
        vt.add("string");
        vt.add("c");

        Enumeration<String> enm = vt.elements();
        List<String> ll = Collections.list(enm);
        System.out.println("List elements: " + ll);
    }

}

Reference : How to convert enumeration to list

How can I create a temp file with a specific extension with .NET?

I mixed @Maxence and @Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method (the fileName is the name of a new file created) adding the extension preferred.

string GetNewTempFile(string extension)
{
    if (!extension.StartWith(".")) extension="." + extension;
    string fileName;
    bool bCollisions = false;
    do {
        fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension);
        try
        {
            using (new FileStream(fileName, FileMode.CreateNew)) { }
            bCollisions = false;
        }
        catch (IOException)
        {
            bCollisions = true;
        }
    }
    while (bCollisions);
    return fileName;
}

Laravel migration table field's type change

First composer requires doctrine/dbal, then:

$table->longText('column_name')->change();

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

pandas: to_numeric for multiple columns

If you are looking for a range of columns, you can try this:

df.iloc[7:] = df.iloc[7:].astype(float)

The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.

I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.

This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.

Test if a command outputs an empty string

sometimes "something" may come not to stdout but to the stderr of the testing application, so here is the fix working more universal way:

if [[ $(partprobe ${1} 2>&1 | wc -c) -ne 0 ]]; then
    echo "require fixing GPT parititioning"
else
    echo "no GPT fix necessary"
fi

PHP foreach loop key value

You can access your array keys like so:

foreach ($array as $key => $value)

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

How can I change the Y-axis figures into percentages in a barplot?

Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:

scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))

This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).

Returning Arrays in Java

Of course the method numbers() returns an array, it's just that you're doing nothing with it. Try this in main():

int[] array = numbers();                    // obtain the array
System.out.println(Arrays.toString(array)); // now print it

That will show the array in the console.