Programs & Examples On #Jpeg

JPEG is a commonly used method of lossy compression for digital photography (image).

JPG vs. JPEG image formats

No difference at all.

I personally prefer having 3 letters extensions, but you might prefer having the full name.
It's pure aestetics (personal taste), nothing else.
The format doesn't change.

You can rename the jpeg files into jpg (or vice versa) an nothing changes: they will open in your picture viewer.

By opening both a JPG and a JPEG file with an hex editor, you will notice that they share the very same heading information.

Use PHP to convert PNG to JPG with compression?

This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:

<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>

Hope that helps

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Convert RGBA PNG to RGB with PIL

import Image

def fig2img ( fig ): """ @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it @param fig a matplotlib figure @return a Python Imaging Library ( PIL ) image """ # put the figure pixmap into a numpy array buf = fig2data ( fig ) w, h, d = buf.shape return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )

def fig2data ( fig ): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer fig.canvas.draw ( )

# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )

# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf

def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True): if not is_already_saved: background = Image.new("RGB", img.size, c) background.paste(img, mask=img.split()[3]) # 3 is the alpha channel

    background.save(path, 'JPEG', quality=100)   
    is_already_saved = True
if if_load:
    if is_already_saved:
        im = Image.open(path)
        return np.array(im)
    else:
        raise ValueError('No image to load.')

Convert SVG image to PNG with PHP

This is v. easy, have been doing work on this for the past few weeks.

You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.

Open the terminal, and run this command:

java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg

That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,

import os

svgs = ('test1.svg', 'test2.svg', 'etc.svg') 
for svg in svgs:
    os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')

Reading an image file in C/C++

You could write your own by looking at the JPEG format.

That said, try a pre-existing library like CImg, or Boost's GIL. Or for strictly JPEG's, libjpeg. There is also the CxImage class on CodeProject.

Here's a big list.

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

matplotlib savefig in jpeg format

I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig.

To upgrade to matplotlib 1.1.0 with pip, use this command:

pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'

EDIT (to respond to comment):

pylab is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.

On my system, pylab is just this:

from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__

You can see that pylab is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab or with matplotlib.pyplot.

If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.

Changing all files' extensions in a folder with one command on Windows

on CMD

type

ren *.* *.jpg

. will select all files, and rename to * (what ever name they have) plus extension to jpg

Python Image Library fails with message "decoder JPEG not available" - PIL

The followed works on ubuntu 12.04:

pip uninstall PIL
apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev
pip install PIL --upgrade

when your see "-- JPEG support avaliable" that means it works.

But, if it still doesn't work when your edit your jpeg image, check the python path !! my python path missed /usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/, so I edit the ~/.bashrc add the following code to this file:

Edit: export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/

then, finally, it works!!

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.

This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.

C# Base64 String to JPEG Image

Front :

  <Image Name="camImage"/>

Back:

 public async void Base64ToImage(string base64String)
        {
            // read stream
            var bytes = Convert.FromBase64String(base64String);
            var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

            // decode image
            var decoder = await BitmapDecoder.CreateAsync(image);
            image.Seek(0);

            // create bitmap
            var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
            await output.SetSourceAsync(image);

            camImage.Source = output;
        }

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

png has a wider color pallete than gif and gif is properitary while png is not. gif can do animations, what normal-png cannot. png-transparency is only supported by browser roughly more recent than IE6, but there is a Javascript fix for that problem. Both support alpha transparency. In general I would say that you should use png for most webgraphics while using jpeg for photos, screenshots, or similiar because png compression does not work too good on thoose.

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

Get Path from another app (WhatsApp)

You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below

 public static String getFilePathFromURI(Context context, Uri contentUri) {
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH  + fileName+".jpg");
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Then IOUtils class is like below

public class IOUtils {



private static final int BUFFER_SIZE = 1024 * 2;

private IOUtils() {
    // Utility class.
}

public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
    }
    return count;
}


}

How do you access the matched groups in a JavaScript regular expression?

Last but not least, I found one line of code that worked fine for me (JS ES6):

_x000D_
_x000D_
let reg = /#([\S]+)/igm; // Get hashtags._x000D_
let string = 'mi alegría es total! ?\n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';_x000D_
_x000D_
let matches = (string.match(reg) || []).map(e => e.replace(reg, '$1'));_x000D_
console.log(matches);
_x000D_
_x000D_
_x000D_

This will return:

['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']

jQuery: Load Modal Dialog Contents via Ajax

$(function ()    {
    $('<div>').dialog({
        modal: true,
        open: function ()
        {
            $(this).load('Sample.htm');
        },         
        height: 400,
        width: 400,
        title: 'Dynamically Loaded Page'
    });
});

http://www.devcurry.com/2010/06/load-page-dynamically-inside-jquery-ui.html

INSERT INTO...SELECT for all MySQL columns

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

Angular2 - Input Field To Accept Only Numbers

You can do this easily using a mask:

<input type='text' mask="99" formControlName="percentage" placeholder="0">

99 - optional 2 digits

Don't forget to import NgxMaskModule in your module:

imports: [
    NgxMaskModule.forRoot(),
]

What are the file limits in Git (number and size)?

As of 2018-04-20 Git for Windows has a bug which effectively limits the file size to 4GB max using that particular implementation (this bug propagates to lfs as well).

jQuery: go to URL with target="_blank"

Use,

var url = $(this).attr('href');
window.open(url, '_blank');

Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.

var url = $(this).prop('href');

Find maximum value of a column and return the corresponding row values using Pandas

The country and place is the index of the series, if you don't need the index, you can set as_index=False:

df.groupby(['country','place'], as_index=False)['value'].max()

Edit:

It seems that you want the place with max value for every country, following code will do what you want:

df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.

We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.

Have a ViewModel for the User

public class UserViewModel
{
  public int UserID { set;get;}
  public string FirstName { set;get;}
   //add remaining properties as per your requirement

}

and in your controller have a method to get a list of Users

public class UserController : Controller
{

   [HttpGet]
   public ActionResult List()
   {
     List<UserViewModel> objList=UserService.GetUsers();  // this method should returns list of  Users
     return View("users",objList)        
   }
}

Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)

and in your users.cshtml ( which is under Views/User folder),

 @model List<UserViewModel>

 <table>

 @foreach(UserViewModel objUser in Model)
 {
   <tr>
      <td>@objUser.UserId.ToString()</td>
      <td>@objUser.FirstName</td>
   </tr>
 }
 </table>

All Set now you can access the url like yourdomain/User/List and it will give you a list of users in an HTML table.

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

Run javascript function when user finishes typing instead of on key up?

It's just one line with underscore.js debounce function:

$('#my-input-box').keyup(_.debounce(doSomething , 500));

This basically says doSomething 500 milliseconds after I stop typing.

For more info: http://underscorejs.org/#debounce

git push rejected

If push request is shows Rejected, then try first pull from your github account and then try push.

Ex:

In my case it was giving an error-

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ashif8984/git-github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

****So what I did was-****

$ git pull
$ git push

And the code was pushed successfully into my Github Account.

Using sessions & session variables in a PHP Login Script

here is the simplest session code using php. We are using 3 files.

login.php

<?php  session_start();   // session starts with the help of this function 


if(isset($_SESSION['use']))   // Checking whether the session is already there or not if 
                              // true then header redirect it to the home page directly 
 {
    header("Location:home.php"); 
 }

if(isset($_POST['login']))   // it checks whether the user clicked login button or not 
{
     $user = $_POST['user'];
     $pass = $_POST['pass'];

      if($user == "Ank" && $pass == "1234")  // username is  set to "Ank"  and Password   
         {                                   // is 1234 by default     

          $_SESSION['use']=$user;


         echo '<script type="text/javascript"> window.open("home.php","_self");</script>';            //  On Successful Login redirects to home.php

        }

        else
        {
            echo "invalid UserName or Password";        
        }
}
 ?>
<html>
<head>

<title> Login Page   </title>

</head>

<body>

<form action="" method="post">

    <table width="200" border="0">
  <tr>
    <td>  UserName</td>
    <td> <input type="text" name="user" > </td>
  </tr>
  <tr>
    <td> PassWord  </td>
    <td><input type="password" name="pass"></td>
  </tr>
  <tr>
    <td> <input type="submit" name="login" value="LOGIN"></td>
    <td></td>
  </tr>
</table>
</form>

</body>
</html>

home.php

<?php   session_start();  ?>

<html>
  <head>
       <title> Home </title>
  </head>
  <body>
<?php
      if(!isset($_SESSION['use'])) // If session is not set then redirect to Login Page
       {
           header("Location:Login.php");  
       }

          echo $_SESSION['use'];

          echo "Login Success";

          echo "<a href='logout.php'> Logout</a> "; 
?>
</body>
</html>

logout.php

<?php
 session_start();

  echo "Logout Successfully ";
  session_destroy();   // function that Destroys Session 
  header("Location: Login.php");
?>

How to show validation message below each textbox using jquery?

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

Sending Multipart File as POST parameters with RestTemplate requests

If you have to send a multipart file that is composed, among other things, by an Object that needs to be converted with a specific HttpMessageConverter and you get the "no suitable HttpMessageConverter" error no matter what you try, you may want to try with this:

RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter converter = new FormHttpMessageConverter();

converter.addPartConverter(new TheRequiredHttpMessageConverter());
//for example, in my case it was "new MappingJackson2HttpMessageConverter()"

restTemplate.getMessageConverters().add(converter);

This solved the problem for me with a custom Object that, together with a file (instanceof FileSystemResource, in my case), was part of the multipart file I needed to send. I tried with TrueGuidance's solution (and many others found around the web) to no avail, then I looked at FormHttpMessageConverter's source code and tried this.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

Try this.

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var json = config.Formatters.JsonFormatter;
        json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }

        );
    }
}

Add IIS 7 AppPool Identities as SQL Server Logons

CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];

Get resultset from oracle stored procedure

In SQL Plus:

SQL> create procedure myproc (prc out sys_refcursor)
  2  is
  3  begin
  4     open prc for select * from emp;
  5  end;
  6  /

Procedure created.

SQL> var rc refcursor
SQL> execute myproc(:rc)

PL/SQL procedure successfully completed.

SQL> print rc

     EMPNO ENAME      JOB              MGR HIREDATE           SAL       COMM     DEPTNO
---------- ---------- --------- ---------- ----------- ---------- ---------- ----------
      7839 KING       PRESIDENT            17-NOV-1981       4999                    10
      7698 BLAKE      MANAGER         7839 01-MAY-1981       2849                    30
      7782 CLARKE     MANAGER         7839 09-JUN-1981       2449                    10
      7566 JONES      MANAGER         7839 02-APR-1981       2974                    20
      7788 SCOTT      ANALYST         7566 09-DEC-1982       2999                    20
      7902 FORD       ANALYST         7566 03-DEC-1981       2999                    20
      7369 SMITHY     CLERK           7902 17-DEC-1980       9988         11         20
      7499 ALLEN      SALESMAN        7698 20-FEB-1981       1599       3009         30
      7521 WARDS      SALESMAN        7698 22-FEB-1981       1249        551         30
      7654 MARTIN     SALESMAN        7698 28-SEP-1981       1249       1400         30
      7844 TURNER     SALESMAN        7698 08-SEP-1981       1499          0         30
      7876 ADAMS      CLERK           7788 12-JAN-1983       1099                    20
      7900 JAMES      CLERK           7698 03-DEC-1981        949                    30
      7934 MILLER     CLERK           7782 23-JAN-1982       1299                    10
      6668 Umberto    CLERK           7566 11-JUN-2009      19999          0         10
      9567 ALLBRIGHT  ANALYST         7788 02-JUN-2009      76999         24         10

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

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

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

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

Who sets response content-type in Spring MVC (@ResponseBody)

Note that in Spring MVC 3.1 you can use the MVC namespace to configure message converters:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

Or code-based configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    converters.add(stringConverter);

    // Add other converters ...
  }
}

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

Format number to 2 decimal places

This is how I used this is as an example:

CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost

How can I specify the schema to run an sql file against in the Postgresql command line

The PGOPTIONS environment variable may be used to achieve this in a flexible way.

In an Unix shell:

PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql

If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS only once and export it.

PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS

psql -d somebase
psql -d someotherbase
...

or invoke the top-level shell script with PGOPTIONS set from the outside

PGOPTIONS="--search_path=my_schema_01"  ./my-upgrade-script.sh

In Windows CMD environment, set PGOPTIONS=value should work the same.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like

order: [[1, 'asc']]

with an empty table, there is no row idx 1 -> this exception ensures. This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.

My solution:

// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];

if(srcCol >= aoColumns.length) {
    continue;
}

// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;

Can we open pdf file using UIWebView on iOS?

NSString *folderName=[NSString stringWithFormat:@"/documents/%@",[tempDictLitrature objectForKey:@"folder"]];
NSString *fileName=[tempDictLitrature objectForKey:@"name"];
[self.navigationItem setTitle:fileName];
NSString *type=[tempDictLitrature objectForKey:@"type"];

NSString *path=[[NSBundle mainBundle]pathForResource:fileName ofType:type inDirectory:folderName];

NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 730)];
[webView setBackgroundColor:[UIColor lightGrayColor]];
webView.scalesPageToFit = YES;

[[webView scrollView] setContentOffset:CGPointZero animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];

Hex-encoded String to Byte Array

I assume what you need is to convert a hex string into a byte array that equals that means the same thing as that hex string? Adding this method should do it for you, without any extra library importing:

public static byte[] hexToByteArray(String s) {
     String[] strBytes = s.split("(?<=\\G.{2})");
     byte[] bytes = new byte[strBytes.length];
     for(int i = 0; i < strBytes.length; i++)
         bytes[i] = (byte)Integer.parseInt(strBytes[i], 16);
     return bytes;
}

How to overcome the CORS issue in ReactJS

the simplest way what I found from a tutorial of "TraversyMedia" is that just use https://cors-anywhere.herokuapp.com in 'axios' or 'fetch' api

https://cors-anywhere.herokuapp.com/{type_your_url_here} 

e.g.

axios.get(`https://cors-anywhere.herokuapp.com/https://www.api.com/`)

and in your case edit url as

url: 'https://cors-anywhere.herokuapp.com/https://www.api.com',

How to include view/partial specific styling in AngularJS

Awesome, thank you!! Just had to make a few adjustments to get it working with ui-router:

    var app = app || angular.module('app', []);

    app.directive('head', ['$rootScope', '$compile', '$state', function ($rootScope, $compile, $state) {

    return {
        restrict: 'E',
        link: function ($scope, elem, attrs, ctrls) {

            var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
            var el = $compile(html)($scope)
            elem.append(el);
            $scope.routeStyles = {};

            function applyStyles(state, action) {
                var sheets = state ? state.css : null;
                if (state.parent) {
                    var parentState = $state.get(state.parent)
                    applyStyles(parentState, action);
                }
                if (sheets) {
                    if (!Array.isArray(sheets)) {
                        sheets = [sheets];
                    }
                    angular.forEach(sheets, function (sheet) {
                        action(sheet);
                    });
                }
            }

            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {

                applyStyles(fromState, function(sheet) {
                    delete $scope.routeStyles[sheet];
                    console.log('>> remove >> ', sheet);
                });

                applyStyles(toState, function(sheet) {
                    $scope.routeStyles[sheet] = sheet;
                    console.log('>> add >> ', sheet);
                });
            });
        }
    }
}]);

Java: splitting the filename into a base and extension

Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm

such an utility class :

class Filename {
  private String fullPath;
  private char pathSeparator, extensionSeparator;

  public Filename(String str, char sep, char ext) {
    fullPath = str;
    pathSeparator = sep;
    extensionSeparator = ext;
  }

  public String extension() {
    int dot = fullPath.lastIndexOf(extensionSeparator);
    return fullPath.substring(dot + 1);
  }

  public String filename() { // gets filename without extension
    int dot = fullPath.lastIndexOf(extensionSeparator);
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(sep + 1, dot);
  }

  public String path() {
    int sep = fullPath.lastIndexOf(pathSeparator);
    return fullPath.substring(0, sep);
  }
}

usage:

public class FilenameDemo {
  public static void main(String[] args) {
    final String FPATH = "/home/mem/index.html";
    Filename myHomePage = new Filename(FPATH, '/', '.');
    System.out.println("Extension = " + myHomePage.extension());
    System.out.println("Filename = " + myHomePage.filename());
    System.out.println("Path = " + myHomePage.path());
  }
}

How to check the function's return value if true or false

ValidateForm returns boolean,not a string.
When you do this if(ValidateForm() == 'false'), is the same of if(false == 'false'), which is not true.

function post(url, formId) {
    if(!ValidateForm()) {
        // False
    } else {
        // True
    }
}

Setting up an MS-Access DB for multi-user access

The correct way of building client/server Microsoft Access applications where the data is stored in a RDBMS is to use the Linked Table method. This ensures Data Isolation and Concurrency is maintained between the Microsoft Access client application and the RDBMS data with no additional and unnecessary programming logic and code which makes maintenance more difficult, and adds to development time.

see: http://claysql.blogspot.com/2014/08/normal-0-false-false-false-en-us-x-none.html

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

Bootstrap carousel resizing image

Had the same problem and none of the CSS solutions presented here worked.

What worked for me was setting up a height="360" without setting any width. My photos aren't the same size and like this they have room to adjust their with but keep the height fixed.

Java: Getting a substring from a string starting after a particular character

what have you tried? it's very simple:

String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)

How do I control how Emacs makes backup files?

The accepted answer is good, but it can be greatly improved by additionally backing up on every save and backing up versioned files.

First, basic settings as described in the accepted answer:

(setq version-control t     ;; Use version numbers for backups.
      kept-new-versions 10  ;; Number of newest versions to keep.
      kept-old-versions 0   ;; Number of oldest versions to keep.
      delete-old-versions t ;; Don't ask to delete excess backup versions.
      backup-by-copying t)  ;; Copy all files, don't rename them.

Next, also backup versioned files, which Emacs does not do by default (you don't commit on every save, right?):

(setq vc-make-backup-files t)

Finally, make a backup on each save, not just the first. We make two kinds of backups:

  1. per-session backups: once on the first save of the buffer in each Emacs session. These simulate Emac's default backup behavior.

  2. per-save backups: once on every save. Emacs does not do this by default, but it's very useful if you leave Emacs running for a long time.

The backups go in different places and Emacs creates the backup dirs automatically if they don't exist:

;; Default and per-save backups go here:
(setq backup-directory-alist '(("" . "~/.emacs.d/backup/per-save")))

(defun force-backup-of-buffer ()
  ;; Make a special "per session" backup at the first save of each
  ;; emacs session.
  (when (not buffer-backed-up)
    ;; Override the default parameters for per-session backups.
    (let ((backup-directory-alist '(("" . "~/.emacs.d/backup/per-session")))
          (kept-new-versions 3))
      (backup-buffer)))
  ;; Make a "per save" backup on each save.  The first save results in
  ;; both a per-session and a per-save backup, to keep the numbering
  ;; of per-save backups consistent.
  (let ((buffer-backed-up nil))
    (backup-buffer)))

(add-hook 'before-save-hook  'force-backup-of-buffer)

I became very interested in this topic after I wrote $< instead of $@ in my Makefile, about three hours after my previous commit :P

The above is based on an Emacs Wiki page I heavily edited.

assign multiple variables to the same value in Javascript

The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment.

let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);

ReactJS: Warning: setState(...): Cannot update during an existing state transition

This same warning will be emitted on any state changes done in a render() call.

An example of a tricky to find case: When rendering a multi-select GUI component based on state data, if state has nothing to display, a call to resetOptions() is considered state change for that component.

The obvious fix is to do resetOptions() in componentDidUpdate() instead of render().

JavaScript validation for empty input field

_x000D_
_x000D_
<pre>_x000D_
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">_x000D_
           <input type="text"   id="name"   name="name" /> _x000D_
           <input type="submit"/>_x000D_
       </form>_x000D_
    </pre>_x000D_
_x000D_
<script language="JavaScript" type="text/javascript">_x000D_
  var frmvalidator = new Validator("myform");_x000D_
  frmvalidator.EnableFocusOnError(false);_x000D_
  frmvalidator.EnableMsgsTogether();_x000D_
  frmvalidator.addValidation("name", "req", "Plese Enter Name");_x000D_
</script>
_x000D_
_x000D_
_x000D_

before using above code you have to add the gen_validatorv31.js file

How to Execute a Python File in Notepad ++?

All the answers for the Run->Run menu option go with the "/K" switch of cmd, so the terminal stays open, or "-i" for python.exe so python forces interactive mode - both to preserve the output for you to observe.

Yet in cmd /k you have to type exit to close it, in the python -i - quit(). If that is too much typing for your liking (for me it sure is :), the Run command to use is

cmd /k C:\Python27\python.exe  "$(FULL_CURRENT_PATH)" & pause & exit

C:\Python27\python.exe - obviously the full path to your python install (or just python if you want to go with the first executable in your user's path).

& is unconditional execution of the next command in Windows - unconditional as it runs regardless of the RC of the previous command (&& is "and" - run only if the previous completed successfully, || - is "or").

pause - prints "Press any key to continue . . ." and waits for any key (that output can be suppressed if need).

exit - well, types the exit for you :)

So at the end, cmd runs python.exe which executes the current file and keeps the window opened, pause waits for you to press any key, and exit finally close the window once you press that any key.

Difference between Dictionary and Hashtable

Dictionary is typed (so valuetypes don't need boxing), a Hashtable isn't (so valuetypes need boxing). Hashtable has a nicer way of obtaining a value than dictionary IMHO, because it always knows the value is an object. Though if you're using .NET 3.5, it's easy to write an extension method for dictionary to get similar behavior.

If you need multiple values per key, check out my sourcecode of MultiValueDictionary here: multimap in .NET

Passing a 2D array to a C++ function

anArray[10][10] is not a pointer to a pointer, it is a contiguous chunk of memory suitable for storing 100 values of type double, which compiler knows how to address because you specified the dimensions. You need to pass it to a function as an array. You can omit the size of the initial dimension, as follows:

void f(double p[][10]) {
}

However, this will not let you pass arrays with the last dimension other than ten.

The best solution in C++ is to use std::vector<std::vector<double> >: it is nearly as efficient, and significantly more convenient.

How to float a div over Google Maps?

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

Just need to move the map below this box. Work to me.

From Google

Address already in use: JVM_Bind java

In windows this scenario happens when Eclipse crashes without a clean shutdown it will have the local Jetty or Tomcat server keep running. When you reopen Eclipse and try to start server again this will lead to the "Address already in use: JVM_Bind"

You can solve this by opening Task Manager and find the javaw.exe process and ending it.

Then you can restart the server on Eclipse.

enter image description here

'this' is undefined in JavaScript class methods

JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:

Ninja = function (name) {
    this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'

enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'

Note that Ninja instances have the same properties but aNinja cannot access the properties of enemyNinja. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype:

Ninja.prototype.jump = function () {
   return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'

Calling this directly will throw an error because this only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window in a browser)

React Js conditionally applying class attributes

you can simply do the following for example.

let currentDir = i18n && i18n.language ? i18n.language == 'en' ? "ml" : "mr" : "ml";

className={`flex flex-col lg:flex-row list-none ${currentDir}-auto`}

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

Its worth mentioning that the default for an 'Any CPU' compile now checks the 'Prefer 32bit' check box. Being set to AnyCPU, on a 64bit OS with 16gb of RAM can still hit an out of memory exception at 2gb if this is checked.

Prefer32BitCheckBox

convert a JavaScript string variable to decimal/money

Yes -- parseFloat.

parseFloat(document.getElementById(amtid4).innerHTML);

For formatting numbers, use toFixed:

var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);

num is now a string with the number formatted with two decimal places.

Is it possible to output a SELECT statement from a PL/SQL block?

You need to use Native dynamic SQL. Also, you do not need BEGIN-END to run SQL command:

declare
  l_tabname VARCHAR2(100) := 'dual';
  l_val1    VARCHAR2(100):= '''foo''';
  l_val2    VARCHAR2(100):= '''bar''';
  l_sql     VARCHAR2(1000);  
begin
  l_sql:= 'SELECT '||l_val1||','||l_val2||' FROM '||l_tabname;
  execute immediate l_sql;
  dbms_output.put_line(l_sql);
end;
/

Output:
 SELECT 'foo','bar' FROM dual

Is there an equivalent of lsusb for OS X

If you are a user of MacPorts, you may simply install usbutils

sudo port install usbutils

If you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools.

How do you synchronise projects to GitHub with Android Studio?

This isn't specific to Android Studio, but a generic behaviour with Intellij's IDEA.

Go to: Preferences > Version Control > GitHub

Also note that you don't need the github integration: the standard git functions should be enough (VCS > Git, Tool Windows > Changes)

jQuery.inArray(), how to use it right?

$.inArray returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
} 

include antiforgerytoken in ajax post ASP.NET MVC

I know this is an old question. But I will add my answer anyway, might help someone like me.

If you dont want to process the result from the controller's post action, like calling the LoggOff method of Accounts controller, you could do as the following version of @DarinDimitrov 's answer:

@using (Html.BeginForm("LoggOff", "Accounts", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<!-- this could be a button -->
<a href="#" id="ajaxSubmit">Submit</a>

<script type="text/javascript">
    $('#ajaxSubmit').click(function () {

        $('#__AjaxAntiForgeryForm').submit();

        return false;
    });
</script>

what is trailing whitespace and how can I handle this?

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.

Error "The connection to adb is down, and a severe error has occurred."

Here is a script I run to restart adb (Android Debug Bridge) server:

#!/usr/bin/env bash

## Summary: restart adb (Android Debug Brdige) server.

## adb binary full path
ADB_BIN=./adb


if pgrep adb >/dev/null 2>&1
then
    echo "adb is running"
    echo "terminating adb ..."
    $ADB_BIN kill-server
    if pgrep adb >/dev/null 2>&1
    then
        echo "did not work"
        echo "kill adb processes by killall"
        killall -9 adb
    else
        echo "terminated"
    fi
else
    echo "adb is not running"
fi

echo "starting adb ..."

$ADB_BIN start-server

echo "adb process:"

echo `pgrep adb`

echo "done"

# END

Deleting elements from std::set while iterating

C++20 will have "uniform container erasure", and you'll be able to write:

std::erase_if(numbers, [](int n){ return n % 2 == 0 });

And that will work for vector, set, deque, etc. See cppReference for more info.

What exactly is Spring Framework for?

The advantage is Dependency Injection (DI). It means outsourcing the task of object creation.Let me explain with an example.

public interface Lunch
{
   public void eat();
}

public class Buffet implements Lunch
{
   public void eat()
   {
      // Eat as much as you can 
   }
}

public class Plated implements Lunch
{
   public void eat()
   {
      // Eat a limited portion
   }
}

Now in my code I have a class LunchDecide as follows:

public class LunchDecide {
    private Lunch todaysLunch;
    public LunchDecide(){
        this.todaysLunch = new Buffet(); // choose Buffet -> eat as much as you want
        //this.todaysLunch = new Plated(); // choose Plated -> eat a limited portion 
    }
}

In the above class, depending on our mood, we pick Buffet() or Plated(). However this system is tightly coupled. Every time we need a different type of Object, we need to change the code. In this case, commenting out a line ! Imagine there are 50 different classes used by 50 different people. It would be a hell of a mess. In this case, we need to Decouple the system. Let's rewrite the LunchDecide class.

public class LunchDecide {
    private Lunch todaysLunch;
    public LunchDecide(Lunch todaysLunch){
        this.todaysLunch = todaysLunch
        }
    }

Notice that instead of creating an object using new keyword we passed the reference to an object of Lunch Type as a parameter to our constructor. Here, object creation is outsourced. This code can be wired either using Xml config file (legacy) or Java Annotations (modern). Either way, the decision on which Type of object would be created would be done there during runtime. An object would be injected by Xml into our code - Our Code is dependent on Xml for that job. Hence, Dependency Injection (DI). DI not only helps in making our system loosely coupled, it simplifies writing of Unit tests since it allows dependencies to be mocked. Last but not the least, DI streamlines Aspect Oriented Programming (AOP) which leads to further decoupling and increase of modularity. Also note that above DI is Constructor Injection. DI can be done by Setter Injection as well - same plain old setter method from encapsulation.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

Android SDK Build Tools are exactly what the name says they are; tools for building Android Applications.It is very important to use the latest build tools version (selected automatically by your IDE via the Android SDK) but the reason the old versions are left there is to support backward compatibility, that is If your projects depend on older versions of the Build Tools.

How to print the values of slices

You could use a for loop to print the []Project as shown in @VonC excellent answer.

package main

import "fmt"

type Project struct{ name string }

func main() {
    projects := []Project{{"p1"}, {"p2"}}
    for i := range projects {
        p := projects[i]
        fmt.Println(p.name) //p1, p2
    }
}

At least one JAR was scanned for TLDs yet contained no TLDs

apache-tomcat-8.0.33

If you want to enable debug logging in tomcat for TLD scanned jars then you have to change /conf/logging.properties file in tomcat directory.

uncomment the line :
org.apache.jasper.servlet.TldScanner.level = FINE

FINE level is for debug log.

This should work for normal tomcat.

If the tomcat is running under eclipse. Then you have to set the path of tomcat logging.properties in eclipse.

  1. Open servers view in eclipse.Stop the server.Double click your tomcat server.
    This will open Overview window for the server.
  2. Click on Open launch configuration.This will open another window.
  3. Go to the Arguments tab(second tab).Go to VM arguments section.
  4. paste this two line there :-
    -Djava.util.logging.config.file="{CATALINA_HOME}\conf\logging.properties"
    -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
    Here CATALINA_HOME is your PC's corresponding tomcat server directory.
  5. Save the Changes.Restart the server.

Now the jar files that scanned for TLDs should show in the log.

Row count on the Filtered data

I know this an old thread, but I found out using the Subtotal method in VBA also accurately renders a count of the rows. The formula I found is in this article, and looks like this:

Application.WorksheetFunction.Subtotal(2, .Range("A2:A" & .Rows(.Rows.Count).End(xlUp).Row))

I tested it and it came out accurately every time, rendering the correct number of visible rows in column A.

Hopefully this will help some other wayfarer of the 'Net like me.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

1) I am using WAMP.

2) I have installed Open Office (from apache http://www.openoffice.org/download/).

3) $output_dir = "C:/wamp/www/projectfolder/"; this is my project folder where i want to create output file.

4) I have already placed my input file here C:/wamp/www/projectfolder/wordfile.docx";

Then I Run My Code.. (given below)

<?php
    set_time_limit(0);
    function MakePropertyValue($name,$value,$osm){
    $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
    $oStruct->Name = $name;
    $oStruct->Value = $value;
    return $oStruct;
    }
    function word2pdf($doc_url, $output_url){

    //Invoke the OpenOffice.org service manager
    $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
    //Set the application to remain hidden to avoid flashing the document onscreen
    $args = array(MakePropertyValue("Hidden",true,$osm));
    //Launch the desktop
    $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
    //Load the .doc file, and pass in the "Hidden" property from above
    $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
    //Set up the arguments for the PDF output
    $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
    //print_r($export_args);
    //Write out the PDF
    $oWriterDoc->storeToURL($output_url,$export_args);
    $oWriterDoc->close(true);
    }

    $output_dir = "C:/wamp/www/projectfolder/";
    $doc_file = "C:/wamp/www/projectfolder/wordfile.docx";
    $pdf_file = "outputfile_name.pdf";

    $output_file = $output_dir . $pdf_file;
    $doc_file = "file:///" . $doc_file;
    $output_file = "file:///" . $output_file;
    word2pdf($doc_file,$output_file);
    ?>

Global constants file in Swift

Swift 4 Version

If you want to create a name for NotificationCenter:

extension Notification.Name {
    static let updateDataList1 = Notification.Name("updateDataList1")
}

Subscribe to notifications:

NotificationCenter.default.addObserver(self, selector: #selector(youFunction), name: .updateDataList1, object: nil)

Send notification:

NotificationCenter.default.post(name: .updateDataList1, object: nil)

If you just want a class with variables to use:

class Keys {
    static let key1 = "YOU_KEY"
    static let key2 = "YOU_KEY"
}

Or:

struct Keys {
    static let key1 = "YOU_KEY"
    static let key2 = "YOU_KEY"
}

How to get first N number of elements from an array

The following worked for me.

array.slice( where_to_start_deleting, array.length )

Here is an example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2, fruits.length);
//Banana,Orange  ->These first two we get as resultant

How to convert NSNumber to NSString

In Swift you can do like this

let number : NSNumber = 95
let str : String = number.stringValue

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

You can solve the problem by checking if your date matches a REGEX pattern. If not, then NULL (or something else you prefer).

In my particular case it was necessary because I have >20 DATE columns saved as CHAR, so I don't know from which column the error is coming from.

Returning to your query:

1. Declare a REGEX pattern.
It is usually a very long string which will certainly pollute your code (you may want to reuse it as well).

define REGEX_DATE = "'your regex pattern goes here'"

Don't forget a single quote inside a double quote around your Regex :-)

A comprehensive thread about Regex date validation you'll find here.

2. Use it as the first CASE condition:

To use Regex validation in the SELECT statement, you cannot use REGEXP_LIKE (it's only valid in WHERE. It took me a long time to understand why my code was not working. So it's certainly worth a note.

Instead, use REGEXP_INSTR
For entries not found in the pattern (your case) use REGEXP_INSTR (variable, pattern) = 0 .

    DEFINE REGEX_DATE = "'your regex pattern goes here'"

    SELECT   c.contract_num,
         CASE
            WHEN REGEXP_INSTR(c.event_dt, &REGEX_DATE) = 0 THEN NULL
            WHEN   (  MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                    - MIN (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                 / COUNT (c.event_occurrence) < 32
            THEN
              'Monthly'
            WHEN       (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) >= 32
                 AND   (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) < 91
            THEN
              'Quarterley'
            ELSE
              'Yearly'
         END
FROM     ps_ca_bp_events c
GROUP BY c.contract_num;

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

i had python 3.8.5 ..but it will not work with tenserflow..

so i installed python 3.7.9 and it worked.

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

How to make the Facebook Like Box responsive?

Colin's example for me clashed with the like button. So I adapted it to only target the Like Box.

.fb-like-box, .fb-like-box span, .fb-like-box span iframe[style] { width: 100% !important; }

Tested in most modern browsers.

jQuery UI Datepicker - Multiple Date Selections

I needed to do the same thing, so have written some JavaScript to enable this, using the onSelect and beforeShowDay events. It maintains its own array of selected dates, so unfortunately doesn't integrate with a textbox showing the current date, etc. I'm just using it as an inline control, and I can then query the array for the currently selected dates.
I used this code as a basis.

<script type="text/javascript">
// Maintain array of dates
var dates = new Array();

function addDate(date) {
    if (jQuery.inArray(date, dates) < 0) 
        dates.push(date);
}

function removeDate(index) {
    dates.splice(index, 1);
}

// Adds a date if we don't have it yet, else remove it
function addOrRemoveDate(date) {
    var index = jQuery.inArray(date, dates);
    if (index >= 0) 
        removeDate(index);
    else 
        addDate(date);
}

// Takes a 1-digit number and inserts a zero before it
function padNumber(number) {
    var ret = new String(number);
    if (ret.length == 1) 
        ret = "0" + ret;
    return ret;
}

jQuery(function () {
    jQuery("#datepicker").datepicker({
        onSelect: function (dateText, inst) {
            addOrRemoveDate(dateText);
        },
        beforeShowDay: function (date) {
            var year = date.getFullYear();
            // months and days are inserted into the array in the form, e.g "01/01/2009", but here the format is "1/1/2009"
            var month = padNumber(date.getMonth() + 1);
            var day = padNumber(date.getDate());
            // This depends on the datepicker's date format
            var dateString = month + "/" + day + "/" + year;

            var gotDate = jQuery.inArray(dateString, dates);
            if (gotDate >= 0) {
                // Enable date so it can be deselected. Set style to be highlighted
                return [true, "ui-state-highlight"];
            }
            // Dates not in the array are left enabled, but with no extra style
            return [true, ""];
        }
    });
});
</script>

Perform commands over ssh with Python

Keep it simple. No libraries required.

import subprocess

subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

XML Serialize generic list of serializable objects

knowTypeList parameter let serialize with DataContractSerializer several known types:

private static void WriteObject(
        string fileName, IEnumerable<Vehichle> reflectedInstances, List<Type> knownTypeList)
    {
        using (FileStream writer = new FileStream(fileName, FileMode.Append))
        {
            foreach (var item in reflectedInstances)
            {
                var serializer = new DataContractSerializer(typeof(Vehichle), knownTypeList);
                serializer.WriteObject(writer, item);
            }
        }
    }

Difference in Months between two dates in JavaScript

You could also consider this solution, this function returns the month difference in integer or number

Passing the start date as the first or last param, is fault tolerant. Meaning, the function would still return the same value.

_x000D_
_x000D_
const diffInMonths = (end, start) => {_x000D_
   var timeDiff = Math.abs(end.getTime() - start.getTime());_x000D_
   return Math.round(timeDiff / (2e3 * 3600 * 365.25));_x000D_
}_x000D_
_x000D_
const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));_x000D_
_x000D_
// shows month difference as integer/number_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How to set base url for rest in spring boot?

For Boot 2.0.0+ this works for me: server.servlet.context-path = /api

css absolute position won't work with margin-left:auto margin-right: auto

I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).

Done! The margin-left and margin-right AUTO for your .divtagABS will now work.

Import mysql DB with XAMPP in command LINE

mysql -h localhost -u username -p databasename < dump.sql

Why is setTimeout(fn, 0) sometimes useful?

Since it is being passed a duration of 0, I suppose it is in order to remove the code passed to the setTimeout from the flow of execution. So if it's a function that could take a while, it won't prevent the subsequent code from executing.

How to make a pure css based dropdown menu?

View code online on: WebCrafts.org

HTML code:

<body id="body">
<div id="navigation">
    <h2>
        Pure CSS Drop-down Menu
    </h2>
  <div id="nav" class="nav">
    <ul>
        <li><a href="#">Menu1</a></li>
        <li>
            <a href="#">Menu2</a>
          <ul>
                <li><a href="#">Sub-Menu1</a></li>
                <li>
                    <a href="#">Sub-Menu2</a>
                  <ul>
                        <li><a href="#">Demo1</a></li>
                      <li><a href="#">Demo2</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub-Menu3</a></li>
                <li><a href="#">Sub-Menu4</a></li>
            </ul>
        </li>
        <li><a href="#">Menu3</a></li>
        <li><a href="#">Menu4</a></li>
    </ul>
  </div>
</div>
</body>

Css code:

body{
    background-color:#111;
}

#navigation{
    text-align:center;
}
#navigation h2{
    color:#DDD;
}

.nav{
    display:inline-block;
    z-index:5;
    font-weight:bold;
}
.nav ul{
    width:auto;
    list-style:none;
}

.nav ul li{
    display:inline-block;
}

.nav ul li a{
    text-decoration:none;
    text-align:center;
    color:#222;
    display:block;
    width:120px;
    line-height:30px;
    background-color:gray;
}

.nav ul li a:hover{
    background-color:#EEC;   
}
.nav ul li ul{
    margin-top:0px;
    padding-left:0px;
    position:absolute;
    display:none;
}

.nav ul li:hover ul{
    display:block;
}

.nav ul li ul li{
    display:block;
}

.nav ul li ul li ul{
    margin-left:100%;
    margin-top:-30px;
    visibility:hidden;
}

.nav ul li ul li:hover ul{
    margin-left:100%;
    visibility:visible;
}

What are the advantages of NumPy over regular Python lists?

Here's a nice answer from the FAQ on the scipy.org website:

What advantages do NumPy arrays offer over (nested) Python lists?

Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

Update MongoDB field using value of another field

You should iterate through. For your specific case:

db.person.find().snapshot().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

Variable's memory size in Python

Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.

How to read a line from the console in C?

getline runnable example

getline was mentioned on this answer but here is an example.

It is POSIX 7, allocates memory for us, and reuses the allocated buffer on a loop nicely.

Pointer newbs, read this: Why is the first argument of getline a pointer to pointer "char**" instead of "char*"?

main.c

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char *line = NULL;
    size_t len = 0;
    ssize_t read = 0;
    while (1) {
        puts("enter a line");
        read = getline(&line, &len, stdin);
        if (read == -1)
            break;
        printf("line = %s", line);
        printf("line length = %zu\n", read);
        puts("");
    }
    free(line);
    return 0;
}

Compile and run:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

Outcome: this shows on therminal:

enter a line

Then if you type:

asdf

and press enter, this shows up:

line = asdf
line length = 5

followed by another:

enter a line

Or from a pipe to stdin:

printf 'asdf\nqwer\n' | ./main.out

gives:

enter a line
line = asdf
line length = 5

enter a line
line = qwer
line length = 5

enter a line

Tested on Ubuntu 20.04.

glibc implementation

No POSIX? Maybe you want to look at the glibc 2.23 implementation.

It resolves to getdelim, which is a simple POSIX superset of getline with an arbitrary line terminator.

It doubles the allocated memory whenever increase is needed, and looks thread-safe.

It requires some macro expansion, but you're unlikely to do much better.

How to move Docker containers between different hosts?

I tried many solutions for this, and this is the one that worked for me :

1.commit/save container to new image :

  1. ++ commit the container:
    # docker stop
    # docker commit CONTAINER_NAME
    # docker save --output IMAGE_NAME.tar IMAGE_NAME:TAG


ps:"Our container CONTAINER_NAME has a mounted volume at '/var/home'" ( you have to inspect your container to specify its volume path : # docker inspect CONTAINER_NAME )

  1. ++ save its volume : we will use an ubuntu image to do the thing.
    # mkdir backup
    # docker run --rm --volumes-from CONTAINER_NAME -v ${pwd}/backup:/backup ubuntu bash -c “cd /var/home && tar cvf /backup/volume_backup.tar .”

Now when you look at ${pwd}/backup , you will find our volume under tar format.
Until now, we have our conatainer's image 'IMAGE_NAME.tar' and its volume 'volume_backup.tar'.

Now you can , recreate the same old container on a new host.

Add two textbox values and display the sum in a third textbox automatically

try this

  function sum() {
       var txtFirstNumberValue = document.getElementById('txt1').value;
       var txtSecondNumberValue = document.getElementById('txt2').value;
       if (txtFirstNumberValue == "")
           txtFirstNumberValue = 0;
       if (txtSecondNumberValue == "")
           txtSecondNumberValue = 0;

       var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
       if (!isNaN(result)) {
           document.getElementById('txt3').value = result;
       }
   }

Adding a regression line on a ggplot

If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:

fit: your fit of a logistic regression curve

#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new 
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)

ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))

MongoDB: How to update multiple documents with a single command?

In the MongoDB Client, type:

db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})

New in version 3.2

Params::

{}:  select all records updated

Keyword argument multi not taken

"Logging out" of phpMyAdmin?

Simple seven step to solve issue in case of WampServer:

  1. Start WampServer
  2. Click on Folder icon Mysql -> Mysql Console
  3. Press Key Enter without password
  4. Execute Statement

    SET PASSWORD FOR root@localhost=PASSWORD('root');
    
  5. open D:\wamp\apps\phpmyadmin4.1.14\config.inc.php file set value

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = '';
    
  6. Restart All services

  7. Open phpMyAdmin in browser enter user root and pass root

Is there an "exists" function for jQuery?

$("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.

if($("selector").length){
   //code in the case
} 

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

fatal: The current branch master has no upstream branch

commit your code using

git commit -m "first commit"

then config your mail id using

git config user.email "[email protected]"

this is work for me

What is the difference between SessionState and ViewState?

Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It's a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.
View State on the other hand is information specific to particular web page. It is stored in a hidden field so that it isn't visible to the user. It is used to maintain the user's illusion that the page remembers what he did on it the last time - dont give him a clean page every time he posts back. Check this page for more.

Search for a string in all tables, rows and columns of a DB

I adapted a script originally written by Narayana Vyas Kondreddi in 2002. I changed the where clause to check text/ntext fields as well, by using patindex rather than like. I also changed the results table slightly. Unreasonably, I changed variable names, and aligned as I prefer (no disrespect to Mr. Kondretti). The user may want to change the data types searched. I used a global table to allow querying mid-processing, but a permanent table might be a smarter way to go.

/* original script by Narayana Vyas Kondreddi, 2002 */
/* adapted by Oliver Holloway, 2009 */

/* these lines can be replaced by use of input parameter for a proc */
declare @search_string varchar(1000);
set @search_string = 'what.you.are.searching.for';

/* create results table */
create table ##string_locations (
  table_name varchar(1000),
  field_name varchar(1000),
  field_value varchar(8000)
)
;
/* special settings */
set nocount on
;
/* declare variables */
declare
  @table_name varchar(1000),
  @field_name varchar(1000)
;
/* variable settings */
set @table_name = ''
;
set @search_string = QUOTENAME('%' + @search_string + '%','''')
;
/* for each table */
while @table_name is not null
begin

  set @field_name = ''
  set @table_name = (
    select MIN(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name))
    from INFORMATION_SCHEMA.TABLES
    where 
      table_type = 'BASE TABLE' and
      QUOTENAME(table_schema) + '.' + QUOTENAME(table_name) > @table_name and
      OBJECTPROPERTY(OBJECT_ID(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name)), 'IsMSShipped') = 0
  )

  /* for each string-ish field */
  while (@table_name is not null) and (@field_name is not null)
  begin
    set @field_name = (
      select MIN(QUOTENAME(column_name))
      from INFORMATION_SCHEMA.COLUMNS
      where 
        table_schema    = PARSENAME(@table_name, 2) and
        table_name  = PARSENAME(@table_name, 1) and
        data_type in ('char', 'varchar', 'nchar', 'nvarchar', 'text', 'ntext') and
        QUOTENAME(column_name) > @field_name
    )

    /* search that field for the string supplied */
    if @field_name is not null
    begin
      insert into ##string_locations
      exec(
        'select ''' + @table_name + ''',''' + @field_name + ''',' + @field_name + 
        'from ' + @table_name + ' (nolock) ' +
        'where patindex(' + @search_string + ',' + @field_name + ') > 0'  /* patindex works with char & text */
      )
    end
    ;
  end
  ;
end
;

/* return results */
select table_name, field_name, field_value from ##string_locations (nolock)
;
/* drop temp table */
--drop table ##string_locations
;

How to check if an email address is real or valid using PHP

You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //Email is valid
}

You can add another check if you want. Parse the domain out and then run checkdnsrr

if(checkdnsrr($domain)) {
     // Domain at least has an MX record, necessary to receive email
}

Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:

  1. Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat

    Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.

    In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.

  2. Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?

  3. If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.

Logging in Scala

Using slf4j and a wrapper is nice but the use of it's built in interpolation breaks down when you have more than two values to interpolate, since then you need to create an Array of values to interpolate.

A more Scala like solution is to use a thunk or cluster to delay the concatenation of the error message. A good example of this is Lift's logger

Log.scala Slf4jLog.scala

Which looks like this:

class Log4JLogger(val logger: Logger) extends LiftLogger {
  override def trace(msg: => AnyRef) = if (isTraceEnabled) logger.trace(msg)
}

Note that msg is a call-by-name and won't be evaluated unless isTraceEnabled is true so there's no cost in generating a nice message string. This works around the slf4j's interpolation mechanism which requires parsing the error message. With this model, you can interpolate any number of values into the error message.

If you have a separate trait that mixes this Log4JLogger into your class, then you can do

trace("The foobar from " + a + " doesn't match the foobar from " +
      b + " and you should reset the baz from " + c")

instead of

info("The foobar from {0} doesn't match the foobar from {1} and you should reset the baz from {c},
     Array(a, b, c))

How to get the currently logged in user's user id in Django?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

The current user is in request object, you can get it by:

def sample_view(request):
    current_user = request.user
    print current_user.id

request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

Uncaught TypeError: Cannot read property 'top' of undefined

Check if the jQuery object contains any element before you try to get its offset:

var nav = $('.content-nav');
if (nav.length) {
  var contentNav = nav.offset().top;
  ...continue to set up the menu
}

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

For me the issue was different: Angular-cli was not installed (I installed a new Node version using NVM and simply forgot to reinstall angular cli)

You can check running "ng version".

If you don't have it just run "npm install -g @angular/cli"

Difference between dangling pointer and memory leak

A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.

Common way to end up with a dangling pointer:

char *func()
{
   char str[10];
   strcpy(str, "Hello!");
   return str; 
}
//returned pointer points to str which has gone out of scope. 

You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)

Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.

int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!

A memory leak is memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which was the only reference to a memory location dynamically allocated (and not freed) which points somewhere else now.)

void func(){
    char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory

Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

How to prevent XSS with HTML/PHP?

Many frameworks help handle XSS in various ways. When rolling your own or if there's some XSS concern, we can leverage filter_input_array (available in PHP 5 >= 5.2.0, PHP 7.) I typically will add this snippet to my SessionController, because all calls go through there before any other controller interacts with the data. In this manner, all user input gets sanitized in 1 central location. If this is done at the beginning of a project or before your database is poisoned, you shouldn't have any issues at time of output...stops garbage in, garbage out.

/* Prevent XSS input */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
/* I prefer not to use $_REQUEST...but for those who do: */
$_REQUEST = (array)$_POST + (array)$_GET + (array)$_REQUEST;

The above will remove ALL HTML & script tags. If you need a solution that allows safe tags, based on a whitelist, check out HTML Purifier.


If your database is already poisoned or you want to deal with XSS at time of output, OWASP recommends creating a custom wrapper function for echo, and using it EVERYWHERE you output user-supplied values:

//xss mitigation functions
function xssafe($data,$encoding='UTF-8')
{
   return htmlspecialchars($data,ENT_QUOTES | ENT_HTML401,$encoding);
}
function xecho($data)
{
   echo xssafe($data);
}

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Mapping two integers to one, in a unique and deterministic way

It isn't that tough to construct a mapping:

   1  2  3  4  5  use this mapping if (a,b) != (b,a)
1  0  1  3  6 10
2  2  4  7 11 16
3  5  8 12 17 23
4  9 13 18 24 31
5 14 19 25 32 40

   1  2  3  4  5 use this mapping if (a,b) == (b,a) (mirror)
1  0  1  2  4  6
2  1  3  5  7 10
3  2  5  8 11 14
4  4  8 11 15 19
5  6 10 14 19 24


    0  1 -1  2 -2 use this if you need negative/positive
 0  0  1  2  4  6
 1  1  3  5  7 10
-1  2  5  8 11 14
 2  4  8 11 15 19
-2  6 10 14 19 24

Figuring out how to get the value for an arbitrary a,b is a little more difficult.

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

How can I limit possible inputs in a HTML5 "number" element?

As I found out you cannot use any of onkeydown, onkeypress or onkeyup events for a complete solution including mobile browsers. By the way onkeypress is deprecated and not present anymore in chrome/opera for android (see: UI Events W3C Working Draft, 04 August 2016).

I figured out a solution using the oninput event only. You may have to do additional number checking as required such as negative/positive sign or decimal and thousand separators and the like but as a start the following should suffice:

_x000D_
_x000D_
function checkMaxLength(event) {_x000D_
 // Prepare to restore the previous value._x000D_
 if (this.oldValue === undefined) {_x000D_
  this.oldValue = this.defaultValue;_x000D_
 }_x000D_
_x000D_
 if (this.value.length > this.maxLength) {_x000D_
  // Set back to the previous value._x000D_
  this.value = oldVal;_x000D_
 }_x000D_
 else {_x000D_
  // Store the previous value._x000D_
  this.oldValue = this.value;_x000D_
  _x000D_
  // Make additional checks for +/- or ./, etc._x000D_
  // Also consider to combine 'maxlength'_x000D_
  // with 'min' and 'max' to prevent wrong submits._x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

I would also recommend to combine maxlength with min and max to prevent wrong submits as stated above several times.

How to pass a function as a parameter in Java?

I used the command pattern that @jk. mentioned, adding a return type:

public interface Callable<I, O> {

    public O call(I input);   
}

Python requests - print entire http request (raw)?

An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.

It's as easy as this:

import requests
from requests_toolbelt.utils import dump

resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))

Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html

You can simply install it by typing:

pip install requests_toolbelt

Remove decimal values using SQL query

Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.

12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.

If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.

If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)

Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.

Determining the path that a yum package installed to

I don't know about yum, but rpm -ql will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.

How do I check if there are duplicates in a flat list?

Use set() to remove duplicates if all values are hashable:

>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
True

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

Why are Python's 'private' methods not actually private?

Why are Python's 'private' methods not actually private?

As I understand it, they can't be private. How could privacy be enforced?

The obvious answer is "private members can only be accessed through self", but that wouldn't work - self is not special in Python, it is nothing more than a commonly-used name for the first parameter of a function.

Execute command on all files in a directory

You can use xarg:

ls | xargs -L 1 -d '\n' your-desired-command 
  • -L 1 causes pass 1 item at a time

  • -d '\n' splits the output of ls based on new line.

How to append a char to a std::string?

I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.

    long start = clock();
    int a = 0;
    //100000000
    std::string ret;
    for (int i = 0; i < 60000000; i++)
    {
        ret.append(1, ' ');
        //ret += ' ';
        //ret.push_back(' ');
        //ret.insert(ret.end(), 1, ' ');
        //ret.resize(ret.size() + 1, ' ');
    }
    long stop = clock();
    long test = stop - start;
    return 0;

According to this test, results are :

     operation             time(ms)            note
------------------------------------------------------------------------
append                     66015
+=                         67328      1.02 time slower than 'append'
resize                     83867      1.27 time slower than 'append'
push_back & insert         90000      more than 1.36 time slower than 'append'

Conclusion

+= seems more understandable, but if you mind about speed, use append

How to resolve a Java Rounding Double issue

As the previous answers stated, this is a consequence of doing floating point arithmetic.

As a previous poster suggested, When you are doing numeric calculations, use java.math.BigDecimal.

However, there is a gotcha to using BigDecimal. When you are converting from the double value to a BigDecimal, you have a choice of using a new BigDecimal(double) constructor or the BigDecimal.valueOf(double) static factory method. Use the static factory method.

The double constructor converts the entire precision of the double to a BigDecimal while the static factory effectively converts it to a String, then converts that to a BigDecimal.

This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the BigDecimal constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.

double value = 0.585;
System.out.println(new BigDecimal(value));
System.out.println(BigDecimal.valueOf(value));

on my system gives

0.58499999999999996447286321199499070644378662109375
0.585

After MySQL install via Brew, I get the error - The server quit without updating PID file

I found that it was a permissions issue with the mysql folder.

chmod -R 777 /usr/local/var/mysql/ 

solved it for me.

Getting path relative to the current working directory?

Thanks to the other answers here and after some experimentation I've created some very useful extension methods:

public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from)
{
    return from.GetRelativePathTo(to);
}

public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
    Func<FileSystemInfo, string> getPath = fsi =>
    {
        var d = fsi as DirectoryInfo;
        return d == null ? fsi.FullName : d.FullName.TrimEnd('\\') + "\\";
    };

    var fromPath = getPath(from);
    var toPath = getPath(to);

    var fromUri = new Uri(fromPath);
    var toUri = new Uri(toPath);

    var relativeUri = fromUri.MakeRelativeUri(toUri);
    var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    return relativePath.Replace('/', Path.DirectorySeparatorChar);
}

Important points:

  • Use FileInfo and DirectoryInfo as method parameters so there is no ambiguity as to what is being worked with. Uri.MakeRelativeUri expects directories to end with a trailing slash.
  • DirectoryInfo.FullName doesn't normalize the trailing slash. It outputs whatever path was used in the constructor. This extension method takes care of that for you.

Is there a git-merge --dry-run option?

I'm surprised nobody has suggested using patches yet.

Say you'd like to test a merge from your_branch into master (I'm assuming you have master checked out):

$ git diff master your_branch > your_branch.patch
$ git apply --check your_branch.patch
$ rm your_branch.patch

That should do the trick.

If you get errors like

error: patch failed: test.txt:1
error: test.txt: patch does not apply

that means that the patch wasn't successful and a merge would produce conflicts. No output means the patch is clean and you'd be able to easily merge the branch


Note that this will not actually change your working tree (aside from creating the patch file of course, but you can safely delete that afterwards). From the git-apply documentation:

--check
    Instead of applying the patch, see if the patch is applicable to the
    current working tree and/or the index file and detects errors. Turns
    off "apply".

Note to anyone who is smarter/more experienced with git than me: please do let me know if I'm wrong here and this method does show different behaviour than a regular merge. It seems strange that in the 8+ years that this question has existed noone would suggest this seemingly obvious solution.

How to randomize two ArrayLists in the same fashion?

Wrap them in another class so that you can end up with a single array or List of those objects.

public class Data {
    private String txtFileName;
    private String imgFileName;

    // Add/generate c'tor, getter/setter, equals, hashCode and other boilerplate.
}

Usage example:

List<Data> list = new ArrayList<Data>();
list.add(new Data("H1.txt", "e1.jpg"));
list.add(new Data("H2.txt", "e2.jpg"));
// ...

Collections.shuffle(list);

Sample database for exercise

Why not download the English Wikipedia? There are compressed SQL files of various sizes, and it should certainly be large enough for you

The main articles are XML, so inserting them into the db is a bit more of a problem, but you might find there are other files there that suit you. For example, the inter-page links SQL file is 2.3GB compressed. Have a look at https://en.wikipedia.org/wiki/Wikipedia:Database_download for more info.

Oskar

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Set select option 'selected', by value

You can achieve this with different methods:
(remember if an element is to be operated, better give it an id or class, rather than having it's parent element an id or class).
Here, As the div has a class to target the select inside it, code will be:

$("div.id_100 select").val("val2");

or

$('div.id_100  option[value="val2"]').prop("selected", true);

If the class would have been given to select itself, code will be:

$(".id_100").val("val2");

or

$('.id_100 option[value=val2]').attr('selected','selected');

or

$('.id_100 option')
    .removeAttr('selected')
    .filter('[value=val1]')
    .attr('selected', true);

To pass the value dynamically, code will be:
valu="val2";

$("div.id_100 select").val(valu);
$("div.id_100 > select > option[value=" + valu + "]").prop("selected",true);

If element is added through ajax, You will have to give 'id' to your element and use
window.document.getElementById else You will have to give 'class' to your element and use
window.document.getElementById

You can also select value of select element by it's index number.
If you have given ID to your select element, code will be:

window.document.getElementById('select_element').selectedIndex = 4;

Remember when you change the select value as said above, change method is not called.
i.e. if you have written code to do some stuff on change of select the above methods will change the select value but will not trigger the change.
for to trigger the change function you have to add .change() at the end. so the code will be:

$("#select_id").val("val2").change();

sql - insert into multiple tables in one query

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.

START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;

http://dev.mysql.com/doc/refman/5.1/en/commit.html

Difference Between Schema / Database in MySQL

in MySQL schema is synonym of database. Its quite confusing for beginner people who jump to MySQL and very first day find the word schema, so guys nothing to worry as both are same.

When you are starting MySQL for the first time you need to create a database (like any other database system) to work with so you can CREATE SCHEMA which is nothing but CREATE DATABASE

In some other database system schema represents a part of database or a collection of Tables, and collection of schema is a database.

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

How do I add a ToolTip to a control?

I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.

private void Info_MouseHover(object sender, EventArgs e)
{
    Control senderObject = sender as Control;
    string hoveredControl = senderObject.Tag.ToString();

    // only instantiate a tooltip if the control's tag contains data
    if (hoveredControl != "")
    {
        ToolTip info = new ToolTip
        {
            AutomaticDelay = 500
        };

        string tooltipMessage = string.Empty;

        // add all conditionals here to modify message based on the tag 
        // of the hovered control
        if (hoveredControl == "save button")
        {
            tooltipMessage = "This button will save stuff.";
        }

        info.SetToolTip(senderObject, tooltipMessage);
    }
}

The role of #ifdef and #ifndef

"#if one" means that if "#define one" has been written "#if one" is executed otherwise "#ifndef one" is executed.

This is just the C Pre-Processor (CPP) Directive equivalent of the if, then, else branch statements in the C language.

i.e. if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); so if there was no #define one statement then the else branch of the statement would be executed.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Seems bit strange code. To get string from Utf8 byte stream all you need to do is:

string str = Encoding.UTF8.GetString(utf8ByteArray);

If you need to save iso-8859-1 byte stream to somewhere then just use: additional line of code for previous:

byte[] iso88591data = Encoding.GetEncoding("ISO-8859-1").GetBytes(str);

How to add line breaks to an HTML textarea?

I have a textarea with id is #infoartist follow:

<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>

In javascript code, i'll get value of textarea and replace escaping new line (\n\r) by <br /> tag, such as:

var text = document.getElementById("infoartist").value;
text = text.replace(/\r?\n/g, '<br />');

So if you are using jquery (like me):

var text = $("#infoartist").val();
text = text.replace(/\r?\n/g, '<br />');

Hope it helped you. :-)

Border for an Image view in Android?

ImageView in xml file

<ImageView
            android:id="@+id/myImage"
            android:layout_width="100dp"
            android:layout_height="100dp"

            android:padding="1dp"
            android:scaleType="centerCrop"
            android:cropToPadding="true"
            android:background="@drawable/border_image"

            android:src="@drawable/ic_launcher" />

save below code with the name of border_image.xml and it should be in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="270"
        android:endColor="#ffffff"
        android:startColor="#ffffff" />

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

    <stroke
        android:width="0.7dp"
        android:color="#b4b4b4" />
</shape>

if you want to give rounded corner to the border of image then you may change a line in border.xml file

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

Reading RFID with Android phones

A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.

It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.

Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.

They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.

Mongoose delete array element in document and save

This is working for me and really very helpful.

SubCategory.update({ _id: { $in:
        arrOfSubCategory.map(function (obj) {
            return mongoose.Types.ObjectId(obj);
        })
    } },
    {
        $pull: {
            coupon: couponId,
        }
    }, { multi: true }, function (err, numberAffected) {
        if(err) {
            return callback({
                error:err
            })
        }
    })
});

I have a model which name is SubCategory and I want to remove Coupon from this category Array. I have an array of categories so I have used arrOfSubCategory. So I fetch each array of object from this array with map function with the help of $in operator.

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

Sorting HTML table with JavaScript

It does WAY more than "just sorting", but dataTables.net does what you need. I use it daily and is well supported and VERY fast (does require jQuery)

http://datatables.net/

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Google Visualizations is another option, but requires a bit more setup that dataTables, but does NOT require any particular framework/library (other than google.visualizations):

http://code.google.com/apis/ajax/playground/?type=visualization#table

And there are other options to... especially if you're using one of the other JS frameworks. Dojo, Prototype, etc all have usable "table enhancement" plugins that provide at minimum table sorting functionality. Many provide more, but I'll restate...I've yet to come across one as powerful and as FAST as datatables.net.

Spring: How to inject a value to static field?

First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.

Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

(works with @Autowired/@Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.

Rails 3 check if attribute changed

For rails 5.1+ callbacks

As of Ruby on Rails 5.1, the attribute_changed? and attribute_was ActiveRecord methods will be deprecated

Use saved_change_to_attribute? instead of attribute_changed?

@user.saved_change_to_street1? # => true/false

More examples here

Select value if condition in SQL Server

Try Case

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

How to get history on react-router v4?

If you are using redux and redux-thunk the best solution will be using react-router-redux

// then, in redux actions for example
import { push } from 'react-router-redux'

dispatch(push('/some/path'))

It's important to see the docs to do some configurations.

Ant build failed: "Target "build..xml" does not exist"

I'm probably late but this worked for me:


  1. Open your build.xml file located in your project's directory.
  2. Copy and Paste the following code in the main project tag : <target name="build" />

Get URL of ASP.Net Page in code-behind

Do you want the server name? Or the host name?

Request.Url.Host ala Stephen

Dns.GetHostName - Server name

Request.Url will have access to most everything you'll need to know about the page being requested.

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

Oracle - How to create a readonly user

create user ro_role identified by ro_role;
grant create session, select any table, select any dictionary to ro_role;

BeautifulSoup Grab Visible Webpage Text

While, i would completely suggest using beautiful-soup in general, if anyone is looking to display the visible parts of a malformed html (e.g. where you have just a segment or line of a web-page) for whatever-reason, the the following will remove content between < and > tags:

import re   ## only use with malformed html - this is not efficient
def display_visible_html_using_re(text):             
    return(re.sub("(\<.*?\>)", "",text))

What is the best java image processing library/approach?

imo the best approach is using GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.

There are a lot of advantages of GraphicsMagick, but one for all:

  • GM is used to process billions of files at the world's largest photo sites (e.g. Flickr and Etsy).

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

How to use variables in SQL statement in Python?

http://www.amk.ca/python/writing/DB-API.html

Be careful when you simply append values of variables to your statements: Imagine a user naming himself ';DROP TABLE Users;' -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:

cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

I found out that declaring @PersistenceContext as EXTENDED also solves this problem:

@PersistenceContext(type = PersistenceContextType.EXTENDED)

How to break out or exit a method in Java?

If you are deeply in recursion inside recursive method, throwing and catching exception may be an option.

Unlike Return that returns only one level up, exception would break out of recursive method as well into the code that initially called it, where it can be catched.

What is the difference between Scrum and Agile Development?

As mentioned above by others,

Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.

So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.

Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role

Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.

Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.

Scrum Master:- There are 6 types of meetings in scrum:

  • Daily Scrum / Standup
  • Backlog grooming: storyline
  • Scrum of Scrums
  • Sprint Planning meeting
  • Sprint review meeting
  • Sprint retrospective

Let me know if any one need more inputs on this.

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got this problem because I uninstalled VS 2012, I don't want to reinstall it back, so I downloaded the AspNetMVC4Setup.exe from Microsoft.com and fixed my problem.

https://www.microsoft.com/en-us/download/details.aspx?id=30683

running a command as a super user from a python script

Try giving the full path to apache2ctl.

How to update a claim in ASP.NET Identity?

To remove claim details from database we can use below code. Also, we need to sign in again to update the cookie values

 // create a new identity 
            var identity = new ClaimsIdentity(User.Identity);

            // Remove the existing claim value of current user from database
            if(identity.FindFirst("NameOfUser")!=null)
                await UserManager.RemoveClaimAsync(applicationUser.Id, identity.FindFirst("NameOfUser"));

            // Update customized claim 
            await UserManager.AddClaimAsync(applicationUser.Id, new Claim("NameOfUser", applicationUser.Name));

            // the claim has been updates, We need to change the cookie value for getting the updated claim
            AuthenticationManager.SignOut(identity.AuthenticationType);
            await SignInManager.SignInAsync(Userprofile, isPersistent: false, rememberBrowser: false);

            return RedirectToAction("Index", "Home");

I can't install python-ldap

"Don't blindly remove/install software"

In a Ubuntu/Debian based distro, you could use apt-file to find the name of the exact package that includes the missing header file.

# do this once
sudo apt-get install apt-file
sudo apt-file update

$ apt-file search lber.h
libldap2-dev: /usr/include/lber.h

As you could see from the output of apt-file search lber.h, you'd just need to install the package libldap2-dev.

sudo apt-get install libldap2-dev

Show two digits after decimal point in c++

This will be possible with setiosflags(ios::showpoint).

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Regular Expression for password validation

Long, and could maybe be shortened. Supports special characters ?"-_.

\A(?=[-\?\"_a-zA-Z0-9]*?[A-Z])(?=[-\?\"_a-zA-Z0-9]*?[a-z])(?=[-\?\"_a-zA-Z0-9]*?[0-9])[-\?\"_a-zA-Z0-9]{8,15}\z

getContext is not a function

I recently got this error because the typo, I write 'canavas' instead of 'canvas', hope this could help someone who is searching for this.

Proper way to get page content

get page content by page name:

<?php
$page = get_page_by_title( 'page-name' );
$content = apply_filters('the_content', $page->post_content); 
echo $content;
?>

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

Load different application.yml in SpringBoot Test

Lu55 Option 1 how to...

Add test only application.yml inside a seperated resources folder.

+-- main
¦   +-- java
¦   +-- resources
¦       +-- application.yml
+-- test
    +-- java
    +-- resources
        +-- application.yml

In this project structure the application.yml under main is loaded if the code under main is running, the application.yml under test is used in a test.

To setup this structure add a new Package folder test/recources if not present.

Eclipse right click on your project -> Properties -> Java Build Path -> Source Tab -> (Dialog ont the rigth side) "Add Folder ..."

Inside Source Folder Selection -> mark test -> click on "Create New Folder ..." button -> type "resources" inside the Textfeld -> Click the "Finish" button.

After pushing the "Finisch" button you can see the sourcefolder {projectname}/src/test/recources (new)

Optional: Arrange folder sequence for the Project Explorer view. Klick on Order and Export Tab mark and move {projectname}/src/test/recources to bottom. Apply and Close

!!! Clean up Project !!!
Eclipse -> Project -> Clean ...

Now there is a separated yaml for test and the main application.

how to load CSS file into jsp

I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css). Make sure your servlet doesn't contain the "/" urlPattern. I hope this worked for u too, - Axel Montini

Performance of Java matrix math libraries?

Building on Varkhan's post that Pentium-specific native code would do better:

The EntityManager is closed

This is how I solved the Doctrine "The EntityManager is closed." issue. Basically each time there's an exception (i.e. duplicate key) or not providing data for a mandatory column will cause Doctrine to close the Entity Manager. If you still want to interact with the database you have to reset the Entity Manger by calling the resetManager() method as mentioned by JGrinon.

In my application I was running multiple RabbitMQ consumers that were all doing the same thing: checking if an entity was there in the database, if yes return it, if not create it and then return it. In the few milliseconds between checking if that entity already existed and creating it another consumer happened to do the same and created the missing entity making the other consumer incur in a duplicate key exception (race condition).

This led to a software design problem. Basically what I was trying to do was creating all the entities in one transaction. This may feel natural to most but was definitely conceptually wrong in my case. Consider the following problem: I had to store a football Match entity which had these dependencies.

  • a group (e.g. Group A, Group B...)
  • a round (e.g. Semi-finals...)
  • a venue (i.e. stadium where the match is taking place)
  • a match status (e.g. half time, full time)
  • the two teams playing the match
  • the match itself

Now, why the venue creation should be in the same transaction as the match? It could be that I've just received a new venue that it's not in my database so I have to create it first. But it could also be that that venue may host another match so another consumer will probably try to create it as well at the same time. So what I had to do was create all the dependencies first in separate transactions making sure I was resetting the entity manager in a duplicate key exception. I'd say that all the entities in there beside the match could be defined as "shared" because they could potentially be part of other transactions in other consumers. Something that is not "shared" in there is the match itself that won't likely be created by two consumers at the same time. So in the last transaction I expect to see just the match and the relation between the two teams and the match.

All of this also led to another issue. If you reset the Entity Manager, all the objects that you've retrieved before resetting are for Doctrine totally new. So Doctrine won't try to run an UPDATE on them but an INSERT! So make sure you create all your dependencies in logically correct transactions and then retrieve all your objects back from the database before setting them to the target entity. Consider the following code as an example:

$group = $this->createGroupIfDoesNotExist($groupData);

$match->setGroup($group); // this is NOT OK!

$venue = $this->createVenueIfDoesNotExist($venueData);

$round = $this->createRoundIfDoesNotExist($roundData);

/**
 * If the venue creation generates a duplicate key exception
 * we are forced to reset the entity manager in order to proceed
 * with the round creation and so we'll loose the group reference.
 * Meaning that Doctrine will try to persist the group as new even
 * if it's already there in the database.
 */

So this is how I think it should be done.

$group = $this->createGroupIfDoesNotExist($groupData); // first transaction, reset if duplicated
$venue = $this->createVenueIfDoesNotExist($venueData); // second transaction, reset if duplicated
$round = $this->createRoundIfDoesNotExist($roundData); // third transaction, reset if duplicated

// we fetch all the entities back directly from the database
$group = $this->getGroup($groupData);
$venue = $this->getVenue($venueData);
$round = $this->getGroup($roundData);

// we finally set them now that no exceptions are going to happen
$match->setGroup($group);
$match->setVenue($venue);
$match->setRound($round);

// match and teams relation...
$matchTeamHome = new MatchTeam();
$matchTeamHome->setMatch($match);
$matchTeamHome->setTeam($teamHome);

$matchTeamAway = new MatchTeam();
$matchTeamAway->setMatch($match);
$matchTeamAway->setTeam($teamAway);

$match->addMatchTeam($matchTeamHome);
$match->addMatchTeam($matchTeamAway);

// last transaction!
$em->persist($match);
$em->persist($matchTeamHome);
$em->persist($matchTeamAway);
$em->flush();

I hope it helps :)

How do I get Flask to run on port 80?

If you want your application on same port i.e port=5000 then just in your terminal run this command:

fuser -k 5000/tcp

and then run:

python app.py

If you want to run on a specified port, e.g. if you want to run on port=80, in your main file just mention this:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

How to show alert message in mvc 4 controller?

TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])

How do you revert to a specific tag in Git?

Use git reset:

git reset --hard "Version 1.0 Revision 1.5"

(assuming that the specified string is the tag).

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

Convert UNIX epoch to Date object

With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():

lubridate::as_datetime(1352068320)

[1] "2012-11-04 22:32:00 UTC"

How to read the post request parameters using JavaScript

POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

Javascript: Setting location.href versus location

Like as has been said already, location is an object. But that person suggested using either. But, you will do better to use the .href version.

Objects have default properties which, if nothing else is specified, they are assumed. In the case of the location object, it has a property called .href. And by not specifying ANY property during the assignment, it will assume "href" by default.

This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. Then your program breaks unexpectedly.

If you mean href, you should specify href.

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

How do you log all events fired by an element in jQuery?

I know the answer has already been accepted to this, but I think there might be a slightly more reliable way where you don't necessarily have to know the name of the event beforehand. This only works for native events though as far as I know, not custom ones that have been created by plugins. I opted to omit the use of jQuery to simplify things a little.

let input = document.getElementById('inputId');

Object.getOwnPropertyNames(input)
  .filter(key => key.slice(0, 2) === 'on')
  .map(key => key.slice(2))
  .forEach(eventName => {
    input.addEventListener(eventName, event => {
      console.log(event.type);
      console.log(event);
    });
  });

I hope this helps anyone who reads this.

EDIT

So I saw another question here that was similar, so another suggestion would be to do the following:

monitorEvents(document.getElementById('inputId'));

Homebrew: Could not symlink, /usr/local/bin is not writable

This is because the current user is not permitted to write in that path. So, to change r/w (read/write) permissions you can either use 1. terminal, or 2. Graphical "Get Info" window.

1. Using Terminal

Google how to use chmod/chown (change mode/change owner) commands from terminal

2. Using graphical 'Get Info'

You can right click on the folder/file you want to change permissions of, then open Get Info which will show you a window like below at the bottom of which you can easily change r/w permissions: enter image description here

Remember to change the permission back to "read only" after your temporary work, if possible

htons() function in socket programing

htons is host-to-network short

This means it works on 16-bit short integers. i.e. 2 bytes.

This function swaps the endianness of a short.

Your number starts out at:

0001 0011 1000 1001 = 5001

When the endianness is changed, it swaps the two bytes:

1000 1001 0001 0011 = 35091

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

How to change to an older version of Node.js

Why use any extension when you can do this without extension :)

Install specific version of node

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Specific version : sudo n 4.4.4 instead of sudo n stable

What permission do I need to access Internet from an Android application?

just put above line like below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avocats.activeavocats"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name="com.example.exp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Error in plot.new() : figure margins too large in R

RStudio Plots canvas is limiting the plot width and heights. However if you make your plot from Rmarkdown code chunk, it works without canvas field limitation because plotting area set according to the paper size.

For instance:

    ```{r}
#inside of code chunk in Rmarkdown
        grid <- par(mfrow=c(4, 5))
        plot(faithful, main="Faithful eruptions")
        plot(large.islands, main="Islands", ylab="Area")
        ...
        par(grid)
    ```

How is the java memory pool divided?

The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits.

The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.

There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/

Diagram of Java memory for several threads Diagram of Java memory distribution

How can I zoom an HTML element in Firefox and Opera?

does this work correctly for you? :

zoom: 145%;
-moz-transform: scale(1.45);
-webkit-transform: scale(1.45);
scale(1.45);
transform: scale(1.45);

What's the proper way to "go get" a private repository?

That looks like the GitLab issue 5769.

In GitLab, since the repositories always end in .git, I must specify .git at the end of the repository name to make it work, for example:

import "example.org/myuser/mygorepo.git"

And:

$ go get example.org/myuser/mygorepo.git

Looks like GitHub solves this by appending ".git".

It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go: go get cannot discover meta tag in HTML5 documents”.

How do I prevent an Android device from going to sleep programmatically?

One option is to use a wake lock. Example from the docs:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

There's also a table on this page that describes the different kinds of wakelocks.

Be aware that some caution needs to be taken when using wake locks. Ensure that you always release() the lock when you're done with it (or not in the foreground). Otherwise your app can potentially cause some serious battery drain and CPU usage.

The documentation also contains a useful page that describes different approaches to keeping a device awake, and when you might choose to use one. If "prevent device from going to sleep" only refers to the screen (and not keeping the CPU active) then a wake lock is probably more than you need.

You also need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this method.

Get spinner selected items text?

For spinners based on a CursorAdapter:

  • get the selected item id: spinner.getSelectedItemId()
  • fetch the item name from your database, for example:

    public String getCountryName(int pId){
        Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
        String ret = null;
        if(cur.moveToFirst()){
            ret = cur.getString(0);
        }
        cur.close();
        return ret;
    }
    

Best way to retrieve variable values from a text file?

hbn's answer won't work out of the box if the file to load is in a subdirectory or is named with dashes.

In such a case you may consider this alternative :

exec open(myconfig.py).read()

Or the simpler but deprecated in python3 :

execfile(myconfig.py)

I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.

How to change UIButton image in Swift

Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.

yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill

// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)

How to stop event bubbling on checkbox click

As others have mentioned, try stopPropagation().

And there is a second handler to try: event.cancelBubble = true; It's a IE specific handler, but it is supported in at least FF. Don't really know much about it, as I haven't used it myself, but it might be worth a shot, if all else fails.

How to convert local time string to UTC?

First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation.

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

Finally, use datetime.astimezone() method to convert the datetime to UTC.

Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

From there, you can use the strftime() method to format the UTC datetime as needed:

utc_dt.strftime("%Y-%m-%d %H:%M:%S")

What are naming conventions for MongoDB?

  1. Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.

  2. I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...

  3. MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.

  4. MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id (but this may be be to indicate that _id is intended to be private, internal, never displayed or edited.

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

I have resolved it by adding below line in my context:

modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

Somehow, [MaxLength] didn't work for me.