Programs & Examples On #Logoff

Spring boot - Not a managed type

I am using spring boot 2.0 and I fixed this by replacing @ComponentScan with @EntityScan

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

Unable to load DLL 'SQLite.Interop.dll'

There are really a lot of answers here, but mine is simple and clear with no-GAC-playing-around.

The problem was, the executable File needs a copy of the right SQLite.Interop.dll (x86 or x64) to access our Database.

Mostly architectures have layers and in my case the Data Layer has the required DLL for SQLite Connection.

So i simple put a post build script into my Data Layer Solution and everything worked fine.


TL;DR;

  1. Set all Projects of your solution to x86 or x64 in the build options.

  2. Add following Post-Build-Script to the Project with the SQLite nuget Package:

    xcopy "$(TargetDir)x64" "$(SolutionDir)bin\Debug\" /y

Of course you have to change the script for Release Build and x86 builds.


STL;DR;

Put your SQLite.Interop.dll next to the *.exe File.

How to get value of checked item from CheckedListBox?

foreach (int x in chklstTerms.CheckedIndices)
{
    chklstTerms.SelectedIndex=x;
    termids.Add(chklstTerms.SelectedValue.ToString());
}

Pushing empty commits to remote

As long as you clearly reference the other commit from the empty commit it should be fine. Something like:

Commit message errata for [commit sha1]

[new commit message]

As others have pointed out, this is often preferable to force pushing a corrected commit.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

how to use getSharedPreferences in android

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;  
prefsEditor = myPrefs.edit();  
//strVersionName->Any value to be stored  
prefsEditor.putString("STOREDVALUE", strVersionName);  
prefsEditor.commit();

//Get Preferenece  
SharedPreferences myPrefs;    
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);  
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

Close window automatically after printing dialog closes

This works for me perfectly @holger, however, i have modified it and suit me better, the window now pops up and close immediately you hit the print or cancel button.

function printcontent()
{ 
var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
disp_setting+="scrollbars=yes,width=300, height=350, left=50, top=25"; 
var content_vlue = document.getElementById("content").innerHTML; 
var w = window.open("","", disp_setting);
w.document.write(content_vlue); //only part of the page to print, using jquery
w.document.close(); //this seems to be the thing doing the trick
w.focus();
w.print();
w.close();
}"

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

Eclipse - "Workspace in use or cannot be created, chose a different one."

Right answer can be found in this (duplicate) question.

I reproduced the answer here (and it works!):

Just delete the .lock file in the .metadata directory in your eclipse workspace directory

Can't accept license agreement Android SDK Platform 24

its mean miss match Android SDK version of cordova with the version you installed. For an example cordova support Android SDK 24 but you don't have Android sdk 24. it may be reverse.

REST API using POST instead of GET

Just to review, REST has certain properties that a developer should follow in order to make it RESTful:

What is REST?

According to wikipedia:

The REST architectural style describes the following six constraints applied to the architecture, while leaving the implementation of the individual components free to design:

  • Client–server: Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable.
  • Stateless: The client–server communication is further constrained by no client context being stored on the server between requests.
  • Cacheable: Responses must, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests.
  • Layered system: A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches.
  • Code on demand (optional): Servers can temporarily extend or customize the functionality of a client by the transfer of executable code.
  • Uniform interface: The uniform interface between clients and servers, discussed below, simplifies and decouples the architecture, which enables each part to evolve independently. (i.e. HTTP GET, POST, PUT, PATCH, DELETE)

What the verbs should do

SO user Daniel Vasallo did a good job of laying out the responsibilities of these methods in the question Understanding REST: Verbs, error codes, and authentication:

When dealing with a Collection URI like: http://example.com/resources/

GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.

PUT: Meaning defined as "replace the entire collection with another collection".

POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.

DELETE: Meaning defined as "delete the entire collection".

So, to answer your question:

Is it right to say that I can use it with a POST query? ...

Are these two queries the same? Can I use the second variant in any case or the documentation should explicitly say that I can use both GET and POST queries?

If you were writing a plain old RPC API call, they could technically interchangeable as long as the processing server side were no different between both calls. However, in order for the call to be RESTful, calling the endpoint via the GET method should have a distinct functionality (which is to get resource(s)) from the POST method (which is to create new resources).

Side note: there is some debate out there about whether or not POST should also be allowed to be used to update resources... though i'm not commenting on that, I'm just telling you some people have an issue with that point.

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

How to center HTML5 Videos?

HTML CODE:

<div>
 <video class="center" src="vd/vd1.mp4" controls poster="dossierimage/imagex.jpg" width="600">?</video>
</div>

CSS CODE:

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

How can I add numbers in a Bash script?

Use the $(( )) arithmetic expansion.

num=$(( $num + $metab ))

See Chapter 13. Arithmetic Expansion for more information.

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Box shadow for bottom side only

You can do the following after adding class one-edge-shadow or use as you like.

.one-edge-shadow {
    -webkit-box-shadow: 0 8px 6px -6px black;
       -moz-box-shadow: 0 8px 6px -6px black;
            box-shadow: 0 8px 6px -6px black;
}

Source

How to specify an alternate location for the .m2 folder or settings.xml permanently?

It's funny how other answers ignore the fact that you can't write to that file...

There are a few workarounds that come to my mind which could help use an arbitrary C:\redirected\settings.xml and use the mvn command as usual happily ever after.

mvn alias

In a Unix shell (or on Cygwin) you can create

alias mvn='mvn --global-settings "C:\redirected\settings.xml"'

so when you're calling mvn blah blah from anywhere the config is "automatically" picked up.
See How to create alias in cmd? if you want this, but don't have a Unix shell.

mvn wrapper

Configure your environment so that mvn is resolved to a wrapper script when typed in the command line:

  • Remove your MVN_HOME/bin or M2_HOME/bin from your PATH so mvn is not resolved any more.
  • Add a folder to PATH (or use an existing one)
  • In that folder create an mvn.bat file with contents:

    call C:\your\path\to\maven\bin\mvn.bat --global-settings "C:\redirected\settings.xml" %*
    

Note: if you want some projects to behave differently you can just create mvn.bat in the same folder as pom.xml so when you run plain mvn it resolves to the local one.

Use where mvn at any time to check how it is resolved, the first one will be run when you type mvn.

mvn.bat hack

If you have write access to C:\your\path\to\maven\bin\mvn.bat, edit the file and add set MAVEN_CMD_LINE_ARG to the :runm2 part:

@REM Start MAVEN2
:runm2
set MAVEN_CMD_LINE_ARGS=--global-settings "C:\redirected\settings.xml" %MAVEN_CMD_LINE_ARGS%
set CLASSWORLDS_LAUNCHER=...

mvn.sh hack

For completeness, you can change the C:\your\path\to\maven\bin\mvn shell script too by changing the exec "$JAVACMD" command's

${CLASSWORLDS_LAUNCHER} "$@"

part to

${CLASSWORLDS_LAUNCHER} --global-settings "C:\redirected\settings.xml" "$@"

Suggestion/Rant

As a person in IT it's funny that you don't have access to your own home folder, for me this constitutes as incompetence from the company you're working for: this is equivalent of hiring someone to do software development, but not providing even the possibility to use anything other than notepad.exe or Microsoft Word to edit the source files. I'd suggest to contact your help desk or administrator and request write access at least to that particular file so that you can change the path of the local repository.

Disclaimer: None of these are tested for this particular use case, but I successfully used all of them previously for various other software.

Convert ASCII number to ASCII Character in C

If i is the int, then

char c = i;

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

git error: failed to push some refs to remote

This happens to me as I had a tag with the same as the branch and I tried to push the branch to remote.

C# password TextBox in a ASP.net website

To do it the ASP.NET way:

<asp:TextBox ID="txtBox1" TextMode="Password" runat="server" />

Windows Scipy Install: No Lapack/Blas Resources Found

This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL, not just vanilla Numpy.

  1. Install python 3.5
  2. pip install "file path" (download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)
  3. pip install scipy

"ImportError: No module named" when trying to run Python script

Solution without scripting:

  1. Open Spyder -> Tools -> PYTHONPATH manager
  2. Add Python paths by clicking "Add Path". E.g: 'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages'
  3. Click "Synchronize..." to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  4. Restart Jupyter if it is open

how to use "tab space" while writing in text file

Use "\t". That's the tab space character.

You can find a list of many of the Java escape characters here: http://java.sun.com/docs/books/tutorial/java/data/characters.html

node.js string.replace doesn't work?

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");  

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");  

Expansion of variables inside single quotes in a command in Bash

Below is what worked for me -

QUOTE="'"
hive -e "alter table TBL_NAME set location $QUOTE$TBL_HDFS_DIR_PATH$QUOTE"

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

Use this in procedure

declare cu cursor for SELECT [name] FROM sys.Tables where [name] like 'tbl_%'
declare @table varchar(100)
declare @sql nvarchar(1000)

OPEN cu  
FETCH NEXT FROM cu INTO @table 

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @sql = N'delete from ' + @table
    EXEC sp_executesql @sql
    FETCH NEXT FROM cu INTO @table 
END   
CLOSE cu;  
DEALLOCATE cu;

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

Showing an image from an array of images - Javascript

This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
  "_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];

var imageIndex = 0; 

function changeImage() {
  myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex = (imageIndex + 1) % imageArray.length;
}

setInterval(changeImage, 5000);

AngularJS : Why ng-bind is better than {{}} in angular?

You can refer to this site it will give you a explanation which one is better as i know {{}} this is slower than ng-bind.

http://corpus.hubwiz.com/2/angularjs/16125872.html refer this site.

How to get subarray from array?

For a simple use of slice, use my extension to Array Class:

Array.prototype.subarray = function(start, end) {
    if (!end) { end = -1; } 
    return this.slice(start, this.length + 1 - (end * -1));
};

Then:

var bigArr = ["a", "b", "c", "fd", "ze"];

Test1:

bigArr.subarray(1, -1);

< ["b", "c", "fd", "ze"]

Test2:

bigArr.subarray(2, -2);

< ["c", "fd"]

Test3:

bigArr.subarray(2);

< ["c", "fd","ze"]

Might be easier for developers coming from another language (i.e. Groovy).

Reactjs - setting inline styles correctly

You could also try setting style inline without using a variable, like so:

style={{"height" : "100%"}} or,

for multiple attributes: style={{"height" : "100%", "width" : "50%"}}

How to properly exit a C# application?

Environment.Exit(exitCode); //exit code 0 is a proper exit and 1 is an error

List an Array of Strings in alphabetical order

You can use Arrays.sort() method. Here's the example,

import java.util.Arrays;

public class Test 
{
    public static void main(String[] args) 
    {
        String arrString[] = { "peter", "taylor", "brooke", "frederick", "cameron" };
        orderedGuests(arrString);
    }

    public static void orderedGuests(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }
}

Output

[brooke, cameron, frederick, peter, taylor]

How to have multiple CSS transitions on an element?

It's possible to make the multiple transitions set with different values for duration, delay and timing function. To split different transitions use ,

button{
  transition: background 1s ease-in-out 2s, width 2s linear;
  -webkit-transition: background 1s ease-in-out 2s, width 2s linear; /* Safari */
}

Reference: https://kolosek.com/css-transition/

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

Difference between pre-increment and post-increment in a loop?

One (++i) is preincrement, one (i++) is postincrement. The difference is in what value is immediately returned from the expression.

// Psuedocode
int i = 0;
print i++; // Prints 0
print i; // Prints 1
int j = 0;
print ++j; // Prints 1
print j; // Prints 1

Edit: Woops, entirely ignored the loop side of things. There's no actual difference in for loops when it's the 'step' portion (for(...; ...; )), but it can come into play in other cases.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

What exactly do you mean by "validation failure"? What are you validating? Are you referring to something like a syntax error (e.g. malformed XML)?

If that's the case, I'd say 400 Bad Request is probably the right thing, but without knowing what it is you're "validating", it's impossible to say.

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

By process (in the JSF specification it's called execute) you tell JSF to limit the processing to component that are specified every thing else is just ignored.

update indicates which element will be updated when the server respond back to you request.

@all : Every component is processed/rendered.

@this: The requesting component with the execute attribute is processed/rendered.

@form : The form that contains the requesting component is processed/rendered.

@parent: The parent that contains the requesting component is processed/rendered.

With Primefaces you can even use JQuery selectors, check out this blog: http://blog.primefaces.org/?p=1867

How to workaround 'FB is not defined'?

I had a similar issue and it turned out to be Adblocker Pro. Be sure to check that this or other blocking extensions have been disabled. I lost around 1hr 30 mins due to this. Feel like such a noob ;)

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

How to merge 2 JSON objects from 2 files using jq?

Here's a version that works recursively (using *) on an arbitrary number of objects:

echo '{"A": {"a": 1}}' '{"A": {"b": 2}}' '{"B": 3}' |\
  jq --slurp 'reduce .[] as $item ({}; . * $item)'

{
  "A": {
    "a": 1,
    "b": 2
  },
  "B": 3
}

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

In my case, creating canvas every time worked for me, even though it's not memory-friendly

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
imageBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
canvas = new Canvas(imageBitmap);
canvas.drawBitmap(bm, 0, 0, null);

How to iterate through a list of dictionaries in Jinja template?

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I got an error in Eclipse Mars version as "Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.

To resolve this issue, please do the following steps, "Right click on Project Choose Build path Choose Configure Build path Choose Libraries tab Select JRE System Library and click on Edit button Choose workspace default JRE and Finish

Problem will be resolved.

What USB driver should we use for the Nexus 5?

I am on Windows 8.1, and I tried everything from the other answers and nothing worked. Finally, I decided to try "Pick from a list of drivers" and found "LGE Mobile Sooner Single ADB Interface" under "ADB Interface". ADB.exe was finally able to find the Nexus 5 and sideload 4.4.1.

I hope this helps.

Javascript array sort and unique

I guess I'll post this answer for some variety. This technique for purging duplicates is something I picked up on for a project in Flash I'm currently working on about a month or so ago.

What you do is make an object and fill it with both a key and a value utilizing each array item. Since duplicate keys are discarded, duplicates are removed.

var nums = [1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9, 10];
var newNums = purgeArray(nums);

function purgeArray(ar)
{
    var obj = {};
    var temp = [];
    for(var i=0;i<ar.length;i++)
    {
        obj[ar[i]] = ar[i];
    }
    for (var item in obj)
    {
        temp.push(obj[item]);
    }
    return temp;
}

There's already 5 other answers, so I don't see a need to post a sorting function.

What is Ad Hoc Query?

Ad hoc query is type of computer definition. Which means this query is specially design to obtain any information when it is only needed. Predefined. refer this https://www.youtube.com/watch?v=0c8JEKmVXhU

How do I reflect over the members of dynamic object?

In the case of ExpandoObject, the ExpandoObject class actually implements IDictionary<string, object> for its properties, so the solution is as trivial as casting:

IDictionary<string, object> propertyValues = (IDictionary<string, object>)s;

Note that this will not work for general dynamic objects. In these cases you will need to drop down to the DLR via IDynamicMetaObjectProvider.

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

How do I close a tkinter window?

In idlelib.PyShell module, root variable of type Tk is defined to be global

At the end of PyShell.main() function it calls root.mainloop() function which is an infinite loop and it runs till the loop is interrupted by root.quit() function. Hence, root.quit() will only interrupt the execution of mainloop

In order to destroy all widgets pertaining to that idlelib window, root.destroy() needs to be called, which is the last line of idlelib.PyShell.main() function.

how to split the ng-repeat data with three columns using bootstrap

Another way is set width:33.33%; float:left to a wrapper div like this:

<div ng-repeat="right in rights" style="width: 33.33%;float: left;">
    <span style="width:60px;display:inline-block;text-align:right">{{$index}}</span>
    <input type="number" style="width:50px;display:inline-block" ">
</div>

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

You cant blame code all the time sometime may be your url is wrong , double check urls

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

How to print from Flask @app.route to python console

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

How to print the ld(linker) search path

I'm not sure that there is any option for simply printing the full effective search path.

But: the search path consists of directories specified by -L options on the command line, followed by directories added to the search path by SEARCH_DIR("...") directives in the linker script(s). So you can work it out if you can see both of those, which you can do as follows:

If you're invoking ld directly:

  • The -L options are whatever you've said they are.
  • To see the linker script, add the --verbose option. Look for the SEARCH_DIR("...") directives, usually near the top of the output. (Note that these are not necessarily the same for every invocation of ld -- the linker has a number of different built-in default linker scripts, and chooses between them based on various other linker options.)

If you're linking via gcc:

  • You can pass the -v option to gcc so that it shows you how it invokes the linker. In fact, it normally does not invoke ld directly, but indirectly via a tool called collect2 (which lives in one of its internal directories), which in turn invokes ld. That will show you what -L options are being used.
  • You can add -Wl,--verbose to the gcc options to make it pass --verbose through to the linker, to see the linker script as described above.

Having links relative to root?

<a href="/fruits/index.html">Back to Fruits List</a>

How to check a not-defined variable in JavaScript

An even easier and more shorthand version would be:

if (!x) {
   //Undefined
}

OR

if (typeof x !== "undefined") {
    //Do something since x is defined.
}

Call An Asynchronous Javascript Function Synchronously

You can force asynchronous JavaScript in NodeJS to be synchronous with sync-rpc.

It will definitely freeze your UI though, so I'm still a naysayer when it comes to whether what it's possible to take the shortcut you need to take. It's not possible to suspend the One And Only Thread in JavaScript, even if NodeJS lets you block it sometimes. No callbacks, events, anything asynchronous at all will be able to process until your promise resolves. So unless you the reader have an unavoidable situation like the OP (or, in my case, are writing a glorified shell script with no callbacks, events, etc.), DO NOT DO THIS!

But here's how you can do this:

./calling-file.js

var createClient = require('sync-rpc');
var mySynchronousCall = createClient(require.resolve('./my-asynchronous-call'), 'init data');

var param1 = 'test data'
var data = mySynchronousCall(param1);
console.log(data); // prints: received "test data" after "init data"

./my-asynchronous-call.js

function init(initData) {
  return function(param1) {
    // Return a promise here and the resulting rpc client will be synchronous
    return Promise.resolve('received "' + param1 + '" after "' + initData + '"');
  };
}
module.exports = init;

LIMITATIONS:

These are both a consequence of how sync-rpc is implemented, which is by abusing require('child_process').spawnSync:

  1. This will not work in the browser.
  2. The arguments to your function must be serializable. Your arguments will pass in and out of JSON.stringify, so functions and non-enumerable properties like prototype chains will be lost.

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

Change Schema Name Of Table In SQL

Create Schema :

IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe')) 
BEGIN
    EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END

ALTER Schema :

ALTER SCHEMA exe 
    TRANSFER dbo.Employees

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

What is the meaning of "this" in Java?

It refers to the current instance of a particular object, so you could write something like

public Object getMe() {
    return this;
}

A common use-case of this is to prevent shadowing. Take the following example:

public class Person {
    private final String name;

    public Person(String name) {
        // how would we initialize the field using parameter?
        // we can't do: name = name;
    }
}

In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.

public class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }
}

Bulk create model objects in django

Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:

SomeModel(Model):
    @classmethod
    def from_file(model, file_obj, headers, delimiter):
        model.objects.bulk_create([
            model(**dict(zip(headers, line.split(delimiter))))
            for line in file_obj],
            batch_size=None)

How to run .APK file on emulator

You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

adb -e install -r yourapp.apk

Once you've done that you should be able to run the app.

The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

Fill Combobox from database

string query = "SELECT column_name FROM table_name";      //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();                               
            
while (reader.Read())   //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}

Loop Through All Subfolders Using VBA

Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

How to create windows service from java jar?

With procrun you need to copy prunsrv to the application directory (download), and create an install.bat like this:

set PR_PATH=%CD%
SET PR_SERVICE_NAME=MyService
SET PR_JAR=MyService.jar
SET START_CLASS=org.my.Main
SET START_METHOD=main
SET STOP_CLASS=java.lang.System
SET STOP_METHOD=exit
rem ; separated values
SET STOP_PARAMS=0
rem ; separated values
SET JVM_OPTIONS=-Dapp.home=%PR_PATH%
prunsrv.exe //IS//%PR_SERVICE_NAME% --Install="%PR_PATH%\prunsrv.exe" --Jvm=auto --Startup=auto --StartMode=jvm --StartClass=%START_CLASS% --StartMethod=%START_METHOD% --StopMode=jvm --StopClass=%STOP_CLASS% --StopMethod=%STOP_METHOD% ++StopParams=%STOP_PARAMS% --Classpath="%PR_PATH%\%PR_JAR%" --DisplayName="%PR_SERVICE_NAME%" ++JvmOptions=%JVM_OPTIONS%

I presume to

  • run this from the same directory where the jar and prunsrv.exe is
  • the jar has its working MANIFEST.MF
  • and you have shutdown hooks registered into JVM (for example with context.registerShutdownHook() in Spring)...
  • not using relative paths for files outside the jar (for example log4j should be used with log4j.appender.X.File=${app.home}/logs/my.log or something alike)

Check the procrun manual and this tutorial for more information.

Add a string of text into an input field when user clicks a button

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/ ?

plot a circle with pyplot

#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np

def xy(r,phi):
  return r*np.cos(phi), r*np.sin(phi)

fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')  

phis=np.arange(0,6.28,0.01)
r =1.
ax.plot( *xy(r,phis), c='r',ls='-' )
plt.show()

Or, if you prefer, look at the paths, http://matplotlib.sourceforge.net/users/path_tutorial.html

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

The remote server returned an error: (403) Forbidden

We should access the website using the name given in the certificate.enter image description here

php - How do I fix this illegal offset type error

I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.

foreach($xml->children() as $newInstr){
        $iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
        $arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
    }

Return zero if no record is found

You can also try: (I tried this and it worked for me)

SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;

Check if a record exists in the database

Use try catch:

try
{
    SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);

    int UserExist = (int)check_User_Name.ExecuteScalar();
    // Update query
}
catch
{
    // Insert query
}

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

I agree with Mark. I set the output to text mode and then sp_HelpText 'sproc'. I have this binded to Crtl-F1 to make it easy.

Is there a way to remove unused imports and declarations from Angular 2+?

To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.

Failure during conversion to COFF: file invalid or corrupt

Do you have Visual Studio 2012 installed as well? If so, 2012 stomps your 2010 IDE, possibly because of compatibility issues with .NET 4.5 and .NET 4.0.

See http://social.msdn.microsoft.com/Forums/da-DK/vssetup/thread/d10adba0-e082-494a-bb16-2bfc039faa80

src absolute path problem

Use forward slashes. See explanation here

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

Compare two List<T> objects for equality, ignoring order

try this!!!

using following code you could compare one or many fields to generate a result list as per your need. result list will contain only modified item(s).

// veriables been used
List<T> diffList = new List<T>();
List<T> gotResultList = new List<T>();



// compare First field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1))).ToList();
// Generate result list
diffList.AddRange(gotResultList);

// compare Second field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2))).ToList();
// Generate result list
diffList.AddRange(gotResultList);


MessageBox.Show(diffList.Count.ToString);

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

enter the values as 0:mm:ss and format as [m]:ss

as this is now in the mins & seconds, simple arithmetic will allow you to calculate your statistics

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I also encountered this problem. I found after changing the table storage engine from MyISAM to Innodb, problem solved .

How to show changed file name only with git log?

If you need just file names like:

dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php

(which I use as a source for tar command) you will also need to filter out commit messages.

In order to do this I use following command:

git log --name-only --oneline | grep -v '.{7} '

Grep command excludes (-v param) every line which starts with seven symbols (which is the length of my git hash for git log command) followed by space. So it filters out every git hash message line and leave only lines with file names.

One useful improvement is to append uniq to remove duplicate lines so it will looks as follow:

git log --name-only --oneline | grep -v '.{7} ' | uniq

How to clear the cache of nginx?

If you want to clear the cache of specific files then you can use the proxy_cache_bypass directive. This is how you do it

location / {
    proxy_cache_bypass $cookie_nocache $arg_nocache;
    # ...
}

Now if you want bypass the cache you access the file by passing the nocache parameter

http://www.example.com/app.css?nocache=true

What is the difference between background and background-color

One thing I've noticed that I don't see in the documentation is using background: url("image.png")

short hand like above if the image is not found it sends a 302 code instead of being ignored like it is if you use

background-image: url("image.png") 

How do I get NuGet to install/update all the packages in the packages.config?

Open Package Manager Console

  • View -> Other Windows -> Package Manager Console

Reinstall all packages in ALL PROJECTS of the current solution:

Update-Package -Reinstall

Reinstall all packages in SPECIFIC PROJECT of the current solution (Thanks to unarity and ashes999):

Update-Package -ProjectName 'YourProjectNameGoesHere' -Reinstall

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Following applies to IIS 7

The error is trying to tell you that one of two things is not working properly:

  • There is no default page (e.g., index.html, default.aspx) for your site. This could mean that the Default Document "feature" is entirely disabled, or just misconfigured.
  • Directory browsing isn't enabled. That is, if you're not serving a default page for your site, maybe you intend to let users navigate the directory contents of your site via http (like a remote "windows explorer").

See the following link for instructions on how to diagnose and fix the above issues.

http://support.microsoft.com/kb/942062/en-us

If neither of these issues is the problem, another thing to check is to make sure that the application pool configured for your website (under IIS Manager, select your website, and click "Basic Settings" on the far right) is configured with the same .Net framework version (in IIS Manager, under "Application Pools") as the targetFramework configured in your web.config, e.g.:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime targetFramework="4.0" />
  </system.web>

I'm not sure why this would generate such a seemingly unrelated error message, but it did for me.

Laravel: getting a a single value from a MySQL query

Edit:

Sorry i forgot about pluck() as many have commented : Easiest way is :

return DB::table('users')->where('username', $username)->pluck('groupName');

Which will directly return the only the first result for the requested row as a string.

Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner

$result = DB::table('users')->select('groupName')->where('username', $username)->first();

The first() tells the queryBuilder to return only one row so no array, so you can do :

return $result->groupName;

Hope it helps

Cannot open new Jupyter Notebook [Permission Denied]

  • List item
  • List item

this problem of not able to open jupyter notebook is like Corona virus.I came across several complaints-including my own.I use windows 10.

Atlast after struggling for 3 days i came across this wonderful foolproof solution:-

1.The jupyter folder is created at path:- C:\Users\deviv_000\AppData\Roaming\jupyter your name will replace->deviv_000

2.Go to cmd and write : cd C:\Users\deviv_000\AppData\Roaming\jupyter this will take cmd to that folder.

3.Now create manually a file as untitled.ipynb in jupyter folder.

4.Come back to cmd and write: jupyter trust untitled.ipynb

5.After cmd performs this operation now write:-
jupyter notebook

SUCCESS!!- your notebook will appear in the next tab.I used chrome.

Regards

Get properties of a class

This TypeScript code

class A {
    private a1;
    public a2;
}

compiles to this JavaScript code

class A {
}

That's because properties in JavaScript start extisting only after they have some value. You have to assign the properties some value.

class A {
    private a1 = "";
    public a2 = "";
}

it compiles to

class A {
    constructor() {
        this.a1 = "";
        this.a2 = "";
    }
}

Still, you cannot get the properties from mere class (you can get only methods from prototype). You must create an instance. Then you get the properties by calling Object.getOwnPropertyNames().

let a = new A();
let array = return Object.getOwnPropertyNames(a);

array[0] === "a1";
array[1] === "a2";

Applied to your example

class Describer {
    static describe(instance): Array<string> {
        return Object.getOwnPropertyNames(instance);
    }
}

let a = new A();
let x = Describer.describe(a);

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Simple JavaScript login form validation

  1. The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this:

    <form name="loginform" onsubmit="validateForm()" method="post">

    Here are some useful links:

  2. For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.

    You can read more about the differences here.

UPDATE:

You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:

<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
    <label>User name</label>
    <input type="text" name="usr" placeholder="username"> 
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var un = document.loginform.usr.value;
        var pw = document.loginform.pword.value;
        var username = "username"; 
        var password = "password";
        if ((un == username) && (pw == password)) {
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
        }
  }
</script>

Replace all occurrences of a string in a data frame

I had the problem, I had to replace "Not Available" with NA and my solution goes like this

data <- sapply(data,function(x) {x <- gsub("Not Available",NA,x)})

How to make a div 100% height of the browser window

Just use the "vh" unit instead of "px", which means view-port height.

height: 100vh;

How can I add a string to the end of each line in Vim?

%s/\s*$/\*/g

this will do the trick, and ensure leading spaces are ignored.

How to get a table creation script in MySQL Workbench?

I came here looking for the answer to the same question. But I found a much better answer myself.

In the tables list, if you right-click on the table name there is a suite of CRUD script generation options in "Send to SQL Editor". You can select multiple tables and take the same approach too.

My version of MySQL Workbench: 5.2.37

Keep SSH session alive

We can keep our ssh connection alive by having following Global configurations

Add the following line to the /etc/ssh/ssh_config file:

ServerAliveInterval 60

What is the Difference Between Mercurial and Git?

Git is a platform, Mercurial is “just” an application. Git is a versioned filesystem platform that happens to ship with a DVCS app in the box, but as normal for platform apps, it is more complex and has rougher edges than focused apps do. But this also means git’s VCS is immensely flexible, and there is a huge depth of non-source-control things you can do with git.

That is the essence of the difference.

Git is best understood from the ground up – from the repository format up. Scott Chacon’s Git Talk is an excellent primer for this. If you try to use git without knowing what’s happening under the hood, you’ll end up confused at some point (unless you stick to only very basic functionality). This may sound stupid when all you want is a DVCS for your daily programming routine, but the genius of git is that the repository format is actually very simple and you can understand git’s entire operation quite easily.

For some more technicality-oriented comparisons, the best articles I have personally seen are Dustin Sallings’:

He has actually used both DVCSs extensively and understands them both well – and ended up preferring git.

Finding what methods a Python object has

I have done the following function (get_object_functions), which receives an object (object_) as its argument, and returns a list (functions) containing all of the methods (including static and class methods) defined in the object's class:

def get_object_functions(object_):
    functions = [attr_name
                 for attr_name in dir(object_)
                 if str(type(getattr(object_,
                                     attr_name))) in ("<class 'function'>",
                                                      "<class 'method'>")]
    return functions

Well, it just checks if the string representation of the type of a class' attribute equals "<class 'function'>" or "<class 'method'>" and then includes that attribute in the functions list if that's True.


Demo

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f'My name is {self.name}')

    @staticmethod
    def say_hi():
        print('hi')

    @classmethod
    def reproduce(cls, name):
        return cls(name, 0)


person = Person('Rafael', 27)
print(get_object_functions(person))

Output

['__init__', 'introduce', 'reproduce', 'say_hi']

For a cleaner version of the code: https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to copy and paste worksheets between Excel workbooks?

This code copies and pastes all sheets (not cell values) from one source workbook to a destination workbook:

Private Sub copypastesheets()

Dim wbSource, wbDestination As Object
Dim nbSheets As Integer

Set wbSource = Workbooks("your_source_workbook_name")
Set wbDestination = Workbooks("your_destination_workbook_name")
nbSheets = wbDestination.Sheets.Count - 1

For Each sheetItem In wbSource.Sheets

    nbSheets = nbSheets + 1
    sheetItem.Copy after:=wbDestination.Sheets(nbSheets)

Next sheetItem


End Sub

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

How to convert R Markdown to PDF?

Follow these simple steps :

1: In the Rmarkdown script run Knit(Ctrl+Shift+K) 2: Then after the html markdown is opened click Open in Browser(top left side) and the html is opened in your web browser 3: Then use Ctrl+P and save as PDF .

Winforms issue - Error creating window handle

I think it's normally related to the computer running out of memory so it's not able to create any more window handles. Normally windows starts to show some strange behavior at this point as well.

Why does overflow:hidden not work in a <td>?

I've just had a similar problem, and had to use the <div> inside the <td> at first (John MacIntyre's solution didn't work for me for various reasons).

Note though that <td><div>...</div></td> isn't valid placement for a div so instead I'm using a <span> with display:block; set. It validates fine now and works.

GROUP BY without aggregate function

That's how GROUP BY works. It takes several rows and turns them into one row. Because of this, it has to know what to do with all the combined rows where there have different values for some columns (fields). This is why you have two options for every field you want to SELECT : Either include it in the GROUP BY clause, or use it in an aggregate function so the system knows how you want to combine the field.

For example, let's say you have this table:

Name | OrderNumber
------------------
John | 1
John | 2

If you say GROUP BY Name, how will it know which OrderNumber to show in the result? So you either include OrderNumber in group by, which will result in these two rows. Or, you use an aggregate function to show how to handle the OrderNumbers. For example, MAX(OrderNumber), which means the result is John | 2 or SUM(OrderNumber) which means the result is John | 3.

C++ static virtual members?

Like others have said, there are 2 important pieces of information:

  1. there is no this pointer when making a static function call and
  2. the this pointer points to the structure where the virtual table, or thunk, are used to look up which runtime method to call.

A static function is determined at compile time.

I showed this code example in C++ static members in class; it shows that you can call a static method given a null pointer:

struct Foo
{
    static int boo() { return 2; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo* pFoo = NULL;
    int b = pFoo->boo(); // b will now have the value 2
    return 0;
}

How to sort a list of strings?

Basic answer:

mylist = ["b", "C", "A"]
mylist.sort()

This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function:

for x in sorted(mylist):
    print x

However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element).

So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools):

sorted(mylist, key=cmp_to_key(locale.strcoll))

And finally, if you need, you can specify a custom locale for sorting:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
  key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']

Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:

# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)

How do you specify a byte literal in Java?

You have to cast, I'm afraid:

f((byte)0);

I believe that will perform the appropriate conversion at compile-time instead of execution time, so it's not actually going to cause performance penalties. It's just inconvenient :(

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

How to normalize a histogram in MATLAB?

My answer to this is the same as in an answer to your earlier question. For a probability density function, the integral over the entire space is 1. Dividing by the sum will not give you the correct density. To get the right density, you must divide by the area. To illustrate my point, try the following example.

[f, x] = hist(randn(10000, 1), 50); % Create histogram from a normal distribution.
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2); % pdf of the normal distribution

% METHOD 1: DIVIDE BY SUM
figure(1)
bar(x, f / sum(f)); hold on
plot(x, g, 'r'); hold off

% METHOD 2: DIVIDE BY AREA
figure(2)
bar(x, f / trapz(x, f)); hold on
plot(x, g, 'r'); hold off

You can see for yourself which method agrees with the correct answer (red curve).

enter image description here

Another method (more straightforward than method 2) to normalize the histogram is to divide by sum(f * dx) which expresses the integral of the probability density function, i.e.

% METHOD 3: DIVIDE BY AREA USING sum()
figure(3)
dx = diff(x(1:2))
bar(x, f / sum(f * dx)); hold on
plot(x, g, 'r'); hold off

Why use def main()?

Without the main sentinel, the code would be executed even if the script were imported as a module.

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

I was going into the same problem so I created a Mixin that seems to work for my use cases.

class ReadOnlyFieldsMixin(object):
    readonly_fields =()

    def __init__(self, *args, **kwargs):
        super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
        for field in (field for name, field in self.fields.iteritems() if name in self.readonly_fields):
            field.widget.attrs['disabled'] = 'true'
            field.required = False

    def clean(self):
        cleaned_data = super(ReadOnlyFieldsMixin,self).clean()
        for field in self.readonly_fields:
           cleaned_data[field] = getattr(self.instance, field)

        return cleaned_data

Usage, just define which ones must be read only:

class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):
    readonly_fields = ('field1', 'field2', 'fieldx')

Count indexes using "for" in Python

If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate function. For example

l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
   print "index", i, "is", fruit

How to asynchronously call a method in Java

i don't like the idea of using Reflection for that.
Not only dangerous for missing it in some refactoring, but it can also be denied by SecurityManager.

FutureTask is a good option as the other options from the java.util.concurrent package.
My favorite for simple tasks:

    Executors.newSingleThreadExecutor().submit(task);

little bit shorter than creating a Thread (task is a Callable or a Runnable)

error MSB6006: "cmd.exe" exited with code 1

Simple and better solution : %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln I make a bat file like this %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe D:\GESTION-SOMECOPA\GestionCommercial\GestionCommercial.sln pause

Then I can see all errors and correct them. Because when you change the folder name (without spaces as seen above) you will have another problems. Visual Studio 2015 works fine after this.

Can I use Objective-C blocks as properties?

For posterity / completeness's sake… Here are two FULL examples of how to implement this ridiculously versatile "way of doing things". @Robert's answer is blissfully concise and correct, but here I want to also show ways to actually "define" the blocks.

@interface       ReusableClass : NSObject
@property (nonatomic,copy) CALayer*(^layerFromArray)(NSArray*);
@end

@implementation  ResusableClass
static  NSString const * privateScope = @"Touch my monkey.";

- (CALayer*(^)(NSArray*)) layerFromArray { 
     return ^CALayer*(NSArray* array){
        CALayer *returnLayer = CALayer.layer
        for (id thing in array) {
            [returnLayer doSomethingCrazy];
            [returnLayer setValue:privateScope
                         forKey:@"anticsAndShenanigans"];
        }
        return list;
    };
}
@end

Silly? Yes. Useful? Hells yeah. Here is a different, "more atomic" way of setting the property.. and a class that is ridiculously useful…

@interface      CALayoutDelegator : NSObject
@property (nonatomic,strong) void(^layoutBlock)(CALayer*);
@end

@implementation CALayoutDelegator
- (id) init { 
   return self = super.init ? 
         [self setLayoutBlock: ^(CALayer*layer){
          for (CALayer* sub in layer.sublayers)
            [sub someDefaultLayoutRoutine];
         }], self : nil;
}
- (void) layoutSublayersOfLayer:(CALayer*)layer {
   self.layoutBlock ? self.layoutBlock(layer) : nil;
}   
@end

This illustrates setting the block property via the accessor (albeit inside init, a debatably dicey practice..) vs the first example's "nonatomic" "getter" mechanism. In either case… the "hardcoded" implementations can always be overwritten, per instance.. a lá..

CALayoutDelegator *littleHelper = CALayoutDelegator.new;
littleHelper.layoutBlock = ^(CALayer*layer){
  [layer.sublayers do:^(id sub){ [sub somethingElseEntirely]; }];
};
someLayer.layoutManager = littleHelper;

Also.. if you want to add a block property in a category... say you want to use a Block instead of some old-school target / action "action"... You can just use associated values to, well.. associate the blocks.

typedef    void(^NSControlActionBlock)(NSControl*); 
@interface       NSControl            (ActionBlocks)
@property (copy) NSControlActionBlock  actionBlock;    @end
@implementation  NSControl            (ActionBlocks)

- (NSControlActionBlock) actionBlock { 
    // use the "getter" method's selector to store/retrieve the block!
    return  objc_getAssociatedObject(self, _cmd); 
} 
- (void) setActionBlock:(NSControlActionBlock)ab {

    objc_setAssociatedObject( // save (copy) the block associatively, as categories can't synthesize Ivars.
    self, @selector(actionBlock),ab ,OBJC_ASSOCIATION_COPY);
    self.target = self;                  // set self as target (where you call the block)
    self.action = @selector(doItYourself); // this is where it's called.
}
- (void) doItYourself {

    if (self.actionBlock && self.target == self) self.actionBlock(self);
}
@end

Now, when you make a button, you don't have to set up some IBAction drama.. Just associate the work to be done at creation...

_button.actionBlock = ^(NSControl*thisButton){ 

     [doc open]; [thisButton setEnabled:NO]; 
};

This pattern can be applied OVER and OVER to Cocoa API's. Use properties to bring the relevant parts of your code closer together, eliminate convoluted delegation paradigms, and leverage the power of objects beyond that of just acting as dumb "containers".

Cannot ignore .idea/workspace.xml - keeps popping up

Since in my case I was performing a first commit of a project, simply deleting .git and .idea folders and then reinitializing git using git init helped to solve a problem. Now I don't have .idea at all.

Responsive design with media query : screen size?

The screen widths Bootstrap v3.x uses are as follows:

  • Extra small devices Phones (<768px) / .col-xs-
  • Small devices Tablets (=768px) / .col-sm-
  • Medium devices Desktops (=992px) / .col-md-
  • Large devices Desktops (=1200px) / .col-lg-

So, these are good to use and work well in practice.

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Best way to format if statement with multiple conditions

The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.

I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".

If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line

Eg.

if user.hasPermission(Admin()) {
   if (x >= 0) && (x < 100) {
      // do something
   }
}

What does PermGen actually stand for?

Permgen stands for Permanent Generation. It is one of the JVM memory areas. It's part of Heap with fixed size by using a flag called MaxPermSize.

Why the name "PermGen" ?

This permgen was named in early days of Java. Permgen mains keeps all the meta data of loaded classes. But the problem is that once a class is loaded it'll remain in the JVM till JVM shutdown. So name permgen is opt for that. But later, dynamic loading of classes came into picture but name was not changed. But with Java 8, they have addressed that issue as well. Now permagen was renamed as MetaSpace with dynamic memory size.

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

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.

This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How to make CREATE OR REPLACE VIEW work in SQL Server?

Edit: Although this question has been marked as a duplicate, it has still been getting attention. The answer provided by @JaKXz is correct and should be the accepted answer.


You'll need to check for the existence of the view. Then do a CREATE VIEW or ALTER VIEW depending on the result.

IF OBJECT_ID('dbo.data_VVVV') IS NULL
BEGIN
    CREATE VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
    ALTER VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
BEGIN
END

How do I set browser width and height in Selenium WebDriver?

It's easy. Here is the full code.

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("Your URL")
driver.set_window_size(480, 320)

Make sure chrome driver is in your system path.

Django - iterate number in for loop of a template

Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}

How to fix "could not find a base address that matches schema http"... in WCF

If it is hosted in IIS, there is no need to specify a base address, it will be the address of the virtual directory.

Plot 3D data in R

Not sure why the code above did not work for the library rgl, but the following link has a great example with the same library. Run the code in R and you will obtain a beautiful 3d plot that you can turn around in all angles.

http://statisticsr.blogspot.de/2008/10/some-r-functions.html

########################################################################
## another example of 3d plot from my personal reserach, use rgl library
########################################################################
# 3D visualization device system

library(rgl);
data(volcano)
dim(volcano)

peak.height <- volcano;
ppm.index <- (1:nrow(volcano));
sample.index <- (1:ncol(volcano));

zlim <- range(peak.height)
zlen <- zlim[2] - zlim[1] + 1
colorlut <- terrain.colors(zlen) # height color lookup table
col <- colorlut[(peak.height-zlim[1]+1)] # assign colors to heights for each point
open3d()

ppm.index1 <- ppm.index*zlim[2]/max(ppm.index);
sample.index1 <- sample.index*zlim[2]/max(sample.index)

title.name <- paste("plot3d ", "volcano", sep = "");
surface3d(ppm.index1, sample.index1, peak.height, color=col, back="lines", main = title.name);
grid3d(c("x", "y+", "z"), n =20)

sample.name <- paste("col.", 1:ncol(volcano), sep="");
sample.label <- as.integer(seq(1, length(sample.name), length = 5));

axis3d('y+',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3);
axis3d('y',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3)
axis3d('z',pos=c(0, 0, NA))

ppm.label <- as.integer(seq(1, length(ppm.index), length = 10));
axes3d('x', at=c(ppm.index1[ppm.label], 0, 0), abs(round(ppm.index[ppm.label], 2)), cex = 0.3);

title3d(main = title.name, sub = "test", xlab = "ppm", ylab = "samples", zlab = "peak")
rgl.bringtotop();

How to get the first and last date of the current year?

print Cast('1/1/' + cast(datepart(yyyy, getdate()) as nvarchar(4)) as date)

Get week number (in the year) from a date PHP

This get today date then tell the week number for the week

<?php
 $date=date("W");
 echo $date." Week Number";
 ?>

Begin, Rescue and Ensure in Ruby?

Yes, ensure ensures that the code is always evaluated. That's why it's called ensure. So, it is equivalent to Java's and C#'s finally.

The general flow of begin/rescue/else/ensure/end looks like this:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
rescue SomeOtherException => some_other_variable
  # code that deals with some other exception
else
  # code that runs only if *no* exception was raised
ensure
  # ensure that this code always runs, no matter what
  # does not change the final value of the block
end

You can leave out rescue, ensure or else. You can also leave out the variables in which case you won't be able to inspect the exception in your exception handling code. (Well, you can always use the global exception variable to access the last exception that was raised, but that's a little bit hacky.) And you can leave out the exception class, in which case all exceptions that inherit from StandardError will be caught. (Please note that this does not mean that all exceptions are caught, because there are exceptions which are instances of Exception but not StandardError. Mostly very severe exceptions that compromise the integrity of the program such as SystemStackError, NoMemoryError, SecurityError, NotImplementedError, LoadError, SyntaxError, ScriptError, Interrupt, SignalException or SystemExit.)

Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, so instead of writing

def foo
  begin
    # ...
  rescue
    # ...
  end
end

you write just

def foo
  # ...
rescue
  # ...
end

or

def foo
  # ...
ensure
  # ...
end

The same applies to class definitions and module definitions.

However, in the specific case you are asking about, there is actually a much better idiom. In general, when you work with some resource which you need to clean up at the end, you do that by passing a block to a method which does all the cleanup for you. It's similar to a using block in C#, except that Ruby is actually powerful enough that you don't have to wait for the high priests of Microsoft to come down from the mountain and graciously change their compiler for you. In Ruby, you can just implement it yourself:

# This is what you want to do:
File.open('myFile.txt', 'w') do |file|
  file.puts content
end

# And this is how you might implement it:
def File.open(filename, mode='r', perm=nil, opt=nil)
  yield filehandle = new(filename, mode, perm, opt)
ensure
  filehandle&.close
end

And what do you know: this is already available in the core library as File.open. But it is a general pattern that you can use in your own code as well, for implementing any kind of resource cleanup (à la using in C#) or transactions or whatever else you might think of.

The only case where this doesn't work, if acquiring and releasing the resource are distributed over different parts of the program. But if it is localized, as in your example, then you can easily use these resource blocks.


BTW: in modern C#, using is actually superfluous, because you can implement Ruby-style resource blocks yourself:

class File
{
    static T open<T>(string filename, string mode, Func<File, T> block)
    {
        var handle = new File(filename, mode);
        try
        {
            return block(handle);
        }
        finally
        {
            handle.Dispose();
        }
    }
}

// Usage:

File.open("myFile.txt", "w", (file) =>
{
    file.WriteLine(contents);
});

@viewChild not working - cannot read property nativeElement of undefined

@ViewChild('keywords-input') keywordsInput; doesn't match id="keywords-input"

id="keywords-input"

should be instead a template variable:

#keywordsInput

Note that camel case should be used, since - is not allowed in template reference names.

@ViewChild() supports names of template variables as string:

@ViewChild('keywordsInput') keywordsInput;

or component or directive types:

@ViewChild(MyKeywordsInputComponent) keywordsInput;

See also https://stackoverflow.com/a/35209681/217408

Hint:
keywordsInput is not set before ngAfterViewInit() is called

Editor does not contain a main type

Just make sure that the folder you work in is added to the built path:

right-click your folder --> build Path --> Use as source Folder

and it should now find main therein.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

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

I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.

Here's my code behind a command button


Private Sub cmdSave()
    Dim sFileName As String
    Dim WB As Workbook

    Application.DisplayAlerts = False

    sFileName = "MyFileName.csv"
    'Copy the contents of required sheet ready to paste into the new CSV
    Sheets(1).Range("A1:T85").Copy 'Define your own range

    'Open a new XLS workbook, save it as the file name
    Set WB = Workbooks.Add
    With WB
        .Title = "MyTitle"
        .Subject = "MySubject"
        .Sheets(1).Select
        ActiveSheet.Paste
        .SaveAs "MyDirectory\" & sFileName, xlCSV
        .Close
    End With

    Application.DisplayAlerts = True
End Sub

This works for me :-)

Removing "http://" from a string

Something like this ought to do:

$url = preg_replace("|^.+?://|", "", $url); 

Removes everything up to and including the ://

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Months after this question, I've levelup my Docker skills. I should use Docker container name instead.

That use dokerized-nginx as bridge to expose ip+port of the container.

Within WEB configuration, I now use mysql://USERNAME:PASSWORD@docker_container_name/DB_NAME to access to Mysql socket through docker (also works with docker-compose, use compose-name instead of container one)

Expanding a parent <div> to the height of its children

Does this do what you want?

.childRightCol, .childLeftCol
{
    display: inline-block;
    width: 50%;
    margin: 0;
    padding: 0;
    vertical-align: top;
}

How can I recover a lost commit in Git?

Try this, This will show all commits recorded in git for a period of time

git reflog

Find the commit you want with

git log HEAD@{3}

or

git log -p HEAD@{3}    

Then check it out if it's the right one:

git checkout HEAD@{3}

This will create a detached head for that commit. Add and commit any changes if needed

git status 
git add
git commit -m "temp_work" 

Now if want to restore commit back to a branch lets say master you will need to name this branch switch to master then merge to master.

git branch temp
git checkout master
git merge temp

Here's also a link specifically for reflog on a Git tutorial site: Atlassian Git Tutorial

Mismatch Detected for 'RuntimeLibrary'

I had this problem along with mismatch in ITERATOR_DEBUG_LEVEL. As a sunday-evening problem after all seemed ok and good to go, I was put out for some time. Working in de VS2017 IDE (Solution Explorer) I had recently added/copied a sourcefile reference to my project (ctrl-drag) from another project. Looking into properties->C/C++/Preprocessor - at source file level, not project level - I noticed that in a Release configuration _DEBUG was specified instead of NDEBUG for this source file. Which was all the change needed to get rid of the problem.

Set color of TextView span in Android

  1. create textview in ur layout
  2. paste this code in ur MainActivity

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    

Download JSON object as a file from browser

React: add this where you want in your render method.

• Object in state:

<a
  className="pull-right btn btn-primary"
  style={{ margin: 10 }}
  href={`data:text/json;charset=utf-8,${encodeURIComponent(
  JSON.stringify(this.state.objectToDownload)
  )}`}
  download="data.json"
>
  DOWNLOAD DATA AS JSON
</a>

• Object in props:

<a
  className="pull-right btn btn-primary"
  style={{ margin: 10 }}
  href={`data:text/json;charset=utf-8,${encodeURIComponent(
  JSON.stringify(this.props.objectToDownload)
  )}`}
  download="data.json"
>
  DOWNLOAD DATA AS JSON
</a>

className and style are optional, modify the style according to your needs.

Biggest advantage to using ASP.Net MVC vs web forms

I can see the only two advantages for smaller sites being: 6) RESTful urls that enables SEO. 7) No ViewState and PostBack events (and greater performance in general)

Testing for small sites is not an issue, neither are the design advantages when a site is coded properly anyway, MVC in many ways obfuscates and makes changes harder to make. I'm still deciding whether these advantages are worth it.

I can clearly see the advantage of MVC in larger multi-developer sites.

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

Spring Boot War deployed to Tomcat

public class Application extends SpringBootServletInitializer {}

just extends the SpringBootServletInitializer. It will works in your AWS/tomcat

How to check type of variable in Java?

I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.

public class TypeTester <T extends Number>{

<T extends Object> String tester(T ToTest){

    if (ToTest instanceof Integer) return ("Integer");
    else if(ToTest instanceof Double) return ("Double");
    else if(ToTest instanceof Float) return ("Float");
    else if(ToTest instanceof String) return ("String");
    else if(ToTest.getClass().isArray()) return ("Array");
    else return ("Unsure");
}
}

I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.

public class Generics {
public static void main(String[] args) {
    int [] myArray = new int [10];

    TypeTester<Integer> callFunction = new TypeTester<Integer>();
    System.out.println(callFunction.tester(myArray));
}
}

You can swap out the myArray in the final line for say 10.2F to test Float etc

Why Anaconda does not recognize conda command?

Same problem with Anaconda running on Ubuntu 15.10. I closed the terminal and opened a new window and it worked fine.

Installing mcrypt extension for PHP on OSX Mountain Lion

I'd create a shell script to install mcrypt module for PHP 5.3 without homebrew.

The scripts install php autoconf if needed and compile module for your php version.

The link is here: https://gist.github.com/lucasgameiro/8730619

Thanks

remove script tag from HTML content

use the str_replace function to replace them with empty space or something

$query = '<script>console.log("I should be banned")</script>';

$badChar = array('<script>','</script>');
$query = str_replace($badChar, '', $query);

echo $query; 
//this echoes console.log("I should be banned")

?>

How to check for valid email address?

I found an excellent (and tested) way to check for valid email address. I paste my code here:

# here i import the module that implements regular expressions
import re
# here is my function to check for valid email address
def test_email(your_pattern):
pattern = re.compile(your_pattern)
# here is an example list of email to check it at the end
emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"]
for email in emails:
    if not re.match(pattern, email):
        print "You failed to match %s" % (email)
    elif not your_pattern:
        print "Forgot to enter a pattern!"
    else:
        print "Pass"
# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"   
# here i test my function passing my pattern
test_email(pattern)

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

Decimal separator comma (',') with numberDecimal inputType in EditText

I decided to change comma to dot only while editing. Here is my tricky and relative simple workaround:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText editText = (EditText) v; 
            String text = editText.getText().toString();
            if (hasFocus) {
                editText.setText(text.replace(",", "."));
            } else {
                if (!text.isEmpty()) {
                    Double doubleValue = Double.valueOf(text.replace(",", "."));
                    editText.setText(someDecimalFormatter.format(doubleValue));
                }
            }
        }
    });

someDecimalFormatter will use comma or dot depends on Locale

Send parameter to Bootstrap modal window?

First of all you should fix modal HTML structure. Now it's not correct, you don't need class .hide:

<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body edit-content">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Then links should point to this modal via data-target attribute:

<a href="#myModal" data-toggle="modal" id="1" data-target="#edit-modal">Edit 1</a>

Finally Js part becomes very simple:

    $('#edit-modal').on('show.bs.modal', function(e) {

        var $modal = $(this),
            esseyId = e.relatedTarget.id;

        $.ajax({
            cache: false,
            type: 'POST',
            url: 'backend.php',
            data: 'EID=' + essayId,
            success: function(data) {
                $modal.find('.edit-content').html(data);
            }
        });
    })

Demo: http://plnkr.co/edit/4XnLTZ557qMegqRmWVwU?p=preview

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Just to update all, after some deliberations, I have decided to use Async Http Client instead to solve my earlier problem. The library allows a cleaner approach (to me) to manipulate HTTP responses especially in cases where JSON objects are returned in all scenarios/HTTP statuses.

protected void getLogin() {

    EditText username = (EditText) findViewById(R.id.username); 
    EditText password = (EditText) findViewById(R.id.password); 

    RequestParams params = new RequestParams();
    params.put("username", username.getText().toString());
    params.put("password", password.getText().toString());

    RestClient.post(getHost() + "api/v1/auth/login", params,
            new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                JSONObject response) {

            try {

                //process JSONObject obj 
                Log.w("myapp","success status code..." + statusCode);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                Throwable throwable, JSONObject errorResponse) {
            Log.w("myapp", "failure status code..." + statusCode);


            try {
                //process JSONObject obj
                Log.w("myapp", "error ..."  + errorResponse.getString("message").toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

Add onclick event to newly added element in JavaScript

.onclick should be set to a function instead of a string. Try

elemm.onclick = function() { alert('blah'); };

instead.

Listing all permutations of a string/integer

class Program
{
    public static void Main(string[] args)
    {
        Permutation("abc");
    }

    static void Permutation(string rest, string prefix = "")
    {
        if (string.IsNullOrEmpty(rest)) Console.WriteLine(prefix);

        // Each letter has a chance to be permutated
        for (int i = 0; i < rest.Length; i++)
        {                
            Permutation(rest.Remove(i, 1), prefix + rest[i]);
        }
    }
}

How can I install a CPAN module into a local directory?

Other answers already on Stackoverflow:

From perlfaq8:


How do I keep my own module/library directory?

When you build modules, tell Perl where to install the modules.

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:

% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit

For Build.PL-based distributions, use the --install_base option:

perl Build.PL --install_base /mydir/perl

You can configure CPAN.pm to automatically use this option too:

% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit

SELECTING with multiple WHERE conditions on same column

Change AND to OR. Simple mistake. Think of it like plain English, I want to select anything with that equals this or that.

How to create a listbox in HTML without allowing multiple selection?

Just use the size attribute:

<select name="sometext" size="5">
  <option>text1</option>
  <option>text2</option>
  <option>text3</option>
  <option>text4</option>
  <option>text5</option>
</select>

To clarify, adding the size attribute did not remove the multiple selection.

The single selection works because you removed the multiple="multiple" attribute.

Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here

run program in Python shell

It depends on what is in test.py. The following is an appropriate structure:

# suppose this is your 'test.py' file
def main():
 """This function runs the core of your program"""
 print("running main")

if __name__ == "__main__":
 # if you call this script from the command line (the shell) it will
 # run the 'main' function
 main()

If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):

$ python test.py
$ # it will print "running main"

If you want to run it from the Python shell, then you simply do the following:

>>> import test
>>> test.main() # this calls the main part of your program

There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.

python: urllib2 how to send cookie with urlopen request

You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookies section of quickstart guide:

To send your own cookies to the server, you can use the cookies parameter:

>>> cookies = dict(cookies_are='working')

>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Switch android x86 screen resolution

Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.

VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"

With the following appended to android kernel cmd:

UVESA_MODE=440x680 DPI=120

JavaScript unit test tools for TDD

You have "runs on actual browser" as a pro, but in my experience that is a con because it is slow. But what makes it valuable is the lack of sufficient JS emulation from the non-browser alternatives. It could be that if your JS is complex enough that only an in browser test will suffice, but there are a couple more options to consider:

HtmlUnit: "It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use." If its emulation is good enough for your use then it will be much faster than driving a browser.

But maybe HtmlUnit has good enough JS support but you don't like Java? Then maybe:

Celerity: Watir API running on JRuby backed by HtmlUnit.

or similarly

Schnell: another JRuby wrapper of HtmlUnit.

Of course if HtmlUnit isn't good enough and you have to drive a browser then you might consider Watir to drive your JS.

Finding the layers and layer sizes for each Docker image

  1. https://hub.docker.com/search?q=* shows all the images in the entire Docker hub, it's not possible to get this via the search command as it doesnt accept wildcards.

  2. As of v1.10 you can find all the layers in an image by pulling it and using these commands:

    docker pull ubuntu
    ID=$(sudo docker inspect -f {{.Id}} ubuntu)
    jq .rootfs.diff_ids /var/lib/docker/image/aufs/imagedb/content/$(echo $ID|tr ':' '/')
    

3) The size can be found in /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/size although LAYERID != the diff_ids found with the previous command. For this you need to look at /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/diff and compare with the previous command output to properly match the correct diff_id and size.

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Application Installation Failed in Android Studio

For those who uses Xiaomi phones, follow these steps:

  1. Settings-> Additional Settings-> Developer options

  2. Turn off MIUI Optimization and reboot your phone

  3. Last Disable verify app over USB

Your device will respond properly.

Also enable install via USB

How to run 'sudo' command in windows

All the answers explain how to elevate your command in a new console host.

What amused me was that none of those tools behave like *nix sudo, allowing to execute the command inside the current console.

So, I wrote: gsudo

Source Code https://github.com/gerardog/gsudo

Installation

Via scoop

  • Install scoop if you don't already have it. Then:
scoop install gsudo

Or via Chocolatey

choco install gsudo

Manual instalation:

Demo

gsudo demo

const vs constexpr on variables

constexpr indicates a value that's constant and known during compilation.
const indicates a value that's only constant; it's not compulsory to know during compilation.

int sz;
constexpr auto arraySize1 = sz;    // error! sz's value unknown at compilation
std::array<int, sz> data1;         // error! same problem

constexpr auto arraySize2 = 10;    // fine, 10 is a compile-time constant
std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr

Note that const doesn’t offer the same guarantee as constexpr, because const objects need not be initialized with values known during compilation.

int sz;
const auto arraySize = sz;       // fine, arraySize is const copy of sz
std::array<int, arraySize> data; // error! arraySize's value unknown at compilation

All constexpr objects are const, but not all const objects are constexpr.

If you want compilers to guarantee that a variable has a value that can be used in contexts requiring compile-time constants, the tool to reach for is constexpr, not const.

How to locate the Path of the current project directory in Java (IDE)?

This is a code snippet to retrieve the path of the current running web application project in java.

public String getPath() throws UnsupportedEncodingException {

    String path = this.getClass().getClassLoader().getResource("").getPath();
    String fullPath = URLDecoder.decode(path, "UTF-8");
    String pathArr[] = fullPath.split("/WEB-INF/classes/");
    System.out.println(fullPath);
    System.out.println(pathArr[0]);
    fullPath = pathArr[0];

    return fullPath;

}

Source: https://dzone.com/articles/get-current-web-application

How can I make a program wait for a variable change in javascript?

What worked for me (I looked all over the place and ended up using someone's jsfiddler / very slightly modifying it - worked nicely) was to set that variable to an object with a getter and setter, and the setter triggers the function that is waiting for variable change.

var myVariableImWaitingOn = function (methodNameToTriggerWhenChanged){
    triggerVar = this;
    triggerVar.val = '';
    triggerVar.onChange = methodNameToTriggerWhenChanged;
    this.SetValue(value){
        if (value != 'undefined' && value != ''){
            triggerVar.val = value; //modify this according to what you're passing in -
            //like a loop if an array that's only available for a short time, etc
            triggerVar.onChange(); //could also pass the val to the waiting function here
            //or the waiting function can just call myVariableImWaitingOn.GetValue()
        }
    };
    this.GetValue(){
        return triggerVar.val();
    };
 };

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

This question helped me a lot but didn't get me all the way in understanding what needs to happen. This blog post did an amazing job of walking me through it.

Here are the important bits all in one place:

  • As pointed out above, you MUST sign your 1.1 API requests. If you are doing something like getting public statuses, you'll want an application key rather than a user key. The full link to the page you want is: https://dev.twitter.com/apps
  • You must hash ALL the parameters, both the oauth ones AND the get parameters (or POST parameters) together.
  • You must SORT the parameters before reducing them to the url encoded form that gets hashed.
  • You must encode some things multiple times - for example, you create a query string from the parameters' url-encoded values, and then you url encode THAT and concatenate with the method type and the url.

I sympathize with all the headaches, so here's some code to wrap it all up:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitterapi',
    'count' => '2'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);

Should I learn C before learning C++?

I love this question - it's like asking "what should I learn first, snowboarding or skiing"? I think it depends if you want to snowboard or to ski. If you want to do both, you have to learn both.

In both sports, you slide down a hill on snow using devices that are sufficiently similar to provoke this question. However, they are also sufficiently different so that learning one does not help you much with the other. Same thing with C and C++. While they appear to be languages sufficiently similar in syntax, the mind set that you need for writing OO code vs procedural code is sufficiently different so that you pretty much have to start from the beginning, whatever language you learn second.

Delete column from SQLite table

Just in case if it could help someone like me.

Based on the Official website and the Accepted answer, I made a code using C# that uses System.Data.SQLite NuGet package.

This code also preserves the Primary key and Foreign key.

CODE in C#:

void RemoveColumnFromSqlite (string tableName, string columnToRemove) {
 try {
    var mSqliteDbConnection = new SQLiteConnection ("Data Source=db_folder\\MySqliteBasedApp.db;Version=3;Page Size=1024;");
    mSqliteDbConnection.Open ();             
    // Reads all columns definitions from table
    List<string> columnDefinition = new List<string> ();
    var mSql = $"SELECT type, sql FROM sqlite_master WHERE tbl_name='{tableName}'";
    var mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    string sqlScript = "";
    using (mSqliteReader = mSqliteCommand.ExecuteReader ()) {
       while (mSqliteReader.Read ()) {
          sqlScript = mSqliteReader["sql"].ToString ();
          break;
       }
    }
    if (!string.IsNullOrEmpty (sqlScript)) {
       // Gets string within first '(' and last ')' characters
       int firstIndex = sqlScript.IndexOf ("(");
       int lastIndex = sqlScript.LastIndexOf (")");
       if (firstIndex >= 0 && lastIndex <= sqlScript.Length - 1) {
          sqlScript = sqlScript.Substring (firstIndex, lastIndex - firstIndex + 1);
       }
       string[] scriptParts = sqlScript.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
       foreach (string s in scriptParts) {
          if (!s.Contains (columnToRemove)) {
             columnDefinition.Add (s);
          }
       }
    }
    string columnDefinitionString = string.Join (",", columnDefinition);
    // Reads all columns from table
    List<string> columns = new List<string> ();
    mSql = $"PRAGMA table_info({tableName})";
    mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    using (mSqliteReader = mSqliteCommand.ExecuteReader ()) {
       while (mSqliteReader.Read ()) columns.Add (mSqliteReader["name"].ToString ());
    }
    columns.Remove (columnToRemove);
    string columnString = string.Join (",", columns);
    mSql = "PRAGMA foreign_keys=OFF";
    mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    int n = mSqliteCommand.ExecuteNonQuery ();
    // Removes a column from the table
    using (SQLiteTransaction tr = mSqliteDbConnection.BeginTransaction ()) {
       using (SQLiteCommand cmd = mSqliteDbConnection.CreateCommand ()) {
          cmd.Transaction = tr;
          string query = $"CREATE TEMPORARY TABLE {tableName}_backup {columnDefinitionString}";
          cmd.CommandText = query;
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"INSERT INTO {tableName}_backup SELECT {columnString} FROM {tableName}";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"DROP TABLE {tableName}";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"CREATE TABLE {tableName} {columnDefinitionString}";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"INSERT INTO {tableName} SELECT {columnString} FROM {tableName}_backup;";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"DROP TABLE {tableName}_backup";
          cmd.ExecuteNonQuery ();
       }
       tr.Commit ();
    }
    mSql = "PRAGMA foreign_keys=ON";
    mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    n = mSqliteCommand.ExecuteNonQuery ();
 } catch (Exception ex) {
    HandleExceptions (ex);
 }
}

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

No problem if all the arrays you are about to use in this scenario are small like in your example.

If you will use this for large blobs (e.g. storing large binary files many Mbs or even Gbs in size into a VARBINARY) then you'd probably be much better off using specific support in SQL Server for reading/writing subsections of such large blobs. Things like READTEXT and UPDATETEXT, or in current versions of SQL Server SUBSTRING.

For more information and examples see either my 2006 article in .NET Magazine ("BLOB + Stream = BlobStream", in Dutch, with complete source code), or an English translation and generalization of this on CodeProject by Peter de Jonghe. Both of these are linked from my weblog.

how to wait for first command to finish?

Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh after the last command of st_new.sh has finished.

Now there is a special command which messes this up: &

cmd &

means: "Start a new background process and execute cmd in it. After starting the background process, immediately continue with the next command in the script."

That means & doesn't wait for cmd to do it's work. My guess is that st_new.sh contains such a command. If that is the case, then you need to modify the script:

cmd &
BACK_PID=$!

This puts the process ID (PID) of the new background process in the variable BACK_PID. You can then wait for it to end:

while kill -0 $BACK_PID ; do
    echo "Process is still active..."
    sleep 1
    # You can add a timeout here if you want
done

or, if you don't want any special handling/output simply

wait $BACK_PID

Note that some programs automatically start a background process when you run them, even if you omit the &. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's & command instead to get the PID.

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

How to install a specific version of a ruby gem?

Use the -v flag:

$ gem install fog -v 1.8

Selected tab's color in Bottom Navigation View

This will work:

setItemBackgroundResource(android.R.color.holo_red_light)

How to find a value in an array of objects in JavaScript?

If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }

You can now easily access it like this: Object['sushi']['name']

Or if the object really is this simple (just 'name' in the object), you could just change it to:

Obj = { 'pizza' : 'bob', 'sushi' : 'john' }

And then access it like: Object['sushi'].

It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

Simplest way to restart service on a remote computer

  1. open service control manager database using openscmanager
  2. get dependent service using EnumDependService()
  3. Stop all dependent services using ChangeConfig() sending STOP signal to this function if they are started
  4. stop actual service
  5. Get all Services dependencies of a service
  6. Start all services dependencies using StartService() if they are stopped
  7. Start actual service

Thus your service is restarted taking care all dependencies.

How do I make a placeholder for a 'select' box?

Building upon MattW's answer, you can make the select placeholder option visible in the drop-down menu after a valid selection has been made, by conditionally hiding it only while the placeholder remains selected (and the select is therefore :invalid).

_x000D_
_x000D_
select:required:invalid {_x000D_
  color: gray;_x000D_
}_x000D_
select:invalid > option[value=""][disabled] {_x000D_
  display: none;_x000D_
}_x000D_
option {_x000D_
  color: black;_x000D_
}
_x000D_
<select required>_x000D_
    <option value="" disabled selected>Select something...</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I convert a float to an int in Objective C?

You can also use C's lroundf(myFloat).


An incredibly useful tip: In Xcode's editor, type your code as say

myInt = roundf(someFloat);

then control/right-click on roundf and Jump to definition (or simply command-click).

You will then clearly see the very long list of the functions available to you. (It's impossible to remember them all, so just use this trick.)

For example, in the example at hand it's likely that lrintf is what you want.

A further tip: to get documentation on those many functions. In your Terminal.app (or any shell - nothing to do with Xcode, just the normal Terminal.app) simply type man lrintf and it will give you full info. Hope it helps someone.

How to get to Model or Viewbag Variables in a Script Tag

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);

Override devise registrations controller

Very simple methods Just go to the terminal and the type following

rails g devise:controllers users //This will create devise controllers in controllers/users folder

Next to use custom views

rails g devise:views users //This will create devise views in views/users folder

now in your route.rb file

devise_for :users, controllers: {
           :sessions => "users/sessions",
           :registrations => "users/registrations" }

You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.

Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !

How to view an HTML file in the browser with Visual Studio Code

CTRL+SHIFT+P will bring up the command palette.
Depending on what you're running of course. Example in an ASP.net app you can type in:
>kestrel and then open up your web browser and type in localhost:(your port here).

If you type in > it will show you the show and run commands

Or in your case with HTML, I think F5 after opening the command palette should open the debugger.

Source: link

How to deal with ModalDialog using selenium webdriver?

Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.

WebElement link = // element that will showModalDialog()

// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
    "var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
  link);

// wait for there to be two windows and choose the one that is 
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
    .until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(final WebDriver driver) {
        final String[] windowHandles =
            driver.getWindowHandles().toArray(new String[0]);
        if (windowHandles.length != 2) {
            return false;
        }
        if (windowHandles[0].equals(parentWindowHandle)) {
            driver.switchTo().window(windowHandles[1]);
        } else {
            driver.switchTo().window(windowHandles[0]);
        }
        return true;
    }
});

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The main problem for causing your table unable to migrate, is that you have running query on your "AppServiceProvider.php" try to check your serviceprovider and disable code for the meantime, and run php artisan migrate

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Take a look at FileSaver.js. It provides a handy saveAs function which takes care of most browser specific quirks.

'adb' is not recognized as an internal or external command, operable program or batch file

In my case it was:

C:\Program Files (x86)\Android\android-sdk\platform-tools

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

Form/JavaScript not working on IE 11 with error DOM7011

I run into this when click on a html , it is fixed by adding type = "button" attribute.

jquery fill dropdown with json data

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().

How do you extract IP addresses from files using a regex in a linux shell?

cat ip_address.txt | grep '^[0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[,].*$\|^.*[,][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[,].*$\|^.*[,][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}$'

Lets assume the file is comma delimited and the position of ip address in the beginning ,end and somewhere in the middle

First regexp looks for the exact match of ip address in the beginning of the line. The second regexp after the or looks for ip address in the middle.we are matching it in such a way that the number that follows ,should be exactly 1 to 3 digits .falsy ips like 12345.12.34.1 can be excluded in this.

The third regexp looks for the ip address at the end of the line