Programs & Examples On #Picocontainer

PicoContainer is a highly embeddable, full-service, Inversion of Control (IoC) container for components honor the Dependency Injection pattern

Creating a mock HttpServletRequest out of a url string?

You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.

In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.

How to get the latest file in a folder?

Try to sort items by creation time. Example below sorts files in a folder and gets first element which is latest.

import glob
import os

files_path = os.path.join(folder, '*')
files = sorted(
    glob.iglob(files_path), key=os.path.getctime, reverse=True) 
print files[0]

Enum "Inheritance"

I also wanted to overload Enums and created a mix of the answer of 'Seven' on this page and the answer of 'Merlyn Morgan-Graham' on a duplicate post of this, plus a couple of improvements.
Main advantages of my solution over the others:

  • automatic increment of the underlying int value
  • automatic naming

This is an out-of-the-box solution and may be directly inserted into your project. It is designed to my needs, so if you don't like some parts of it, just replace them with your own code.

First, there is the base class CEnum that all custom enums should inherit from. It has the basic functionality, similar to the .net Enum type:

public class CEnum
{
  protected static readonly int msc_iUpdateNames  = int.MinValue;
  protected static int          ms_iAutoValue     = -1;
  protected static List<int>    ms_listiValue     = new List<int>();

  public int Value
  {
    get;
    protected set;
  }

  public string Name
  {
    get;
    protected set;
  }

  protected CEnum ()
  {
    CommonConstructor (-1);
  }

  protected CEnum (int i_iValue)
  {
    CommonConstructor (i_iValue);
  }

  public static string[] GetNames (IList<CEnum> i_listoValue)
  {
    if (i_listoValue == null)
      return null;
    string[] asName = new string[i_listoValue.Count];
    for (int ixCnt = 0; ixCnt < asName.Length; ixCnt++)
      asName[ixCnt] = i_listoValue[ixCnt]?.Name;
    return asName;
  }

  public static CEnum[] GetValues ()
  {
    return new CEnum[0];
  }

  protected virtual void CommonConstructor (int i_iValue)
  {
    if (i_iValue == msc_iUpdateNames)
    {
      UpdateNames (this.GetType ());
      return;
    }
    else if (i_iValue > ms_iAutoValue)
      ms_iAutoValue = i_iValue;
    else
      i_iValue = ++ms_iAutoValue;

    if (ms_listiValue.Contains (i_iValue))
      throw new ArgumentException ("duplicate value " + i_iValue.ToString ());
    Value = i_iValue;
    ms_listiValue.Add (i_iValue);
  }

  private static void UpdateNames (Type i_oType)
  {
    if (i_oType == null)
      return;
    FieldInfo[] aoFieldInfo = i_oType.GetFields (BindingFlags.Public | BindingFlags.Static);

    foreach (FieldInfo oFieldInfo in aoFieldInfo)
    {
      CEnum oEnumResult = oFieldInfo.GetValue (null) as CEnum;
      if (oEnumResult == null)
        continue;
      oEnumResult.Name = oFieldInfo.Name;
    }
  }
}

Secondly, here are 2 derived Enum classes. All derived classes need some basic methods in order to work as expected. It's always the same boilerplate code; I haven't found a way yet to outsource it to the base class. The code of the first level of inheritance differs slightly from all subsequent levels.

public class CEnumResult : CEnum
{
  private   static List<CEnumResult>  ms_listoValue = new List<CEnumResult>();

  public    static readonly CEnumResult Nothing         = new CEnumResult (  0);
  public    static readonly CEnumResult SUCCESS         = new CEnumResult (  1);
  public    static readonly CEnumResult UserAbort       = new CEnumResult ( 11);
  public    static readonly CEnumResult InProgress      = new CEnumResult (101);
  public    static readonly CEnumResult Pausing         = new CEnumResult (201);
  private   static readonly CEnumResult Dummy           = new CEnumResult (msc_iUpdateNames);

  protected CEnumResult () : base ()
  {
  }

  protected CEnumResult (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> ();
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

public class CEnumResultClassCommon : CEnumResult
{
  private   static List<CEnumResultClassCommon> ms_listoValue = new List<CEnumResultClassCommon>();

  public    static readonly CEnumResult Error_InternalProgramming           = new CEnumResultClassCommon (1000);

  public    static readonly CEnumResult Error_Initialization                = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_ObjectNotInitialized          = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_DLLMissing                    = new CEnumResultClassCommon ();
  // ... many more
  private   static readonly CEnumResult Dummy                               = new CEnumResultClassCommon (msc_iUpdateNames);

  protected CEnumResultClassCommon () : base ()
  {
  }

  protected CEnumResultClassCommon (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> (CEnumResult.GetValues ());
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

The classes have been successfully tested with follwing code:

private static void Main (string[] args)
{
  CEnumResult oEnumResult = CEnumResultClassCommon.Error_Initialization;
  string sName = oEnumResult.Name;   // sName = "Error_Initialization"

  CEnum[] aoEnumResult = CEnumResultClassCommon.GetValues ();   // aoEnumResult = {testCEnumResult.Program.CEnumResult[9]}
  string[] asEnumNames = CEnum.GetNames (aoEnumResult);
  int ixValue = Array.IndexOf (aoEnumResult, oEnumResult);    // ixValue = 6
}

Add a tooltip to a div

<div title="tooltip text..">
    Your Text....
</div>

Simple most way to add tooltip to your div element.

C# How to determine if a number is a multiple of another?

bool isMultiple = a % b == 0;

This will be true if a is a multiple of b

Setting initial values on load with Select2 with Ajax

Change the value after the page loads

$('#data').val('').change();

How to vertically center a "div" element for all browsers using CSS?

Especially for parent divs with relative (unknown) height, the centering in the unknown solution works great for me. There are some really nice code examples in the article.

It was tested in Chrome, Firefox, Opera, and Internet Explorer.

_x000D_
_x000D_
/* This parent can be any width and height */_x000D_
.block {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
/* The ghost, nudged to maintain perfect centering */_x000D_
.block:before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%;_x000D_
  vertical-align: middle;_x000D_
  margin-right: -0.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
/* The element to be centered, can_x000D_
   also be of any width and height */ _x000D_
.centered {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  width: 300px;_x000D_
}
_x000D_
<div style="width: 400px; height: 200px;">_x000D_
   <div class="block" style="height: 90%; width: 100%">_x000D_
  <div class="centered">_x000D_
  <h1>Some text</h1>_x000D_
  <p>Any other text..."</p>_x000D_
  </div> _x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between 'struct' and 'typedef struct' in C++?

You can't use forward declaration with the typedef struct.

The struct itself is an anonymous type, so you don't have an actual name to forward declare.

typedef struct{
    int one;
    int two;
}myStruct;

A forward declaration like this wont work:

struct myStruct; //forward declaration fails

void blah(myStruct* pStruct);

//error C2371: 'myStruct' : redefinition; different basic types

How to empty a redis database?

There are right answers but I just want to add one more option (requires downtime):

  1. Stop Redis.
  2. Delete RDB file (find location in redis.conf).
  3. Start Redis.

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

check if directory exists and delete in one command unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

How to list all files in a directory and its subdirectories in hadoop hdfs

don't use recursive approach (heap issues) :) use a queue

queue.add(param_dir)
while (queue is not empty){

  directory=  queue.pop
 - get items from current directory
 - if item is file add to a list (final list)
 - if item is directory => queue.push
}

that was easy, enjoy!

Pip Install not installing into correct directory?

1 - Something that might work

The pip executable is actually a Python script.

By default it contains (on Linux):

#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==1.5.6','console_scripts','pip'
__requires__ = 'pip==1.5.6'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
    )

So if you got the same in MacOS, pip would always use /usr/bin/python.

But this is a default. You can still provide the version of python you want either by editing the file or by using python explicitly.

If which python returns /usr/bin/python then something went wrong when you installed your own version. If it is /Library/Frameworks/Python.framework/Versions/2.7/bin/python, you can directly call:

sudo python `which pip` install scikit-learn --upgrade

However, chances are high that it won't work. The reason is that sudo is resetting all your environment variables. To make it work, the easiest would be to use:

sudo -E pip install scikit-learn --upgrade

or

sudo -E python `which pip` install scikit-learn --upgrade

depending on your setup.

2 - What you should do

pip was not thought of as something that root should execute. The actual best way to use it is to install a local, non-root, python version. You just have to make sure that you use it by default by setting up the correct environment variables (such as PATH on Linux) and then install pip without sudo using that python version.

An even better way would be to setup virtualenvs from your root install.

This way, you can install/update whatever you want without root privileges and never bother again about why sudo pip is not working. You would also avoid to provide root privileges to whatever is on Pypi and that would warrant that you don't mix system libs with your own.

get next sequence value from database using hibernate

Your idea with the SequenceGenerator fake entity is good.

@Id
@GenericGenerator(name = "my_seq", strategy = "sequence", parameters = {
        @org.hibernate.annotations.Parameter(name = "sequence_name", value = "MY_CUSTOM_NAMED_SQN"),
})
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")

It is important to use the parameter with the key name "sequence_name". Run a debugging session on the hibernate class SequenceStyleGenerator, the configure(...) method at the line final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment ); to see more details about how the sequence name is computed by Hibernate. There are some defaults in there you could also use.

After the fake entity, I created a CrudRepository:

public interface SequenceRepository extends CrudRepository<SequenceGenerator, Long> {}

In the Junit, I call the save method of the SequenceRepository.

SequenceGenerator sequenceObject = new SequenceGenerator(); SequenceGenerator result = sequenceRepository.save(sequenceObject);

If there is a better way to do this (maybe support for a generator on any type of field instead of just Id), I would be more than happy to use it instead of this "trick".

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

how to download image from any web page in java

   // Do you want to download an image?
   // But are u denied access?
   // well here is the solution.

    public static void DownloadImage(String search, String path) {

    // This will get input data from the server
    InputStream inputStream = null;

    // This will read the data from the server;
    OutputStream outputStream = null;

    try {
        // This will open a socket from client to server
        URL url = new URL(search);

       // This user agent is for if the server wants real humans to visit
        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

       // This socket type will allow to set user_agent
        URLConnection con = url.openConnection();

        // Setting the user agent
        con.setRequestProperty("User-Agent", USER_AGENT);

        // Requesting input data from server
        inputStream = con.getInputStream();

        // Open local file writer
        outputStream = new FileOutputStream(path);

        // Limiting byte written to file per loop
        byte[] buffer = new byte[2048];

        // Increments file size
        int length;

        // Looping until server finishes
        while ((length = inputStream.read(buffer)) != -1) {
            // Writing data
            outputStream.write(buffer, 0, length);
        }
    } catch (Exception ex) {
        Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);
     }

     // closing used resources
     // The computer will not be able to use the image
     // This is a must

     outputStream.close();
     inputStream.close();
}

Create text file and fill it using bash

#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
  echo "File $1.json already exists!"
else
  cat > $file_location <<EOF
{
      "contact": {
          "name": "xyz",
          "phonenumber":   "xxx-xxx-xxxx"
      }
    }
EOF
fi

This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.

How to bring view in front of everything?

You need to use framelayout. And the better way to do this is to make the view invisible when thay are not require. Also you need to set the position for each and every view,So that they will move according to there corresponding position

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

Is there a way to delete all the data from a topic or delete the topic before every run?

As a dirty workaround, you can adjust per-topic runtime retention settings, e.g. bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic my_topic --config retention.bytes=1 (retention.bytes=0 might also work)

After a short while kafka should free the space. Not sure if this has any implications compared to re-creating the topic.

ps. Better bring retention settings back, once kafka done with cleaning.

You can also use retention.ms to persist historical data

How to show MessageBox on asp.net?

There is pretty concise and easy way:

Response.Write("<script>alert('Your text');</script>");

What should I do if the current ASP.NET session is null?

The following statement is not entirely accurate:

"So if you are calling other functionality, including static classes, from your page, you should be fine"

I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.

As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:

There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:

[WebMethod(EnableSession = true)]

By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.

Thanks to Matthew Cosier for the solution.

Just thought I'd add my two cents.

Ed

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

JSON datetime between Python and JavaScript

My advice is to use a library. There are several available at pypi.org.

I use this one, it it works good: https://pypi.python.org/pypi/asjson

Android Studio doesn't recognize my device

Change the connection method Build-In CD ROM it works for me

Multiple select statements in Single query

You can certainly us the a Select Agregation statement as Postulated by Ben James, However This will result in a view with as many columns as you have tables. An alternate method may be as follows:

SELECT COUNT(user_table.id) AS TableCount,'user_table' AS TableSource FROM user_table
UNION SELECT COUNT(cat_table.id) AS TableCount,'cat_table' AS TableSource FROM cat_table
UNION SELECT COUNT(course_table.id) AS TableCount, 'course_table' AS TableSource From course_table;

The Nice thing about an approch like this is that you can explicitly write the Union statements and generate a view or create a temp table to hold values that are added consecutively from a Proc cals using variables in place of your table names. I tend to go more with the latter, but it really depends on personal preference and application. If you are sure the tables will never change, you want the data in a single row format, and you will not be adding tables. stick with Ben James' solution. Otherwise I'd advise flexibility, you can always hack a cross tab struc.

Webpack not excluding node_modules

try this below solution:

exclude:path.resolve(__dirname, "node_modules")

Do you recommend using semicolons after every statement in JavaScript?

What everyone seems to miss is that the semi-colons in JavaScript are not statement terminators but statement separators. It's a subtle difference, but it is important to the way the parser is programmed. Treat them like what they are and you will find leaving them out will feel much more natural.

I've programmed in other languages where the semi-colon is a statement separator and also optional as the parser does 'semi-colon insertion' on newlines where it does not break the grammar. So I was not unfamiliar with it when I found it in JavaScript.

I don't like noise in a language (which is one reason I'm bad at Perl) and semi-colons are noise in JavaScript. So I omit them.

Best way to copy from one array to another

There are lots of solutions:

b = Arrays.copyOf(a, a.length);

Which allocates a new array, copies over the elements of a, and returns the new array.

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Which copies the source array content into a destination array that you allocate yourself.

Or

b = a.clone();

which works very much like Arrays.copyOf(). See this thread.

Or the one you posted, if you reverse the direction of the assignment in the loop:

b[i] = a[i]; // NOT a[i] = b[i];

Android set height and width of Custom view programmatically

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

Copy from one workbook and paste into another

This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 

'Close x:
x.Close

End Sub

To extend this to the entire sheet:

With x.Sheets("name of copying sheet").UsedRange
    'Now, paste to y worksheet:
    y.Sheets("sheet name").Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
End With

And yet another way, store the value as a variable and write the variable to the destination:

Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value

'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals 

'Close x:
x.Close

End Sub

The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:

Copy/PasteSpecial vs Range.Value = Range.Value

That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.

How to change background color in the Notepad++ text editor?

Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.

The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

https://draculatheme.com/notepad-plus-plus

Receiving login prompt using integrated windows authentication

I was having this issue on .net core 2 and after going through most suggestions from here it seems that we missed a setting on web.config

<aspNetCore processPath="dotnet" arguments=".\app.dll" forwardWindowsAuthToken="false" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

The correct setting was forwardWindowsAuthToken="true" that seems obvious now but when there are so many situations for same problem it's harder to pinpoint

Edit: i also found helpful the following Msdn article that goes through troubleshooting the issue.

how to get the base url in javascript

Let's say you have your global scripts file and you don't want to define that URL repeatedly in other files. That's the point where BASE_URL kicks in.

In your global_script.js file, do this

<script>
 var BASE_URL = "http://localhost:8000";
</script>

Then you can use that variable anywhere else to call your URL. For example...

<script>
   fetch(`{{BASE_URL}}/task-create/`,{
         ..............
            
        }).then((response) => {
            .............
   })
</script>

Laravel Unknown Column 'updated_at'

In the model, write the below code;

public $timestamps = false;

This would work.

Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.

Generate a dummy-variable

another way you can do it is use

ifelse(year < 1965 , 1, 0)

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

What's the u prefix in a Python string?

I came here because I had funny-char-syndrome on my requests output. I thought response.text would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.

Turns out response.encoding was empty somehow and so response did not know how to properly decode the content and just treated it as ASCII (I guess).

My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8') to it. The result was schöne Umlaute.

The correctly decoded

für

vs. the improperly decoded

fAzr

Save base64 string as PDF at client side with JavaScript

_x000D_
_x000D_
dataURItoBlob(dataURI) {_x000D_
      const byteString = window.atob(dataURI);_x000D_
      const arrayBuffer = new ArrayBuffer(byteString.length);_x000D_
      const int8Array = new Uint8Array(arrayBuffer);_x000D_
      for (let i = 0; i < byteString.length; i++) {_x000D_
        int8Array[i] = byteString.charCodeAt(i);_x000D_
      }_x000D_
      const blob = new Blob([int8Array], { type: 'application/pdf'});_x000D_
      return blob;_x000D_
    }_x000D_
_x000D_
// data should be your response data in base64 format_x000D_
_x000D_
const blob = this.dataURItoBlob(data);_x000D_
const url = URL.createObjectURL(blob);_x000D_
_x000D_
// to open the PDF in a new window_x000D_
window.open(url, '_blank');
_x000D_
_x000D_
_x000D_

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

How to calculate a Mod b in Casio fx-991ES calculator

You can calculate A mod B (for positive numbers) using this:

Pol( -Rec( 1/r , 2πr × A/B ) , Y ) ( πr - Y ) B

Then press [CALC], and enter your values for A and B, and any value for Y.

/ indicates using the fraction key, and r means radians ( [SHIFT] [Ans] [2] )

How to check if a service is running via batch file and start it, if it is not running?

Cuando se use Windows en Español, el código debe quedar asi (when using Windows in Spanish, code is):

for /F "tokens=3 delims=: " %%H in ('sc query MYSERVICE ^| findstr "        ESTADO"') do (
  if /I "%%H" NEQ "RUNNING" (
    REM Put your code you want to execute here
    REM For example, the following line
    net start MYSERVICE
  )
)

Reemplazar MYSERVICE con el nombre del servicio que se desea procesar. Puedes ver el nombre del servicio viendo las propiedades del servicio. (Replace MYSERVICE with the name of the service to be processed. You can see the name of the service on service properties.)

How to get JSON from URL in JavaScript?

ES8(2017) try

obj = await (await fetch(url)).json();

_x000D_
_x000D_
async function load() {_x000D_
    let url = 'https://my-json-server.typicode.com/typicode/demo/db';_x000D_
    let obj = await (await fetch(url)).json();_x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
_x000D_
_x000D_

you can handle errors by try-catch

_x000D_
_x000D_
async function load() {_x000D_
    let url = 'http://query.yahooapis.com/v1/publ...';_x000D_
    let obj = null;_x000D_
    _x000D_
    try {_x000D_
        obj = await (await fetch(url)).json();_x000D_
    } catch(e) {_x000D_
        console.log('error');_x000D_
    }_x000D_
    _x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
_x000D_
_x000D_

What's the difference between REST & RESTful

REST is an style of software architecture for distributed software

Conforming to the REST constraints is referred to as being ‘RESTful’.

Very used today to build web services as an alternative to SOAP.

Here you have some links to check

http://en.wikipedia.org/wiki/Representational_State_Transfer
http://www.computerworld.com/s/article/297424/Representational_State_Transfer_REST_
http://www.ibm.com/developerworks/webservices/library/ws-restful/

nodemon not working: -bash: nodemon: command not found

Install nodemon:

sudo npm install -g nodemon

Run server:

sudo nodemon server.js

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

Optimal way to concatenate/aggregate strings

Although @serge answer is correct but i compared time consumption of his way against xmlpath and i found the xmlpath is so faster. I'll write the compare code and you can check it by yourself. This is @serge way:

DECLARE @startTime datetime2;
DECLARE @endTime datetime2;
DECLARE @counter INT;
SET @counter = 1;

set nocount on;

declare @YourTable table (ID int, Name nvarchar(50))

WHILE @counter < 1000
BEGIN
    insert into @YourTable VALUES (ROUND(@counter/10,0), CONVERT(NVARCHAR(50), @counter) + 'CC')
    SET @counter = @counter + 1;
END

SET @startTime = GETDATE()

;WITH Partitioned AS
(
    SELECT 
        ID,
        Name,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber,
        COUNT(*) OVER (PARTITION BY ID) AS NameCount
    FROM @YourTable
),
Concatenated AS
(
    SELECT ID, CAST(Name AS nvarchar) AS FullName, Name, NameNumber, NameCount FROM Partitioned WHERE NameNumber = 1

    UNION ALL

    SELECT 
        P.ID, CAST(C.FullName + ', ' + P.Name AS nvarchar), P.Name, P.NameNumber, P.NameCount
    FROM Partitioned AS P
        INNER JOIN Concatenated AS C ON P.ID = C.ID AND P.NameNumber = C.NameNumber + 1
)
SELECT 
    ID,
    FullName
FROM Concatenated
WHERE NameNumber = NameCount

SET @endTime = GETDATE();

SELECT DATEDIFF(millisecond,@startTime, @endTime)
--Take about 54 milliseconds

And this is xmlpath way:

DECLARE @startTime datetime2;
DECLARE @endTime datetime2;
DECLARE @counter INT;
SET @counter = 1;

set nocount on;

declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))

WHILE @counter < 1000
BEGIN
    insert into @YourTable VALUES (@counter, ROUND(@counter/10,0), CONVERT(NVARCHAR(50), @counter) + 'CC')
    SET @counter = @counter + 1;
END

SET @startTime = GETDATE();

set nocount off
SELECT
    t1.HeaderValue
        ,STUFF(
                   (SELECT
                        ', ' + t2.ChildValue
                        FROM @YourTable t2
                        WHERE t1.HeaderValue=t2.HeaderValue
                        ORDER BY t2.ChildValue
                        FOR XML PATH(''), TYPE
                   ).value('.','varchar(max)')
                   ,1,2, ''
              ) AS ChildValues
    FROM @YourTable t1
    GROUP BY t1.HeaderValue

SET @endTime = GETDATE();

SELECT DATEDIFF(millisecond,@startTime, @endTime)
--Take about 4 milliseconds

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I encountered the same error when added http-builder to dependencies.
In my case, I could solve by simply excluding asm like this:

compile('org.codehaus.groovy.modules.http-builder:http-builder:0.7'){
    excludes 'xml-apis'
    exclude(group:'xerces', module: 'xercesImpl')
    excludes 'asm'
}

Echo newline in Bash prints literal \n

I just use echo no arguments

echo "Hello"
echo
echo "World"

Random number c++ in some range

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

Apache won't start in wamp

If Apache is installed as a Windows service, any errors will show up in the Windows System event log. To view the System event log, navigate to Windows Administrative Tools->Event Viewer and open the System log in the Windows Logs folder. Or, you can see the same errors by running httpd.exe at the command line. In my case, httpd.exe is located here: C:\Bitnami\wampstack-5.6.26-2\apache2\bin.

If there is a problem with starting Apache, most likely the problem can be fixed by editing the httpd.conf file located in the \apache2\conf folder. As already suggested, you can check the syntax of the httpd.conf file by running httpd.exe -t at the command line.

I found that the I had to

Change SetEnv PATH "C:\Bitnami\wampstack-5.6.26-2\apache2\bin;${PATH}" in httpd.conf

to

SetEnv PATH "C:\Bitnami\wampstack-5.6.26-2\apache2\bin;%PATH%"

What does "static" mean in C?

Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

Look at this for example - A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

#include<stdio.h> 
int fun() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("%d ", fun()); 
  printf("%d ", fun()); 
  return 0; 
}

This will output: 1 2

As 1 stays in the memory as it was declared static

Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.

#include <stdio.h> 
int main() 
{ 
    static int x; 
    int y; 
    printf("%d \n %d", x, y); 
}

This will output : 0 [some_garbage_value]

These are the major ones I found that weren't explained above for a newbie!

How can I know which radio button is selected via jQuery?

I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata

It'll give you a js object of the answers, so a form like:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

will give you:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}

Python, how to read bytes from file and save it?

with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.

How do I convert two lists into a dictionary?

method without zip function

l1 = [1,2,3,4,5]
l2 = ['a','b','c','d','e']
d1 = {}
for l1_ in l1:
    for l2_ in l2:
        d1[l1_] = l2_
        l2.remove(l2_)
        break  

print (d1)


{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}

Java: how to import a jar file from command line

You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass

If perchance you are using linux, you should use ":" instead of ";" in the classpath.

How to use function srand() with time.h?

If you chose to srand, it is a good idea to then call rand() at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.

srand(time(NULL));
rand();
//Now use rand()

If available, either random or arc4rand would be better.

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Is putting a div inside an anchor ever correct?

No it won't validate, but yes it generally will work in modern browsers. That being said, use a span inside your anchor, and set display: block on it as well, that will definitely work everywhere, and it will validate!

How might I extract the property values of a JavaScript object into an array?

Object.values() method is now supported. This will give you an array of values of an object.

Object.values(dataObject)

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Using G++ to compile multiple .cpp and .h files

If you want to use #include <myheader.hpp> inside your cpp files you can use:

g++ *.cpp -I. -o out

Scanner vs. StringTokenizer vs. String.Split

String.split() works very good but has its own boundaries, like if you wanted to split a string as shown below based on single or double pipe (|) symbol, it doesn't work. In this situation you can use StringTokenizer.

ABC|IJK

Are lists thread-safe?

Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:

L[0] += 1

is not guaranteed to actually increase L[0] by one if another thread does the same thing, because += is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.

In git, what is the difference between merge --squash and rebase?

Let's start by the following example:

enter image description here

Now we have 3 options to merge changes of feature branch into master branch:

  1. Merge commits
    Will keep all commits history of the feature branch and move them into the master branch
    Will add extra dummy commit.

  2. Rebase and merge
    Will append all commits history of the feature branch in the front of the master branch
    Will NOT add extra dummy commit.

  3. Squash and merge
    Will group all feature branch commits into one commit then append it in the front of the master branch
    Will add extra dummy commit.

You can find below how the master branch will look after each one of them.

enter image description here

In all cases:
We can safely DELETE the feature branch.

Replacing blank values (white space) with NaN in pandas

This should work

df.loc[df.Variable == '', 'Variable'] = 'Value'

or

df.loc[df.Variable1 == '', 'Variable2'] = 'Value'

How can I do factory reset using adb in android?

You can send intent MASTER_CLEAR in adb:

adb shell am broadcast -a android.intent.action.MASTER_CLEAR

or as root

adb shell  "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"

How to parseInt in Angular.js

Perform the operation inside the scope itself.

<script>
angular.controller('MyCtrl', function($scope, $window) {
$scope.num1= 0;
$scope.num2= 1;


  $scope.total = $scope.num1 + $scope.num2;

 });
</script>
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">

Total: {{total}}

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

Numpy: find index of the elements within range

Wanted to add numexpr into the mix:

import numpy as np
import numexpr as ne

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)

Would only make sense for larger arrays with millions... or if you hitting a memory limits.

How does paintComponent work?

Calling object.paintComponent(g) is an error.

Instead this method is called automatically when the panel is created. The paintComponent() method can also be called explicitly by the repaint() method defined in Component class.

The effect of calling repaint() is that Swing automatically clears the graphic on the panel and executes the paintComponent method to redraw the graphics on this panel.

Height of an HTML select box (dropdown)

Confirmed.

The part that drops down is set to either:

  1. The height needed to show all entries, or
  2. The height needed to show x entries (with scrollbars to see remaining), where x is
    • 20 in Firefox & Chrome
    • 30 in IE 6, 7, 8
    • 16 for Opera 10
    • 14 for Opera 11
    • 22 for Safari 4
    • 18 for Safari 5
    • 11 in IE 5.0, 5.5
  3. In IE/Edge, if there are no options, a stupidly high list of 11 blanks entries.

For (3) above you can see the results in this JSFiddle

Simple timeout in java

What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is

Option 1 (preferred):

final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

try {
    handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    handler.cancel(true);
}

executor.shutdownNow();

Option 2:

final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

executor.schedule(new Runnable() {
    @Override
    public void run(){
        handler.cancel(true);
    }      
}, timeout.toMillis(), TimeUnit.MILLISECONDS);

executor.shutdownNow();

Those are only a draft so that you can get the main idea.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()

How to modify a specified commit?

For me it was for removing some credentials from a repo. I tried rebasing and ran into a ton of seemingly unrelated conflicts along the way when trying to rebase --continue. Don't bother attempting to rebase yourself, use the tool called BFG (brew install bfg) on mac.

Saving excel worksheet to CSV files with filename+worksheet name using VB

Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)

Body of Http.DELETE request in Angular2

Below is a relevant code example for Angular 4/5 with the new HttpClient.

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

public removeItem(item) {
    let options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      body: item,
    };

    return this._http
      .delete('/api/menu-items', options)
      .map((response: Response) => response)
      .toPromise()
      .catch(this.handleError);
  }

Array of PHP Objects

Yes.

$array[] = new stdClass;
$array[] = new stdClass;

print_r($array);

Results in:

Array
(
    [0] => stdClass Object
        (
        )

    [1] => stdClass Object
        (
        )

)

Opening the Settings app from another app

From @Yatheeshaless's answer:

You can open settings app programmatically in iOS8, but not in earlier versions of iOS.

Swift:

   UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)

Swift 4:

if let url = NSURL(string: UIApplicationOpenSettingsURLString) as URL? {
    UIApplication.shared.openURL(url)
}

Swift 4.2 (BETA):

if let url = NSURL(string: UIApplication.openSettingsURLString) as URL? {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Objective-C:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

HTML form submit to PHP script

Try this:

<form method="post" action="check.php">
    <select name="website_string">
        <option value="" selected="selected"></option>
        <option VALUE="abc"> ABC</option>
        <option VALUE="def"> def</option>
        <option VALUE="hij"> hij</option>
    </select>
    <input TYPE="submit" name="submit" />
</form>

Both your select control and your submit button had the same name attribute, so the last one used was the submit button when you clicked it. All other syntax errors aside.

check.php

<?php
    echo $_POST['website_string'];
?>

Obligatory disclaimer about using raw $_POST data. Sanitize anything you'll actually be using in application logic.

Tracking CPU and Memory usage per process

Although I have not tried this out, ProcDump seems like a better solution.

Description from site:

ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (using the same definition of a window hang that Windows and Task Manager use), unhandled exception monitoring and can generate dumps based on the values of system performance counters. It also can serve as a general process dump utility that you can embed in other scripts.

Async await in linq select

I prefer this as an extension method:

public static async Task<IEnumerable<T>> WhenAll<T>(this IEnumerable<Task<T>> tasks)
{
    return await Task.WhenAll(tasks);
}

So that it is usable with method chaining:

var inputs = await events
  .Select(async ev => await ProcessEventAsync(ev))
  .WhenAll()

Prevent flex items from overflowing a container

One easy solution is to use overflow values other than visible to make the text flex basis width reset as expected.

  1. Here with value auto the text wraps as expected and the article content does not overflow main container.

  2. Also, the article flex value must either have a auto basis AND be able to shrink, OR, only grow AND explicit 0 basis

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
  overflow: auto; /* 1. overflow not `visible` */_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
  /* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

iFrame Height Auto (CSS)

@SweetSpice, use position as absolute in place of relative. It will work

#frame{
overflow: hidden;
width: 860px;
height: 100%;
position: absolute;
}

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

Can angularjs routes have optional parameter values?

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

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

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

How to implement a Boolean search with multiple columns in pandas

All the considerations made by @EdChum in 2014 are still valid, but the pandas.Dataframe.ix method is deprecated from the version 0.0.20 of pandas. Directly from the docs:

Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

In subsequent versions of pandas, this method has been replaced by new indexing methods pandas.Dataframe.loc and pandas.Dataframe.iloc.

If you want to learn more, in this post you can find comparisons between the methods mentioned above.

Ultimately, to date (and there does not seem to be any change in the upcoming versions of pandas from this point of view), the answer to this question is as follows:

foo = df.loc[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

How can I use goto in Javascript?

// example of goto in javascript:

var i, j;
loop_1:
    for (i = 0; i < 3; i++) { //The first for statement is labeled "loop_1"
        loop_2:
            for (j = 0; j < 3; j++) { //The second for statement is labeled "loop_2"
                if (i === 1 && j === 1) {
                    continue loop_1;
                }
                console.log('i = ' + i + ', j = ' + j);
            }
        }

Java SecurityException: signer information does not match

this happened to me when using JUnit + rest assured + hamcrest, in this case, dont add junit to build path, if you have the maven project, this resolved me, below is the pom.xml

<dependencies>

    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>

    </dependency>


</dependencies>

Transferring files over SSH

You need to specify both source and destination, and if you want to copy directories you should look at the -r option.

So to recursively copy /home/user/whatever from remote server to your current directory:

scp -pr user@remoteserver:whatever .

How to get file extension from string in C++

A NET/CLI version using System::String

   System::String^ GetFileExtension(System::String^ FileName)
   {
       int Ext=FileName->LastIndexOf('.');
       if( Ext != -1 )
           return FileName->Substring(Ext+1);
       return "";
   }

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

According to http://shouldiprefix.com/#appearance

Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.

I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/

What methods of ‘clearfix’ can I use?

I always use the micro-clearfix :

.cf:before,
.cf:after {
    content: " ";
    display: table;
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 */
.cf {
    *zoom: 1;
}

In Cascade Framework I even apply it by default on block level elements. IMO, applying it by default on block level elements gives block level elements more intuitive behavior than their traditonal behavior. It also made it a lot easier for me to add support for older browsers to Cascade Framework (which supports IE6-8 as well as modern browsers).

"No Content-Security-Policy meta tag found." error in my phonegap application

After adding the cordova-plugin-whitelist, you must tell your application to allow access all the web-page links or specific links, if you want to keep it specific.

You can simply add this to your config.xml, which can be found in your application's root directory:

Recommended in the documentation:

<allow-navigation href="http://example.com/*" />

or:

<allow-navigation href="http://*/*" />

From the plugin's documentation:

Navigation Whitelist

Controls which URLs the WebView itself can be navigated to. Applies to top-level navigations only.

Quirks: on Android it also applies to iframes for non-http(s) schemes.

By default, navigations only to file:// URLs, are allowed. To allow other other URLs, you must add tags to your config.xml:

<!-- Allow links to example.com -->
<allow-navigation href="http://example.com/*" />

<!-- Wildcards are allowed for the protocol, as a prefix
     to the host, or as a suffix to the path -->
<allow-navigation href="*://*.example.com/*" />

<!-- A wildcard can be used to whitelist the entire network,
     over HTTP and HTTPS.
     *NOT RECOMMENDED* -->
<allow-navigation href="*" />

<!-- The above is equivalent to these three declarations -->
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />

How to center body on a page?

Also apply text-align: center; on the html element like so:

html {
  text-align: center;
}

A better approach though is to have an inner container div, which will be centralized, and not the body.

Android/Eclipse: how can I add an image in the res/drawable folder?

When inserting an image into the drawable folders, another import point in addition to the "no capital letters" rule is that the image name cannot contain dashes or other special characters.

Choosing line type and color in Gnuplot 4.0

I've ran into this topic, because i was struggling with dashed lines too (gnuplot 4.6 patchlevel 0)

If you use:

set termoption dashed

Your posted code will work accordingly.

Related question:
However, if I want to export a png with: set terminal png, this isn't working anymore. Anyone got a clue why?

Turns out, out, gnuplots png export library doesnt support this.
Possbile solutions:

  • one can simply export to ps, then convert it with pstopng
  • according to @christoph, if you use pngcairo as your terminal (set terminal pngcairo) it will work

javax.faces.application.ViewExpiredException: View could not be restored

I add the following configuration to web.xml and it got resolved.

<context-param>
    <param-name>com.sun.faces.numberOfViewsInSession</param-name>
    <param-value>500</param-value>
</context-param>
<context-param>
    <param-name>com.sun.faces.numberOfLogicalViews</param-name>
    <param-value>500</param-value>
</context-param>

QED symbol in latex

You can use \blacksquare ¦:

When creating TeX, Knuth provided the symbol ¦ (solid black square), also called by mathematicians tombstone or Halmos symbol (after Paul Halmos, who pioneered its use as an equivalent of Q.E.D.). The tombstone is sometimes open: ? (hollow black square).

How to correctly assign a new string value?

Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

But you can call functions to help achieve what you want.

The strncpy() function could be used here. For maximum safety I suggest following this pattern:

strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case

Also have a look at the strncat() and memcpy() functions.

move a virtual machine from one vCenter to another vCenter

Copying the VM files onto an external HDD and then bringing it in to the destination will take a lot longer and requires multiple steps. Using vCenter Converter Standalone Client will do everything for you and is much faster. No external HDD required. Not sure where you got the cloning part from. vCenter Converter Standalone Client is simply copying the VM files by importing and exporting from source to destination, shutdown the source VM, then register the VM at destination and power on. All in one step. Takes about 1 min to set that up vCenter Converter Standalone Client.

How to Get enum item name from its value

How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."

On some older C code (quite some time ago), I found code analogous to:

std::string weekEnumToStr(int n)
{
   std::string s("unknown");
   switch (n)
   {
   case 0: { s = "Mon"; } break;
   case 1: { s = "Tue"; } break;
   case 2: { s = "Wed"; } break;
   case 3: { s = "Thu"; } break;
   case 4: { s = "Fri"; } break;
   case 5: { s = "Sat"; } break;
   case 6: { s = "Sun"; } break;
   }
   return s;
}

Con: This establishes a "pathological dependency" between the enumeration values and the function... meaning if you change the enum you must change the function to match. I suppose this is true even for a std::map.

I vaguely remember we found a utility to generate the function code from the enum code. The enum table length had grown to several hundred ... and at some point it is maybe a sound choice to write code to write code.


Note -

in an embedded system enhancement effort, my team replaced many tables (100+?) of null-terminated-strings used to map enum int values to their text strings.

The problem with the tables was that a value out of range was often not noticed because many of these tables were gathered into one region of code / memory, such that a value out-of-range reached past the named table end(s) and returned a null-terminated-string from some subsequent table.

Using the function-with-switch statement also allowed us to add an assert in the default clause of the switch. The asserts found several more coding errors during test, and our asserts were tied into a static-ram-system-log our field techs could search.

How do I remove the space between inline/inline-block elements?

I had this problem right now and from font-size:0; I've found that in Internet Explorer 7 the problem remains because Internet Explorer thinks "Font Size 0?!?! WTF are you crazy man?" - So, in my case I've Eric Meyer's CSS reset and with font-size:0.01em; I have a difference of 1 pixel from Internet Explorer 7 to Firefox 9, so, I think this can be a solution.

Get selected key/value of a combo box using jQuery

<select name="foo" id="foo">
 <option value="1">a</option>
 <option value="2">b</option>
 <option value="3">c</option>
  </select>
  <input type="button" id="button" value="Button" />
  });
  <script> ("#foo").val() </script>

which returns 1 if you have selected a and so on..

Concatenating two std::vectors

vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Make sure that both projects are in the same .net version also check copy local property but this should be true as default

What are the dark corners of Vim your mom never told you about?

:! [command] executes an external command while you're in Vim.

But add a dot after the colon, :.! [command], and it'll dump the output of the command into your current window. That's : . !

For example:

:.! ls

I use this a lot for things like adding the current date into a document I'm typing:

:.! date

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

Parameter in like clause JPQL

Use JpaRepository or CrudRepository as repository interface:

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

    @Query("SELECT t from Customer t where LOWER(t.name) LIKE %:name%")
    public List<Customer> findByName(@Param("name") String name);

}


@Service(value="customerService")
public class CustomerServiceImpl implements CustomerService {

    private CustomerRepository customerRepository;
    
    //...

    @Override
    public List<Customer> pattern(String text) throws Exception {
        return customerRepository.findByName(text.toLowerCase());
    }
}

how to reference a YAML "setting" from elsewhere in the same YAML file?

I've create a library, available on Packagist, that performs this function: https://packagist.org/packages/grasmash/yaml-expander

Example YAML file:

type: book
book:
  title: Dune
  author: Frank Herbert
  copyright: ${book.author} 1965
  protaganist: ${characters.0.name}
  media:
    - hardcover
characters:
  - name: Paul Atreides
    occupation: Kwisatz Haderach
    aliases:
      - Usul
      - Muad'Dib
      - The Preacher
  - name: Duncan Idaho
    occupation: Swordmaster
summary: ${book.title} by ${book.author}
product-name: ${${type}.title}

Example logic:

// Parse a yaml string directly, expanding internal property references.
$yaml_string = file_get_contents("dune.yml");
$expanded = \Grasmash\YamlExpander\Expander::parse($yaml_string);
print_r($expanded);

Resultant array:

array (
  'type' => 'book',
  'book' => 
  array (
    'title' => 'Dune',
    'author' => 'Frank Herbert',
    'copyright' => 'Frank Herbert 1965',
    'protaganist' => 'Paul Atreides',
    'media' => 
    array (
      0 => 'hardcover',
    ),
  ),
  'characters' => 
  array (
    0 => 
    array (
      'name' => 'Paul Atreides',
      'occupation' => 'Kwisatz Haderach',
      'aliases' => 
      array (
        0 => 'Usul',
        1 => 'Muad\'Dib',
        2 => 'The Preacher',
      ),
    ),
    1 => 
    array (
      'name' => 'Duncan Idaho',
      'occupation' => 'Swordmaster',
    ),
  ),
  'summary' => 'Dune by Frank Herbert',
);

TensorFlow not found using pip

The only thing that worked for me was to use Ananconda and create a new conda env with conda create -n tensorflow python=3.5 then activate using activate tensorflow and finally conda install -c conda-forge tensorflow.

This works around every issue I had including ssl certs, proxy settings, and does not need admin access. It should be noted that this is not directly supported by the tensorflow team.

Source

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

String split on new line, tab and some number of spaces

Regex's aren't really the best tool for the job here. As others have said, using a combination of str.strip() and str.split() is the way to go. Here's a one liner to do it:

>>> data = '''\n\tName: John Smith
... \n\t  Home: Anytown USA
... \n\t    Phone: 555-555-555
... \n\t  Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t  Misc: Data with spaces'''
>>> {line.strip().split(': ')[0]:line.split(': ')[1] for line in data.splitlines() if line.strip() != ''}
{'Name': 'Jane Smith', 'Other Home': 'Somewhere Else', 'Notes': 'Other data', 'Misc': 'Data with spaces', 'Phone': '555-555-555', 'Home': 'Anytown USA'}

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

Right click on the project and select [replace with] -> Head Revision .Now select pull changes in current branch or pull changes from upstream.

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

Randomize numbers with jQuery?

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6);

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 6);
  $('#my_div').text(number);
},
1000); // every 1 second

Base table or view not found: 1146 Table Laravel 5

If your error is not related to the issue of

Laravel can't determine the plural form of the word you used for your table name.

with this solution

and still have this error, try my approach. you should find the problem in the default "AppServiceProvider.php" or other ServiceProviders defined for that application specifically or even in Kernel.php in App\Console

This error happened for me and I solved it temporary and still couldn't figure out the exact origin and description.

In my case the main problem for causing my table unable to migrate, is that I have running code/query on my "PermissionsServiceProvider.php" in the boot() method.

In the same way, maybe, you defined something in boot() method of AppServiceProvider.php or in the Kernel.php

So first check your Serviceproviders and disable code for a while, and run php artisan migrate and then undo changes in your code.

Chrome Dev Tools - Modify javascript and reload

The Resource Override extension allows you to do exactly that:

  • create a file rule for the url you want to replace
  • edit the js/css/etc in the extension
  • reload as often as you want :)

Check if a string within a list contains a specific string with Linq

LINQ Any() would do the job:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

background-image: url("images/plaid.jpg") no-repeat; wont show up

If that really is all that's in your CSS file, then yes, nothing will happen. You need a selector, even if it's as simple as body:

body {
    background-image: url(...);
}

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

As Kristian Glass Said, there is no comparison between IaaS(AWS) and PaaS(Heroku, EngineYard).

PaaS basically helps developers to speed the development of app,thereby saving money and most importantly innovating their applications and business instead of setting up configurations and managing things like servers and databases. Other features buying to use PaaS is the application deployment process such as agility, High Availability, Monitoring, Scale / Descale, limited need for expertise, easy deployment, and reduced cost and development time.

But still there is a dark side to PaaS which lead barrier to PaaS adoption :

  • Less Control over Server and databases
  • Costs will be very high if not governed properly
  • Premature and dubious in current day and age

Apart from above you should have enough skill set to mange you IaaS:

  • Hardware acquisition
  • Operating System
  • Server Software
  • Server Side Scripting Environment
  • Web server
  • Database Management System(Mysql, Redis etc)
  • Configure production server
  • Tool for testing and deployment
  • Monitoring App
  • High Availability
  • Load Blancing/ Http Routing
  • Service Backup Policies
  • Team Collaboration
  • Rebuild Production

If you have small scale business, PaaS will be best option for you:

  • Pay as you Go
  • Low start up cost
  • Leave the plumbing to expert
  • PaaS handles auto scaling/descaling, Load balancing, disaster recovery
  • PaaS manages all security requirements
  • PaaS manages reliability, High Availability
  • Paas manages many third party add-ons for you

It will be totally individual choice based on requirement. You can have details on my PPT Hosting Rails Apps.

How to control border height?

not bad .. but try this one ... (should works for all but ist just -webkit included)

<br>
<input type="text" style="
  background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">

//Feel free to edit and add all other browser..

Adding a leading zero to some values in column in MySQL

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):

UPDATE table SET phone_num = concat('0', phone_num) 

I just concated 0 in front of the phone_num.

Python Requests and persistent sessions

Upon trying all the answers above, I found that using "RequestsCookieJar" instead of the regular CookieJar for subsequent requests fixed my problem.

import requests
import json

# The Login URL
authUrl = 'https://whatever.com/login'

# The subsequent URL
testUrl = 'https://whatever.com/someEndpoint'

# Logout URL
testlogoutUrl = 'https://whatever.com/logout'

# Whatever you are posting
login_data =  {'formPosted':'1', 
               'login_email':'[email protected]', 
               'password':'pw'
               }

# The Authentication token or any other data that we will receive from the Authentication Request. 
token = ''

# Post the login Request
loginRequest = requests.post(authUrl, login_data)
print("{}".format(loginRequest.text))

# Save the request content to your variable. In this case I needed a field called token. 
token = str(json.loads(loginRequest.content)['token'])  # or ['access_token']
print("{}".format(token))

# Verify Successful login
print("{}".format(loginRequest.status_code))

# Create your Requests Cookie Jar for your subsequent requests and add the cookie
jar = requests.cookies.RequestsCookieJar()
jar.set('LWSSO_COOKIE_KEY', token)

# Execute your next request(s) with the Request Cookie Jar set
r = requests.get(testUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))
print("R.STCD: {}".format(r.status_code))

# Execute your logout request(s) with the Request Cookie Jar set
r = requests.delete(testlogoutUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))  # should show "Request Not Authorized"
print("R.STCD: {}".format(r.status_code))  # should show 401

How to copy to clipboard in Vim?

In your vimrc file you can specify to automatically use the system clipboard for copy and paste.

On Windows set:

set clipboard=unnamed

On Linux set (vim 7.3.74+):

set clipboard=unnamedplus

NOTE: You may need to use an up to date version of Vim for these to work.

http://vim.wikia.com/wiki/Accessing_the_system_clipboard

How to force R to use a specified factor level as reference in a regression?

See the relevel() function. Here is an example:

set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
                 y = 4 + (1.5*x) + rnorm(100, sd = 2),
                 b = gl(5, 20))
head(DF)
str(DF)

m1 <- lm(y ~ x + b, data = DF)
summary(m1)

Now alter the factor b in DF by use of the relevel() function:

DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)

The models have estimated different reference levels.

> coef(m1)
(Intercept)           x          b2          b3          b4          b5 
  3.2903239   1.4358520   0.6296896   0.3698343   1.0357633   0.4666219 
> coef(m2)
(Intercept)           x          b1          b2          b4          b5 
 3.66015826  1.43585196 -0.36983433  0.25985529  0.66592898  0.09678759

How to change a dataframe column from String type to Double type in PySpark?

pyspark version:

  df = <source data>
  df.printSchema()

  from pyspark.sql.types import *

  # Change column type
  df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
  df_new.printSchema()
  df_new.select("myColumn").show()

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Remove json element

All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:

var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];

This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

std::string text = "--foo=98";
std::string start = "--foo=";

if (text.find(start) == 0)
{
    int n = stoi(text.substr(start.length()));
    std::cout << n << std::endl;
}

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.

How to use a filter in a controller?

Reusing An Angular.js Filter - View / Controller

This Solution is covering reusing Angular Filters. Which is yet another way to filter data, and Google landed me here when I needed such; and I like to share.

Use Case

If you are already filtering, say in an ng-repeat in your view (as below), then you might have defined a filter in the controller as further follows. And then you can reuse as in the final examples.

Filter Use Example - Filtered Repeat in View

<div ng-app="someApp" ng-controller="someController">
    <h2>Duplicates</h2>
    <table class="table table-striped table-light table-bordered-light">
        <thead>
            <tr>
                <th>Name</th>
                <th>Gender</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="person in data | filter: searchDuplicate:true">
                <td>{{person.name}}</td>
                <td>{{person.gender}}</td>
            </tr>
        </tbody>
    </table>
</div>

Angular Filter Definition Example

angular.module('someApp',[])
.controller('someController', function($scope, $filter ) {

    $scope.people = [{name: 'Bob', gender: 'male'  , hasDuplicate: true },
                     {name: 'Bob', gender: 'male'  , hasDuplicate: true },
                     {name: 'Bob', gender: 'female', hasDuplicate: false}];

    $scope.searchDuplicate = { hasDuplicate : true };
})

So, the concept here is that you are already using a filter created for your view, and then realize you would like to use it in your controller also.

Filter Function Use Within Controller Example 1

var dup = $filter('filter')($scope.people, $scope.searchDuplicate, true)

Filter Function Use Within Controller Example 2

Show a Button only if no duplicates are found, using the prior filter.

Html Button

<div ng-if="showButton()"><button class="btn btn-primary" ng-click="doSomething();"></button></div>

Show/Hide Button

$scope.doSomething = function(){ /* ... */ };
$scope.showButton = function(){ return $filter('filter')($scope.people, $scope.searchDuplicate, true).length == 0; };

Some may find this version of filtering easy, and it is an Angular.js option.

The optional comparator parameter "true" used in the view and in the $filter function call specifies you want a strict comparison. If you omit, values can be searched for over multiple columns.

https://docs.angularjs.org/api/ng/filter/filter

How to create a file in Ruby

You can also use constants instead of strings to specify the mode you want. The benefit is if you make a typo in a constant name, your program will raise an runtime exception.

The constants are File::RDONLY or File::WRONLY or File::CREAT. You can also combine them if you like.

Full description of file open modes on ruby-doc.org

How to hide action bar before activity is created, and then show it again?

Put your splash screen in a separate activity and use startActivityForResult from your main activity's onCreate method to display it. This works because, according to the docs:

As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.

You should probably do this only if the argument to onCreate is null (indicating a fresh launch of your activity, as opposed to a restart due to a configuration change).

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Building on D.A.'s suggestion that "the only way to do what you want is to modify the underlying data" and using numpy to modify the underlying data...

This works for me, and is pretty fast:

def tz_to_naive(datetime_index):
    """Converts a tz-aware DatetimeIndex into a tz-naive DatetimeIndex,
    effectively baking the timezone into the internal representation.

    Parameters
    ----------
    datetime_index : pandas.DatetimeIndex, tz-aware

    Returns
    -------
    pandas.DatetimeIndex, tz-naive
    """
    # Calculate timezone offset relative to UTC
    timestamp = datetime_index[0]
    tz_offset = (timestamp.replace(tzinfo=None) - 
                 timestamp.tz_convert('UTC').replace(tzinfo=None))
    tz_offset_td64 = np.timedelta64(tz_offset)

    # Now convert to naive DatetimeIndex
    return pd.DatetimeIndex(datetime_index.values + tz_offset_td64)

Adjust icon size of Floating action button (fab)

As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center" in your ImageButton to avoid auto resize.

Error message "Forbidden You don't have permission to access / on this server"

This is pretty ridiculous, but I got the 403 Forbidden when the file I was trying to download wasn't there on the filesystem. The apache error is not very accurate in this case, and the whole thing worked after I simply put the file where it was supposed to be.

opening a window form from another form programmatically

This might also help:

void ButtQuitClick(object sender, EventArgs e)
{
    QuitWin form = new QuitWin();
    form.Show();
}

Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.

When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.

What does @media screen and (max-width: 1024px) mean in CSS?

It targets some specified feature to execute some other codes...

For example:

@media all and (max-width: 600px) {
  .navigation {
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
    padding: 0;

  }

the above snippet say if the device that run this program have screen with 600px or less than 600px width, in this case our program must execute this part .

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Why can't I shrink a transaction log file, even after backup?

Try creating another full backup after you backup the log w/ truncate_only (IIRC you should do this anyway to maintain the log chain). In simple recovery mode, your log shouldn't grow much anyway since it's effectively truncated after every transaction. Then try specifying the size you want the logfile to be, e.g.

-- shrink log file to c. 1 GB
DBCC SHRINKFILE (Wxlog0, 1000);

The TRUNCATEONLY option doesn't rearrange the pages inside the log file, so you might have an active page at the "end" of your file, which could prevent it from being shrunk.

You can also use DBCC SQLPERF(LOGSPACE) to make sure that there really is space in the log file to be freed.

remove objects from array by object property

To delete an object by it's id in given array;

const hero = [{'id' : 1, 'name' : 'hero1'}, {'id': 2, 'name' : 'hero2'}];
//remove hero1
const updatedHero = hero.filter(item => item.id !== 1);

R: "Unary operator error" from multiline ggplot2 command

Try to consolidate the syntax in a single line. this will clear the error

Creating a PDF from a RDLC Report in the Background

You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.

Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;`enter code here`
        string extension = string.Empty;
        DataSet dsGrpSum, dsActPlan, dsProfitDetails,
            dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;

    enter code here

//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
            param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
            param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
            param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
            param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
            param[4] = new ReportParameter("Report_Parameter_4", "5th Para");

            DataSet  dsData= "Fill this dataset with your data";
            ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
            ReportViewer viewer = new ReportViewer();
            viewer.LocalReport.Refresh();
            viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
            viewer.LocalReport.SetParameters(param);
            viewer.LocalReport.DataSources.Add(rdsAct); // Add  datasource here         
            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            // byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.          
            // System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
            Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
            Response.Flush(); // send it to the client to download  
            Response.End();

How To Get Selected Value From UIPickerView

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   weightSelected = [pickerArray objectAtIndex:row];
}

How does Facebook disable the browser's integrated Developer Tools?

I couldn't get it to trigger that on any page. A more robust version of this would do it:

window.console.log = function(){
    console.error('The developer console is temp...');
    window.console.log = function() {
        return false;
    }
}

console.log('test');

To style the output: Colors in JavaScript console

Edit Thinking @joeldixon66 has the right idea: Disable JavaScript execution from console « ::: KSpace :::

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

How to fit a smooth curve to my data in R?

I like loess() a lot for smoothing:

x <- 1:10
y <- c(2,4,6,8,7,12,14,16,18,20)
lo <- loess(y~x)
plot(x,y)
lines(predict(lo), col='red', lwd=2)

Venables and Ripley's MASS book has an entire section on smoothing that also covers splines and polynomials -- but loess() is just about everybody's favourite.

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

For those still having this issue, my issue was resolved in the AndroidManifest.xml file. Where it says <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">, you need to remove NoActionBar, making it <activity android:name=".MainActivity" android:theme="@style/AppTheme">, because with NoActionBar set the app doesnt know whether or not it wants an action bar when you call one up inside of MainActivity.java

dynamically add and remove view to viewpager

I was looking for simple solution to remove views from viewpager (no fragments) dynamically. So, if you have some info, that your pages belongs to, you can set it to View as tag. Just like that (adapter code):

@Override
public Object instantiateItem(ViewGroup collection, int position)
{
    ImageView iv = new ImageView(mContext);
    MediaMessage msg = mMessages.get(position);
    ...

    iv.setTag(media);
    return iv;
}

@Override
public int getItemPosition (Object object)
{
    View o = (View) object;
    int index = mMessages.indexOf(o.getTag());
    if (index == -1)
        return POSITION_NONE;
    else
        return index;
}

You just need remove your info from mMessages, and then call notifyDataSetChanged() for your adapter. Bad news there is no animation in this case.

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

How to access environment variable values?

For django see (https://github.com/joke2k/django-environ)

$ pip install django-environ

import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()

# False if not in os.environ
DEBUG = env('DEBUG')

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

Generate random numbers uniformly over an entire range

This should provide a uniform distribution over the range [low, high) without using floats, as long as the overall range is less than RAND_MAX.

uint32_t rand_range_low(uint32_t low, uint32_t high)
{
    uint32_t val;
    // only for 0 < range <= RAND_MAX
    assert(low < high);
    assert(high - low <= RAND_MAX);

    uint32_t range = high-low;
    uint32_t scale = RAND_MAX/range;
    do {
        val = rand();
    } while (val >= scale * range); // since scale is truncated, pick a new val until it's lower than scale*range
    return val/scale + low;
}

and for values greater than RAND_MAX you want something like

uint32_t rand_range(uint32_t low, uint32_t high)
{
    assert(high>low);
    uint32_t val;
    uint32_t range = high-low;
    if (range < RAND_MAX)
        return rand_range_low(low, high);
    uint32_t scale = range/RAND_MAX;
    do {
        val = rand() + rand_range(0, scale) * RAND_MAX; // scale the initial range in RAND_MAX steps, then add an offset to get a uniform interval
    } while (val >= range);
    return val + low;
}

This is roughly how std::uniform_int_distribution does things.

Safe navigation operator (?.) or (!.) and null property paths

Building on @Pvl's answer, you can include type safety on your returned value as well if you use overrides:

function dig<
  T,
  K1 extends keyof T
  >(obj: T, key1: K1): T[K1];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1]
  >(obj: T, key1: K1, key2: K2): T[K1][K2];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2]
  >(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3]
  >(obj: T, key1: K1, key2: K2, key3: K3, key4: K4): T[K1][K2][K3][K4];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3],
  K5 extends keyof T[K1][K2][K3][K4]
  >(obj: T, key1: K1, key2: K2, key3: K3, key4: K4, key5: K5): T[K1][K2][K3][K4][K5];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3],
  K5 extends keyof T[K1][K2][K3][K4]
  >(obj: T, key1: K1, key2?: K2, key3?: K3, key4?: K4, key5?: K5):
  T[K1] |
  T[K1][K2] |
  T[K1][K2][K3] |
  T[K1][K2][K3][K4] |
  T[K1][K2][K3][K4][K5] {
    let value: any = obj && obj[key1];

    if (key2) {
      value = value && value[key2];
    }

    if (key3) {
      value = value && value[key3];
    }

    if (key4) {
      value = value && value[key4];
    }

    if (key5) {
      value = value && value[key5];
    }

    return value;
}

Example on playground.

Two div blocks on same line

Try an HTML table or use the following CSS :

<div id="bloc1" style="float:left">...</div>
<div id="bloc2">...</div>

(or use an HTML table)

chai test array equality doesn't work as expected

This is how to use chai to deeply test associative arrays.

I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)

I did it by defining the variable as an object (not array) prior to my function call:

var myAssocArray = {};   // not []
var expectedAssocArray = {};  // not []

expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';

// legacy function which returns associate array reference
myFunction(myAssocArray);

assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');

When do I need to use a semicolon vs a slash in Oracle SQL?

It's a matter of preference, but I prefer to see scripts that consistently use the slash - this way all "units" of work (creating a PL/SQL object, running a PL/SQL anonymous block, and executing a DML statement) can be picked out more easily by eye.

Also, if you eventually move to something like Ant for deployment it will simplify the definition of targets to have a consistent statement delimiter.

What is the MySQL JDBC driver connection string?

it's depends on what service you're using.

if you use MySQL Workbench it wold be some thing like this :

jdbc:mysql://"host":"port number"/

String url = "jdbc:mysql://localhost:3306/";

And of course it will be different if you using SSL/SSH.

For more information follow the official link of Jetbriens (intelliJ idea) :

Connecting to a database #

https://www.jetbrains.com/help/idea/connecting-to-a-database.html


Configuring database connections #

https://www.jetbrains.com/help/idea/configuring-database-connections.html

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

$(document).ready(function() is not working

Set events after loading DOM Elements.

$(function () {
        $(document).on("click","selector",function (e) {
          alert("hi");

        });

    });

SQL DROP TABLE foreign key constraint

If you want to DROP a table which has been referenced by other table using the foreign key use

DROP TABLE *table_name* CASCADE CONSTRAINTS;
I think it should work for you.

How to count items in JSON object using command line?

You can also use jq to track down the array within the returned json and then pipe that in to a second jq call to get its length. Suppose it was in a property called records, like {"records":[...]}.

$ curl https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$ 

How to Rotate a UIImage 90 degrees?

For Swift: Here is a simple extension to UIImage:

//ImageRotation.swift

import UIKit

extension UIImage {  
    public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
        let radiansToDegrees: (CGFloat) -> CGFloat = {
            return $0 * (180.0 / CGFloat(M_PI))
        }
        let degreesToRadians: (CGFloat) -> CGFloat = {
            return $0 / 180.0 * CGFloat(M_PI)
        }

        // calculate the size of the rotated view's containing box for our drawing space
        let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
        let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
        rotatedViewBox.transform = t
        let rotatedSize = rotatedViewBox.frame.size

        // Create the bitmap context
        UIGraphicsBeginImageContext(rotatedSize)
        let bitmap = UIGraphicsGetCurrentContext()

        // Move the origin to the middle of the image so we will rotate and scale around the center.
        CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);

        //   // Rotate the image context
        CGContextRotateCTM(bitmap, degreesToRadians(degrees));

        // Now, draw the rotated/scaled image into the context
        var yFlip: CGFloat

        if(flip){
            yFlip = CGFloat(-1.0)
        } else {
            yFlip = CGFloat(1.0)
        }

        CGContextScaleCTM(bitmap, yFlip, -1.0)
        CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }
}

(Source)

Use it with:

rotatedPhoto = rotatedPhoto?.imageRotatedByDegrees(90, flip: false) 

The former will rotate an image and flip it if flip is set to true.

Should black box or white box testing be the emphasis for testers?

It's a bit of an open door, but in the end both are about equally important.

What's worse?

  1. software that does what it needs to do, but internally has problems?

  2. software that is supposed to work if you look at the sources, but doesn't?

My answer: Neither is totally acceptable, but software cannot be proven to be 100% bugfree. So you're going to have to make some trade-offs. Option two is more directly noticable to clients, so you're going to get problems with that sooner. On the long run, option one is going to be problematic.

svn : how to create a branch from certain revision of trunk

Try below one:

svn copy http://svn.example.com/repos/calc/trunk@rev-no 
       http://svn.example.com/repos/calc/branches/my-calc-branch 
  -m "Creating a private branch of /calc/trunk."  --parents

No slash "\" between the svn URLs.

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

Sort a Custom Class List<T>

YourVariable.Sort((a, b) => a.amount.CompareTo(b.amount));

connect to host localhost port 22: Connection refused

Check if this port is open. Maybe your SSH demon is not running. See if sshd is running. If not, then start it.

Python using enumerate inside list comprehension

If you're using long lists, it appears the list comprehension's faster, not to mention more readable.

~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
1000000 loops, best of 3: 1.61 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
1000000 loops, best of 3: 0.978 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]"
1000000 loops, best of 3: 0.767 usec per loop

Python Anaconda - How to Safely Uninstall

If you're uninstalling Anaconda to be able to use the base Python installation in the system, you could temporarily disable the path by following these steps and not uninstalling Anaconda.

Go to your home directory. Just a cd command will do.

Edit the file .bashrc.

Look for something like export PATH="/home/ubuntu/anaconda3/bin:$PATH" in the file.

Put a # at the beginning to comment it from the script.

#export PATH="/home/ubuntu/anaconda3/bin:$PATH"

Open a new terminal and you should be running the base python installation. This works on Linux systems. Should work on Mac too.

Splitting String and put it on int array

Let's consider that you have input as "1,2,3,4".

That means the length of the input is 7. So now you write the size = 7/2 = 3.5. But as size is an int, it will be rounded off to 3. In short, you are losing 1 value.

If you rewrite the code as below it should work:

String input;
int length, count, size;
Scanner keyboard = new Scanner(System.in);
input = keyboard.next();
length = input.length();

String strarray[] = input.split(",");
int intarray[] = new int[strarray.length];

for (count = 0; count < intarray.length ; count++) {
    intarray[count] = Integer.parseInt(strarray[count]);
}

for (int s : intarray) {
    System.out.println(s);
}

Chrome:The website uses HSTS. Network errors...this page will probably work later

I encounter same error, and incognito mode also has same issue. I resolve this issue by clear Chrome history.

How to use the read command in Bash?

Another alternative altogether is to use the printf function.

printf -v str 'hello'

Moreover, this construct, combined with the use of single quotes where appropriate, helps to avoid the multi-escape problems of subshells and other forms of interpolative quoting.

How to disable margin-collapsing?

overflow:hidden prevents collapsing margins but it's not free of side effects - namely it... hides overflow.

Apart form this and what you've mentioned you just have to learn live with it and learn for this day when they are actually useful (comes every 3 to 5 years).

How to Git stash pop specific stash in 1.8.3?

I have 2.22 installed and this worked..

git stash pop --index 1

How can I use pickle to save a dict?

import pickle

dictobj = {'Jack' : 123, 'John' : 456}

filename = "/foldername/filestore"

fileobj = open(filename, 'wb')

pickle.dump(dictobj, fileobj)

fileobj.close()

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Calculating the distance between 2 points

Here is my 2 cents:

double dX = x1 - x2;
double dY = y1 - y2;
double multi = dX * dX + dY * dY;
double rad = Math.Round(Math.Sqrt(multi), 3, MidpointRounding.AwayFromZero);

x1, y1 is the first coordinate and x2, y2 the second. The last line is the square root with it rounded to 3 decimal places.

Difference between "git add -A" and "git add ."

In Git 2.x:

  • If you are located directly at the working directory, then git add -A and git add . work without the difference.

  • If you are in any subdirectory of the working directory, git add -A will add all files from the entire working directory, and git add . will add files from your current directory.

And that's all.

multiple where condition codeigniter

Try this

$data = array(
               'email' =>$email,
               'last_ip' => $last_ip
            );

$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data); 

How can I change the user on Git Bash?

For Mac Users

I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.

You need to remove those credentials from Keychain Access and then try to push.

Hope it help to Mac users.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Setting Java heap space under Maven 2 on Windows

It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

Default VM Arguments = -Xms128m -Xmx1024m

Is nested function a good approach when required by only one function?

Generally, no, do not define functions inside functions.

Unless you have a really good reason. Which you don't.

Why not?

What is a really good reason to define functions inside functions?

When what you actually want is a dingdang closure.

How to remove all white space from the beginning or end of a string?

String.Trim() removes all whitespace from the beginning and end of a string. To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

What is the difference between call and apply?

Difference between these to methods are, how you want to pass the parameters.

“A for array and C for comma” is a handy mnemonic.

find files by extension, *.html under a folder in nodejs

The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with .html

var fs = require('fs');
var path = require('path');

var searchRecursive = function(dir, pattern) {
  // This is where we store pattern matches of all files inside the directory
  var results = [];

  // Read contents of directory
  fs.readdirSync(dir).forEach(function (dirInner) {
    // Obtain absolute path
    dirInner = path.resolve(dir, dirInner);

    // Get stats to determine if path is a directory or a file
    var stat = fs.statSync(dirInner);

    // If path is a directory, scan it and combine results
    if (stat.isDirectory()) {
      results = results.concat(searchRecursive(dirInner, pattern));
    }

    // If path is a file and ends with pattern then push it onto results
    if (stat.isFile() && dirInner.endsWith(pattern)) {
      results.push(dirInner);
    }
  });

  return results;
};

var files = searchRecursive('./', '.html'); // replace dir and pattern
                                                // as you seem fit

console.log(files);

Why not inherit from List<T>?

There are some good answers here. I would add to them the following points.

What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?

Ask any ten non-computer-programmer people who are familiar with the existence of football to fill in the blank:

A football team is a particular kind of _____

Did anyone say "list of football players with a few bells and whistles", or did they all say "sports team" or "club" or "organization"? Your notion that a football team is a particular kind of list of players is in your human mind and your human mind alone.

List<T> is a mechanism. Football team is a business object -- that is, an object that represents some concept that is in the business domain of the program. Don't mix those! A football team is a kind of team; it has a roster, a roster is a list of players. A roster is not a particular kind of list of players. A roster is a list of players. So make a property called Roster that is a List<Player>. And make it ReadOnlyList<Player> while you're at it, unless you believe that everyone who knows about a football team gets to delete players from the roster.

Is inheriting from List<T> always unacceptable?

Unacceptable to who? Me? No.

When is it acceptable?

When you're building a mechanism that extends the List<T> mechanism.

What must a programmer consider, when deciding whether to inherit from List<T> or not?

Am I building a mechanism or a business object?

But that's a lot of code! What do I get for all that work?

You spent more time typing up your question that it would have taken you to write forwarding methods for the relevant members of List<T> fifty times over. You're clearly not afraid of verbosity, and we are talking about a very small amount of code here; this is a few minutes work.

UPDATE

I gave it some more thought and there is another reason to not model a football team as a list of players. In fact it might be a bad idea to model a football team as having a list of players too. The problem with a team as/having a list of players is that what you've got is a snapshot of the team at a moment in time. I don't know what your business case is for this class, but if I had a class that represented a football team I would want to ask it questions like "how many Seahawks players missed games due to injury between 2003 and 2013?" or "What Denver player who previously played for another team had the largest year-over-year increase in yards ran?" or "Did the Piggers go all the way this year?"

That is, a football team seems to me to be well modeled as a collection of historical facts such as when a player was recruited, injured, retired, etc. Obviously the current player roster is an important fact that should probably be front-and-center, but there may be other interesting things you want to do with this object that require a more historical perspective.

GitHub "fatal: remote origin already exists"

That error message indicates that you already have a remote in your git directory. If you are satisfied with that remote, your can push your code. If not or if you can't push just:

git remote remove origin
git remote add origin [email protected]:ppreyer/first_app.git

Voilà !

How to display list items as columns?

Thank you for this example, SPRBRN. It helped me. And I can suggest the mixin, which I've used based on the code given above:

//multi-column-list( fixed columns width)
  @mixin multi-column-list($column-width, $column-rule-style) {
  -webkit-column-width: $column-width;
  -moz-column-width: $column-width;
  -o-column-width: $column-width;
  -ms-column-width: $column-width;
  column-width: $column-width;

  -webkit-column-rule-style: $column-rule-style;
  -moz-column-rule-style: $column-rule-style;
  -o-column-rule-style: $column-rule-style;
  -ms-column-rule-style: $column-rule-style;
  column-rule-style: $column-rule-style;
 }

Using:

   @include multi-column-list(250px, solid);

Add leading zeroes to number in Java?

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

How do I suspend painting for a control and its children?

At my previous job we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls.

After a lot of googling and reflector usage I came across the WM_SETREDRAW win32 message. This really stops controls drawing whilst you update them and can be applied, IIRC to the parent/containing panel.

This is a very very simple class demonstrating how to use this message:

class DrawingControl
{
    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

    private const int WM_SETREDRAW = 11; 

    public static void SuspendDrawing( Control parent )
    {
        SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
    }

    public static void ResumeDrawing( Control parent )
    {
        SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
        parent.Refresh();
    }
}

There are fuller discussions on this - google for C# and WM_SETREDRAW, e.g.

C# Jitter

Suspending Layouts

And to whom it may concern, this is similar example in VB:

Public Module Extensions
    <DllImport("user32.dll")>
    Private Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As IntPtr) As Integer
    End Function

    Private Const WM_SETREDRAW As Integer = 11

    ' Extension methods for Control
    <Extension()>
    Public Sub ResumeDrawing(ByVal Target As Control, ByVal Redraw As Boolean)
        SendMessage(Target.Handle, WM_SETREDRAW, True, 0)
        If Redraw Then
            Target.Refresh()
        End If
    End Sub

    <Extension()>
    Public Sub SuspendDrawing(ByVal Target As Control)
        SendMessage(Target.Handle, WM_SETREDRAW, False, 0)
    End Sub

    <Extension()>
    Public Sub ResumeDrawing(ByVal Target As Control)
        ResumeDrawing(Target, True)
    End Sub
End Module

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

We were getting this same error in Fiddler when trying to figure out why our Silverlight ArcGIS map viewer wasn't loading the map. In our case it was a typo in the URL in the code. There was an equal sign in there for some reason.
http:=//someurltosome/awesome/place
instead of
http://someurltosome/awesome/place

After taking out that equal sign it worked great (of course).