Programs & Examples On #Web services enhancements

Laravel - Pass more than one variable to view

Use compact

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();
    return View::make('users', compact('ms','persons'));
}

How can I format a number into a string with leading zeros?

Here I want my no to limit in 4 digit like if it is 1 it should show as 0001,if it 11 it should show as 0011..Below are the code.

        reciptno=1;//Pass only integer.

        string formatted = string.Format("{0:0000}", reciptno);

        TxtRecNo.Text = formatted;//Output=0001..

I implemented this code to generate Money receipt no.

How to insert array of data into mysql using php

if(is_array($EMailArr)){
    foreach($EMailArr as $key => $value){

    $R_ID = (int) $value['R_ID'];
    $email = mysql_real_escape_string( $value['email'] );
    $name = mysql_real_escape_string( $value['name'] );

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
    mysql_query($sql) or exit(mysql_error()); 
    }
}

A better example solution with PDO:

 $q = $sql->prepare("INSERT INTO `email_list` 
                     SET `R_ID` = ?, `EMAIL` = ?, `NAME` = ?");

 foreach($EMailArr as $value){
   $q ->execute( array( $value['R_ID'], $value['email'], $value['name'] ));
 }

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

Nginx fails to load css files

add this to your ngnix conf file

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";

C# equivalent of C++ vector, with contiguous memory?

First of all, stay away from Arraylist or Hashtable. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.

Now, what you are looking for is the List<T> class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

Get file name from a file location in Java

Here are 2 ways(both are OS independent.)

Using Paths : Since 1.7

Path p = Paths.get(<Absolute Path of Linux/Windows system>);
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();

Using FilenameUtils in Apache Commons IO :

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

How to import multiple csv files in a single load?

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\*.csv)

will consider files tmp, tmp1, tmp2, ....

How do I convert this list of dictionaries to a csv file?

import csv

with open('file_name.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(('colum1', 'colum2', 'colum3'))
    for key, value in dictionary.items():
        writer.writerow([key, value[0], value[1]])

This would be the simplest way to write data to .csv file

_csv.Error: field larger than field limit (131072)

I just had this happen to me on a 'plain' CSV file. Some people might call it an invalid formatted file. No escape characters, no double quotes and delimiter was a semicolon.

A sample line from this file would look like this:

First cell; Second " Cell with one double quote and leading space;'Partially quoted' cell;Last cell

the single quote in the second cell would throw the parser off its rails. What worked was:

csv.reader(inputfile, delimiter=';', doublequote='False', quotechar='', quoting=csv.QUOTE_NONE)

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

How do I draw a shadow under a UIView?

You can try this .... you can play with the values. The shadowRadius dictates the amount of blur. shadowOffset dictates where the shadow goes.

Swift 2.0

let radius: CGFloat = demoView.frame.width / 2.0 //change it to .height if you need spread for height
let shadowPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 2.1 * radius, height: demoView.frame.height))
//Change 2.1 to amount of spread you need and for height replace the code for height

demoView.layer.cornerRadius = 2
demoView.layer.shadowColor = UIColor.blackColor().CGColor
demoView.layer.shadowOffset = CGSize(width: 0.5, height: 0.4)  //Here you control x and y
demoView.layer.shadowOpacity = 0.5
demoView.layer.shadowRadius = 5.0 //Here your control your blur
demoView.layer.masksToBounds =  false
demoView.layer.shadowPath = shadowPath.CGPath

Swift 3.0

let radius: CGFloat = demoView.frame.width / 2.0 //change it to .height if you need spread for height 
let shadowPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 2.1 * radius, height: demoView.frame.height)) 
//Change 2.1 to amount of spread you need and for height replace the code for height

demoView.layer.cornerRadius = 2
demoView.layer.shadowColor = UIColor.black.cgColor
demoView.layer.shadowOffset = CGSize(width: 0.5, height: 0.4)  //Here you control x and y
demoView.layer.shadowOpacity = 0.5
demoView.layer.shadowRadius = 5.0 //Here your control your blur
demoView.layer.masksToBounds =  false
demoView.layer.shadowPath = shadowPath.cgPath

Example with spread

Example with spread

To create a basic shadow

    demoView.layer.cornerRadius = 2
    demoView.layer.shadowColor = UIColor.blackColor().CGColor
    demoView.layer.shadowOffset = CGSizeMake(0.5, 4.0); //Here your control your spread
    demoView.layer.shadowOpacity = 0.5 
    demoView.layer.shadowRadius = 5.0 //Here your control your blur

Basic Shadow example in Swift 2.0

OUTPUT

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

Make an Android button change background on click through XML

I used this to change the background for my button

            button.setBackground(getResources().getDrawable(R.drawable.primary_button));

"button" is the variable holding my Button, and the image am setting in the background is primary_button

Pass a datetime from javascript to c# (Controller)

Try to use toISOString(). It returns string in ISO8601 format.

GET method

javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

POST method

javascript

$.post('/example/do', { date: date.toISOString() }, function (result) {
    console.log(result);
});

c#

[HttpPost]
public JsonResult Do(DateTime date)
{
     return Json(date.ToString());
}

How to know if .keyup() is a character key (jQuery)

Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):

You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.

The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.

$("input").keypress(function(e) {
    if (e.which !== 0) {
        alert("Character was typed. It was: " + String.fromCharCode(e.which));
    }
});

keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.


The following was the original answer, but is not correct and may not work reliably in all situations.

To match the keycode with a word character (eg., a would match. space would not)

$("input").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWordcharacter = c.match(/\w/);
}); 

Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.

Getting Index of an item in an arraylist;

for (int i = 0; i < list.length; i++) {
   if (list.get(i) .getName().equalsIgnoreCase("myName")) {
    System.out.println(i);
    break;
  }
}

Define a global variable in a JavaScript function

No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:

var trailimage;

function makeObj(address) {
  trailimage = [address, 50, 50];

Determine if variable is defined in Python

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

Loop through list with both content and index

>>> for i, s in enumerate(S):

How to ignore SSL certificate errors in Apache HttpClient 4.0

All of the other answers were either deprecated or didn't work for HttpClient 4.3.

Here is a way to allow all hostnames when building an http client.

CloseableHttpClient httpClient = HttpClients
    .custom()
    .setHostnameVerifier(new AllowAllHostnameVerifier())
    .build();

Or if you are using version 4.4 or later, the updated call looks like this:

CloseableHttpClient httpClient = HttpClients
    .custom()
    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
    .build();

Groovy write to file (newline)

It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

You can always get the correct new line character through System.getProperty("line.separator") for example.

Can we pass parameters to a view in SQL?

No, a view is static. One thing you can do (depending on the version of SQl server) is index a view.

In your example (querying only one table), an indexed view has no benefit to simply querying the table with an index on it, but if you are doing a lot of joins on tables with join conditions, an indexed view can greatly improve performance.

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

Get row-index values of Pandas DataFrame as list?

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

Python convert tuple to string

This works:

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

It will produce:

'abcdgxre'

You can also use a delimiter like a comma to produce:

'a,b,c,d,g,x,r,e'

By using:

','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

JavaScript Array splice vs slice

The difference between Slice() and Splice() javascript build-in functions is, Slice returns removed item but did not change the original array ; like,

        // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.slice(index)
        // result=4  
        // after slicing=>  array =[1,2,3,4,5]  (same as original array)

but in splice() case it affects original array; like,

         // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.splice(index)
        // result=4  
        // after splicing array =[1,2,3,5]  (splicing affects original array)

Create a custom View by inflating a layout?

A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer: I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.

Code following:

public class MyView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public MyView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        inflate(getContext(), R.layout.my_view_layout, this);
    }
}

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

Parse JSON in JavaScript?

If you like

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

you can access the JSON elements by JsonObject with (.) dot:

JsonObject.result;
JsonObject.count;

How to run iPhone emulator WITHOUT starting Xcode?

The solutions above didn't work for me in ZSH. I needed to escape the dot in the iPhoneSimulator.platform. This works for me:

alias simulator="open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app"

This could be even more resilient version:

alias simulator="open -a 'iOS Simulator'"

How to write connection string in web.config file and read from it?

After opening the web.config file in application, add sample db connection in connectionStrings section like this:

<connectionStrings>  
    <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   
</connectionStrings>  

Declaring connectionStrings in web.config file:

 <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient" />   

There is no need of username and password to access the database server. Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

using System.Configuration;

This namespace is used to get configuration section details from web.config file.

using System;  
using System.Data.SqlClient;  
using System.Configuration;  
public partial class _Default: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {  
        //Get connection string from web.config file  
        string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
        //create new sqlconnection and connection to database by using connection string from web.config file  
        SqlConnection con = new SqlConnection(strcon);  
        con.Open();  
    }  
}  

Advantages of SQL Server 2008 over SQL Server 2005?

SQL 2008 also allows you to disable lock escalation on specific tables. I have found this very useful on small frequently updated tables where locks can escalate causing concurrency issues. In SQL 2005, even with the ROWLOCK hint on delete statements locks can be escalated which can lead to deadlocks. In my testing, an application which I have developed had concurrency issues during small table manipulation due to lock escalation on SQL 2005. In SQL 2008 this problem went away.

It is still important to bear in mind the potential overhead of handling large numbers of row locks, but having the option to stop escalation when you want to is very useful.

Difference between add(), replace(), and addToBackStack()

1) fragmentTransaction.addToBackStack(str);

Description - Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.

2) fragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)

Description - Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

3) fragmentTransaction.add(int containerViewId, Fragment fragment, String tag)

Description - Add a fragment to the activity state. This fragment may optionally also have its view (if Fragment.onCreateView returns non-null) into a container view of the activity.

What does it mean to replace an already existing fragment, and adding a fragment to the activity state and adding an activity to the back stack ?

There is a stack in which all the activities in the running state are kept. Fragments belong to the activity. So you can add them to embed them in a activity.

You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. This is essentially useful when you have defined your fragment container at different layouts. You just need to replace with any other fragment in any layout.

When you navigate to the current layout, you have the id of that container to replace it with the fragment you want.

You can also go back to the previous fragment in the backStack with the popBackStack() method. For that you need to add that fragment in the stack using addToBackStack() and then commit() to reflect. This is in reverse order with the current on top.

findFragmentByTag does this search for tag added by the add/replace method or the addToBackStack method ?

If depends upon how you added the tag. It then just finds a fragment by its tag that you defined before either when inflated from XML or as supplied when added in a transaction.

References: FragmentTransaction

Cross-browser custom styling for file upload button

The best example is this one, No hiding, No jQuery, It's completely pure CSS

http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

_x000D_
_x000D_
.custom-file-input::-webkit-file-upload-button {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
    content: 'Select some files';_x000D_
    display: inline-block;_x000D_
    background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
    border: 1px solid #999;_x000D_
    border-radius: 3px;_x000D_
    padding: 5px 8px;_x000D_
    outline: none;_x000D_
    white-space: nowrap;_x000D_
    -webkit-user-select: none;_x000D_
    cursor: pointer;_x000D_
    text-shadow: 1px 1px #fff;_x000D_
    font-weight: 700;_x000D_
    font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
    border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
    background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
_x000D_
_x000D_

Can't subtract offset-naive and offset-aware datetimes

I know this is old, but just thought I would add my solution just in case someone finds it useful.

I wanted to compare the local naive datetime with an aware datetime from a timeserver. I basically created a new naive datetime object using the aware datetime object. It's a bit of a hack and doesn't look very pretty but gets the job done.

import ntplib
import datetime
from datetime import timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)    

try:
    ntpt = ntplib.NTPClient()
    response = ntpt.request('pool.ntp.org')
    date = utc_to_local(datetime.datetime.utcfromtimestamp(response.tx_time))
    sysdate = datetime.datetime.now()

...here comes the fudge...

    temp_date = datetime.datetime(int(str(date)[:4]),int(str(date)[5:7]),int(str(date)[8:10]),int(str(date)[11:13]),int(str(date)[14:16]),int(str(date)[17:19]))
    dt_delta = temp_date-sysdate
except Exception:
    print('Something went wrong :-(')

How to append contents of multiple files into one file

All of the (text-) files into one

find . | xargs cat > outfile

xargs makes the output-lines of find . the arguments of cat.

find has many options, like -name '*.txt' or -type.

you should check them out if you want to use it in your pipeline

call javascript function onchange event of dropdown list

using jQuery

 $("#ddl").change(function () {
                alert($(this).val());
            });

jsFiddle

Comparing two .jar files

How do I convert an enum to a list in C#?

Language[] result = (Language[])Enum.GetValues(typeof(Language))

getFilesDir() vs Environment.getDataDirectory()

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Environment.getDataDirectory()

Return the user data directory.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

The pageContext is an implicit object available in JSPs. The EL documentation says

The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...

Thus this expression will get the current HttpServletRequest object and get the context path for the current request and append /JSPAddress.jsp to it to create a link (that will work even if the context-path this resource is accessed at changes).

The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.


For example, if your JSP (named thisJSP.jsp) is accessed at http://myhost.com/myWebApp/thisJSP.jsp, thecontext path will be myWebApp. Thus, the link href generated will be /myWebApp/JSPAddress.jsp.

If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp without any work on your part.

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

c++ string array initialization

In C++11 you can. A note beforehand: Don't new the array, there's no need for that.

First, string[] strArray is a syntax error, that should either be string* strArray or string strArray[]. And I assume that it's just for the sake of the example that you don't pass any size parameter.

#include <string>

void foo(std::string* strArray, unsigned size){
  // do stuff...
}

template<class T>
using alias = T;

int main(){
  foo(alias<std::string[]>{"hi", "there"}, 2);
}

Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!

template<unsigned N>
void foo(int const (&arr)[N]){
  // ...
}

Note that this will only match stack arrays, like int x[5] = .... Or temporary ones, created by the use of alias above.

int main(){
  foo(alias<int[]>{1, 2, 3});
}

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

Add the loading screen in starting of the android application

Write the code:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000)  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

What is the difference between onBlur and onChange attribute in HTML?

onChange is when something within a field changes eg, you write something in a text input.

onBlur is when you take focus away from a field eg, you were writing in a text input and you have clicked off it.

So really they are almost the same thing but for onChange to behave the way onBlur does something in that input needs to change.

What is "git remote add ..." and "git push origin master"?

This is an answer to this question (Export Heroku App to a new GitHub repo) which has been marked as duplicate of this one and redirected here.

I wanted to mirror my repo from Heroku to Github personal so that it shows all commits etc also which I made in Heroku. https://docs.github.com/en/free-pro-team@latest/github/importing-your-projects-to-github/importing-a-git-repository-using-the-command-line in Github documentation was useful.

Changing image size in Markdown

When using Flask (I am using it with flat pages)... I found that enabling explicitly (was not by default for some reason) 'attr_list' in extensions within the call to markdown does the trick - and then one can use the attributes (very useful also to access CSS - class="my class" for example...).

FLATPAGES_HTML_RENDERER = prerender_jinja

and the function:

def prerender_jinja(text):
    prerendered_body = render_template_string(Markup(text))
    pygmented_body   = markdown.markdown(prerendered_body, extensions=['codehilite', 'fenced_code', 'tables', 'attr_list'])
    return pygmented_body

And then in Markdown:

![image](https://octodex.github.com/images/yaktocat.png "This is a tooltip"){: width=200px}

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

If above solutions did not work for you then you may have doing something as following ..

1) installing the app from Appstore.
2) updating it with sign APK with same package name updated version.

So basically there are two kinds if APK's.

1) you uploaded on playstore known as original APK.
2) download from playstore known as derived APK.

In this case basically you are downloading derived apk and updating it with original APK.

For let it work fine uploaded new signed released APK in the internal test mode on the Google Play Store and download the derived APK to check the update scenario.

enter image description here

Starting a shell in the Docker Alpine container

ole@T:~$ docker run -it --rm alpine /bin/ash
(inside container) / # 

Options used above:

  • /bin/ash is Ash (Almquist Shell) provided by BusyBox
  • --rm Automatically remove the container when it exits (docker run --help)
  • -i Interactive mode (Keep STDIN open even if not attached)
  • -t Allocate a pseudo-TTY

Error in model.frame.default: variable lengths differ

Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.

How to get an absolute file path in Python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Performance wise substring(0, 1) is better as found by following:

    String example = "something";
    String firstLetter  = "";

    long l=System.nanoTime();
    firstLetter = String.valueOf(example.charAt(0));
    System.out.println("String.valueOf: "+ (System.nanoTime()-l));

    l=System.nanoTime();
    firstLetter = Character.toString(example.charAt(0));
    System.out.println("Character.toString: "+ (System.nanoTime()-l));

    l=System.nanoTime();
    firstLetter = example.substring(0, 1);
    System.out.println("substring: "+ (System.nanoTime()-l));

Output:

String.valueOf: 38553
Character.toString: 30451
substring: 8660

How do I register a DLL file on Windows 7 64-bit?

Knowing the error message would be rather valuable. It is meant to provide info, even though it doesn't make any sense to you it does to us. Being forced to guess, I'd say that the DLL is a 32-bit DirectX filter. In which case this should be the proper course of action:

cd c:\windows\syswow64
move ..\system32\dllname.ax .
regsvr32.exe dllname.ax

This must be run at an elevated command prompt so that UAC cannot stop the registry access that's required. Ask more questions about this at superuser.com

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

Printing Lists as Tabular Data

When I do this, I like to have some control over the details of how the table is formatted. In particular, I want header cells to have a different format than body cells, and the table column widths to only be as wide as each one needs to be. Here's my solution:

def format_matrix(header, matrix,
                  top_format, left_format, cell_format, row_delim, col_delim):
    table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)]
    table_format = [['{:^{}}'] + len(header) * [top_format]] \
                 + len(matrix) * [[left_format] + len(header) * [cell_format]]
    col_widths = [max(
                      len(format.format(cell, 0))
                      for format, cell in zip(col_format, col))
                  for col_format, col in zip(zip(*table_format), zip(*table))]
    return row_delim.join(
               col_delim.join(
                   format.format(cell, width)
                   for format, cell, width in zip(row_format, row, col_widths))
               for row_format, row in zip(table_format, table))

print format_matrix(['Man Utd', 'Man City', 'T Hotspur', 'Really Long Column'],
                    [[1, 2, 1, -1], [0, 1, 0, 5], [2, 4, 2, 2], [0, 1, 0, 6]],
                    '{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')

Here's the output:

                   | Man Utd | Man City | T Hotspur | Really Long Column
Man Utd            |   1.000 |    2.000 |     1.000 |             -1.000
Man City           |   0.000 |    1.000 |     0.000 |              5.000
T Hotspur          |   2.000 |    4.000 |     2.000 |              2.000
Really Long Column |   0.000 |    1.000 |     0.000 |              6.000

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

Table and Index size in SQL Server

EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"

glob exclude pattern

You can use the below method:

# Get all the files
allFiles = glob.glob("*")
# Files starting with eph
ephFiles = glob.glob("eph*")
# Files which doesnt start with eph
noephFiles = []
for file in allFiles:
    if file not in ephFiles:
        noephFiles.append(file)
# noepchFiles has all the file which doesnt start with eph.

Thank you.  

Assigning variables with dynamic names in Java

You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.

Postgresql, update if row with some unique value exists, else insert

I found this post more relevant in this scenario:

WITH upsert AS (
     UPDATE spider_count SET tally=tally+1 
     WHERE date='today' AND spider='Googlebot' 
     RETURNING *
)
INSERT INTO spider_count (spider, tally) 
SELECT 'Googlebot', 1 
WHERE NOT EXISTS (SELECT * FROM upsert)

How to parse JSON to receive a Date object in JavaScript?

//
// formats a .net date into a javascript compatible date
//
function FormatJsonDate(jsonDt) 
{              
    var MIN_DATE = -62135578800000; // const

    var date = new Date(parseInt(jsonDt.substr(6, jsonDt.length-8)));                                                       
    return date.toString() == new Date(MIN_DATE).toString() ? "" : (date.getMonth() + 1) + "\\" + date.getDate() + "\\" + date.getFullYear(); 
}

How to set default font family in React Native?

For React Native version = 0.60, in your root file create a file called react-native.config.js and put the followings, then just run react-native link

module.exports = {
  assets: ["./assets/fonts"]
}

Get today date in google appScript

Google Apps Script is JavaScript, the date object is initiated with new Date() and all JavaScript methods apply, see doc here

How to add new elements to an array?

you can create a arraylist, and use Collection.addAll() to convert the string array to your arraylist

How to use pip with python 3.4 on windows?

I know this is a very old topic, but in case someone needs it

there is no pip in python 3.4, so we have to use python -m ensurepip to install pip

Merge (Concat) Multiple JSONObjects in Java

Thanks to Erel. Here is a Gson version.

/**
 * Merge "source" into "target". If fields have equal name, merge them recursively.
 * Null values in source will remove the field from the target.
 * Override target values with source values
 * Keys not supplied in source will remain unchanged in target
 * 
 * @return the merged object (target).
 */
public static JsonObject deepMerge(JsonObject source, JsonObject target) throws Exception {

    for (Map.Entry<String,JsonElement> sourceEntry : source.entrySet()) {
        String key = sourceEntry.getKey();
        JsonElement value = sourceEntry.getValue();
        if (!target.has(key)) {
            //target does not have the same key, so perhaps it should be added to target
            if (!value.isJsonNull()) //well, only add if the source value is not null
            target.add(key, value);
        } else {
            if (!value.isJsonNull()) {
                if (value.isJsonObject()) {
                    //source value is json object, start deep merge
                    deepMerge(value.getAsJsonObject(), target.get(key).getAsJsonObject());
                } else {
                    target.add(key,value);
                }
            } else {
                target.remove(key);
            }
        }
    }
    return target;
}



/**
 * simple test
 */
public static void main(String[] args) throws Exception {
    JsonParser parser = new JsonParser();
    JsonObject a = null;
    JsonObject b = null;
    a = parser.parse("{offer: {issue1: null, issue2: null}, accept: true, reject: null}").getAsJsonObject();
    b = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject();
    System.out.println(deepMerge(a,b));
    // prints:
    // {"offer":{},"accept":true}
    a = parser.parse("{offer: {issue1: value1}, accept: true, reject: null}").getAsJsonObject();
    b = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject();
    System.out.println(deepMerge(a,b));
    // prints:
    // {"offer":{"issue2":"value2","issue1":"value1"},"accept":true}

}

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

As others have said just reinstall the MVC package to your web project using nuget, but be sure to add the MVC package to any projects depending on the web project, such as unit tests. If you build each included project individually, you will see witch ones require the update.

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

Why I can't access remote Jupyter Notebook server?

Try doing below step:

Following command fixes the read/write

    sudo chmod -R a+rw /home/ubuntu/certs/mycert.pem

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

How do I extract data from JSON with PHP?

// Using json as php array 

$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';

//or use from file
//$json = file_get_contents('results.json');

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

How to add an image to the emulator gallery in android studio?

Although you can have logat on a real device too, if you need to use an emulator try transferring the images through the Android Device Monitor, accessible from the toolbar in Android Studio (it's in eclipse too, of course).

Once you select the device from ADM, you can see the folders tree and copy things inside

keytool error Keystore was tampered with, or password was incorrect

keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect

I solved my problem when I changed keystore path C:\MyWorks\mykeystore to C:\MyWorks\mykeystore.keystore.

Apache POI error loading XSSFWorkbook class

Please note that 4.0 is not sufficient since ListValuedMap, was introduced in version 4.1.

You need to use this maven repository link for version 4.1. Replicated below for convenience

 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
 <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.1</version>
</dependency>

How to replace a hash key with another key

hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}

How do I remove link underlining in my HTML email?

Another way to fool Gmail (for phone numbers): use a ~ instead of a -

404-835-9421 --> 404~835~9421

It'll save you (or less savvy users ;-) the trip down html lane.

I found another way to remove links in outlook that i tested so far. if you create a blank class for example in your css say .blank {} and then do the following to your links for example:

<a href="http://www.link.com/"><span class="blank" style="text-decoration:none !important;">Search</span></a>

this worked for me hopefully it will help someone who is still having trouble taking out the underline of links in outlook. If anyone has a workaround for gmail please could you help me tried everything in this thread nothing is working.

Thanks

Why is Event.target not Element in Typescript?

Typescript 3.2.4

For retrieving property you must cast target to appropriate data type:

e => console.log((e.target as Element).id)

How do I change Eclipse to use spaces instead of tabs?

In Eclipse go to Window » Preferences then search for Formatter.

You will see various bold links, click on each bold link and set it to use spaces instead of tabs.

In the java formatter link, you have to edit the profile and select the tab policy, spaces only in indentation tab

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.

public static Stream ToStream(this bytes[] bytes) 
{
    return new MemoryStream(bytes) 
    {
        Position = 0
    };
}

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

in the manifest file set second activity parentActivityName as first activity and remove the screenOrientation parameter to the second activity. it means your first activity is the parent and decide to an orientation of your second activity.

<activity
        android:name=".view.FirstActiviy"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme" />

<activity
        android:name=".view.SecondActivity"
        android:parentActivityName=".view.FirstActiviy"
        android:theme="@style/AppTheme.Transparent" />

SQLite error 'attempt to write a readonly database' during insert?

I used:

echo exec('whoami');

to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:

sudo chown -R :username /var/www/html/myapp

Hope this helps someone out there.

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

Oracle 'Partition By' and 'Row_Number' keyword

That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.

This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.

Hope that helps...

How can I use the apply() function for a single column?

If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:

import pandas as pd
import swifter

def fnc(m):
    return m*3+4

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})

# apply a self created function to a single column in pandas
df["y"] = df.m.swifter.apply(fnc)

This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

MySQL error - #1062 - Duplicate entry ' ' for key 2

Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday

git stash -> merge stashed change with current changes

you can easily

  1. Commit your current changes
  2. Unstash your stash and resolve conflicts
  3. Commit changes from stash
  4. Soft reset to commit you are comming from (last correct commit)

Using the "start" command with parameters passed to the started program

The spaces are DOSs/CMDs Problems so you should go to the Path via:

cd "c:\program files\Microsoft Virtual PC"

and then simply start VPC via:

start Virtual~1.exe -pc MY-PC -launch

~1 means the first exe with "Virtual" at the beginning. So if there is a "Virtual PC.exe" and a "Virtual PC1.exe" the first would be the Virtual~1.exe and the second Virtual~2.exe and so on.

Or use a VNC-Client like VirtualBox.

Can't include C++ headers like vector in Android NDK

In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines

I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html

Check if null Boolean is true results in exception

Use the Apache BooleanUtils.

(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)

Don't reinvent the wheel. Leverage what's already been built and use isTrue():

BooleanUtils.isTrue( bool );

Checks if a Boolean value is true, handling null by returning false.

If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

Unable to copy ~/.ssh/id_rsa.pub

add by user root this command : ssh user_to_acces@hostName -X

user_to_acces = user hostName = hostname machine

How to set environment variable for everyone under my linux system?

Using PAM is execellent.

# modify the display PAM
$ cat /etc/security/pam_env.conf 
# BEFORE: $ export DISPLAY=:0.0 && python /var/tmp/myproject/click.py &
# AFTER : $ python $abc/click.py &
DISPLAY  DEFAULT=${REMOTEHOST}:0.0 OVERRIDE=${DISPLAY}
abc   DEFAULT=/var/tmp/myproject

How to make sure that a certain Port is not occupied by any other process

It's (Get-NetTCPConnection -LocalPort "port no.").OwningProcess

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

Never hardcode this location. Use the environment variables %ProgramFiles% or %ProgramFiles(x86)%.

When specifying these, always quote because Microsoft may have put spaces or other special characters in them.

"%ProgramFiles%\theapp\app.exe"
"%ProgramFiles(x86)%\theapp\app.exe"

In addition, the directory might be expressed in a language you do not know. http://www.samlogic.net/articles/program-files-folder-different-languages.htm

>set|findstr /i /r ".*program.*="
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files

Use these commands to find the values on a machine. DO NOT hardcode them into a program or .bat or .cmd file script. Use the variable.

set | findstr /R "^Program"
set | findstr /R "^Common"

git - Server host key not cached

Just uninstall Git Extensions and Install again by choosing OpenSSH instead of

How do I install g++ for Fedora?

Run the command bellow in a terminal emulator:

sudo dnf install gcc-c++

Enter password and that's it...

Get the position of a div/span tag

As Alex noted you can use jQuery offset() to get the position relative to the document flow. Use position() for its x,y coordinates relative to the parent.

EDIT: Switched document.ready for window.load because load waits for all of the elements so you get their size instead of simply preparing the DOM. In my experience, load results in fewer incorrectly Javascript positioned elements.

$(window).load(function(){ 
  // Log the position with jQuery
  var position = $('#myDivInQuestion').position();
  console.log('X: ' + position.left + ", Y: " + position.top );
});

How to detect chrome and safari browser (webkit)

you can use this minified jQuery snippet to detect if your user is viewing using a mobile device. If you need to test for a specific device I’ve included a collection of JavaScript snippets below which can be used to detect various mobile handheld devices such as iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 * jQuery.browser.mobile will be true if the browser is a mobile device
 **/

    (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Example Usage:

if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!’);
}
else
{
console.log(‘You are not using a mobile device!’);
}

Detect iPad

var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
…
}

Detect iPhone

var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
…
}

Detect iPod

var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
…
}

Detect iDevice

var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());

if (isiDevice)
{
…
}

Detect Andriod

var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

if (isAndroid)
{
…
}

Detect Blackberry

var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());

if (isBlackBerry)
{
…
}

Detect WebOs

var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());

if (isWebOS)
{
…
}

Detect Windows Phone

var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());

if (isWindowsPhone)
{
…
}

SQL Query for Logins

Select * From Master..SysUsers Where IsSqlUser = 1

How to unpublish an app in Google Play Developer Console

As per new Interface follow these steps

  1. Go to Google Play Developer Console
  2. Select your app you want to un-publish
  3. From the left Navigation Release >> Setup >> Advance Settings
  4. In the App Availability Check on Unpublished Radio button enter image description here

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

Difference between getAttribute() and getParameter()

-getParameter() :

<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>

    <html>
    <body>
    <%
    String sValue = request.getParameter("testParam");
    %>
    <%= sValue %>
    </body>
    </html>

request.getParameter("testParam") will get the value from the posted form of the input box named "testParam" which is "Client param". It will then print it out, so you should see "Client Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.

-getAttribute() : request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.getAttribute always return object.

How to make a view with rounded corners?

Use shape in xml with rectangle.set the property of bottom or upper radius as want.then apply that xml as background to ur view....or...use gradients to do it from code.

How can I switch views programmatically in a view controller? (Xcode, iPhone)

#import "YourViewController.h"

To push a view including the navigation bar and/or tab bar:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
YourViewController *viewController = (YourViewcontroller *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self.navigationController pushViewController:viewController animated:YES];

To set identifier to a view controller, Open YourStoryboard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

Extract subset of key-value pairs from Python dictionary object?

A bit shorter, at least:

wanted_keys = ['l', 'm', 'n'] # The keys you want
dict((k, bigdict[k]) for k in wanted_keys if k in bigdict)

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

It was recently identified that Composer consumes high CPU + memory on packages that have a lot of historical tags. See composer/composer#7577

A workaround to this problem is using symfony/flex or https://github.com/rubenrua/symfony-clean-tags-composer-plugin

composer global require rubenrua/symfony-clean-tags-composer-plugin

Calling a user defined function in jQuery

jQuery.fn.make_me_red = function() {
    alert($(this).attr('id'));
    $(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
    //$(this).siblings(".hello").make_me_red(); 
    $(this).make_me_red(); 
    $(this).addClass("active");
});
?

Function declaration and callback in jQuery.

Is there a download function in jsFiddle?

You have to put /show a after the URL you're working on:

For example:

"http://jsfiddle.net/rkw79/PagTJ/show/"

for Field URL :

"http://jsfiddle.net/rkw79/PagTJ/"

after that save the file and go to the show folder(or the file name you have saved with) under that folder u will get a html file show_resource.HTML .that is your actual file.now open it in browser and view the source code. Best of luck--------Ujjwal Gupta

GROUP BY having MAX date

Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.

It's better to run the subquery once, in the FROM clause, to get the max date per control number.

SELECT n.* 
FROM tblpm n 
INNER JOIN (
  SELECT control_number, MAX(date_updated) AS date_updated
  FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);

How to map and remove nil values in Ruby

Ruby 2.7+

There is now!

Ruby 2.7 is introducing filter_map for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.

For example:

numbers = [1, 2, 5, 8, 10, 13]
enum.filter_map { |i| i * 2 if i.even? }
# => [4, 16, 20]

In your case, as the block evaluates to falsey, simply:

items.filter_map { |x| process_x url }

"Ruby 2.7 adds Enumerable#filter_map" is a good read on the subject, with some performance benchmarks against some of the earlier approaches to this problem:

N = 100_000
enum = 1.upto(1_000)
Benchmark.bmbm do |x|
  x.report("select + map")  { N.times { enum.select { |i| i.even? }.map{ |i| i + 1 } } }
  x.report("map + compact") { N.times { enum.map { |i| i + 1 if i.even? }.compact } }
  x.report("filter_map")    { N.times { enum.filter_map { |i| i + 1 if i.even? } } }
end

# Rehearsal -------------------------------------------------
# select + map    8.569651   0.051319   8.620970 (  8.632449)
# map + compact   7.392666   0.133964   7.526630 (  7.538013)
# filter_map      6.923772   0.022314   6.946086 (  6.956135)
# --------------------------------------- total: 23.093686sec
# 
#                     user     system      total        real
# select + map    8.550637   0.033190   8.583827 (  8.597627)
# map + compact   7.263667   0.131180   7.394847 (  7.405570)
# filter_map      6.761388   0.018223   6.779611 (  6.790559)

How to make the overflow CSS property work with hidden as value

Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden as well, e.g.:

<div style="overflow: hidden">
  <div style="overflow: hidden">some text that should not overflow<div>
</div>

Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)

JavaScript replace \n with <br />

You need the /g for global matching

replace(/\n/g, "<br />");

This works for me for \n - see this answer if you might have \r\n

NOTE: The dupe is the most complete answer for any combination of \r\n, \r or \n

_x000D_
_x000D_
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
console.log(messagetoSend);
_x000D_
<textarea id="x" rows="9">_x000D_
    Line 1_x000D_
    _x000D_
    _x000D_
    Line 2_x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
    Line 3_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

UPDATE

It seems some visitors of this question have text with the breaklines escaped as

some text\r\nover more than one line"

In that case you need to escape the slashes:

replace(/\\r\\n/g, "<br />");

NOTE: All browsers will ignore \r in a string when rendering.

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

Simplest way to download and unzip files in Node.js cross-platform?

Checkout adm-zip.

ADM-ZIP is a pure JavaScript implementation for zip data compression for NodeJS.

The library allows you to:

  • decompress zip files directly to disk or in-memory buffers
  • compress files and store them to disk in .zip format or in compressed buffers
  • update content of/add new/delete files from an existing .zip

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

Should I use "camel case" or underscores in python?

for everything related to Python's style guide: i'd recommend you read PEP8.

To answer your question:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

PostgreSQL: Why psql can't connect to server?

I had the same issue on Devuan ascii (maybe Debian, too?). The config file /etc/postgresql/9.6/main/postgresql.conf contains a directive unix_socket_directories which points to /var/run/postgresql by default. Changing it to /tmp, where most clients look by default, fixed it for me.

PHP - regex to allow letters and numbers only

You left off the / (pattern delimiter) and $ (match end string).

preg_match("/^[a-zA-Z0-9]+$/", $value)

Android and setting alpha for (image) view alpha

Use this form to ancient version of android.

ImageView myImageView;
myImageView = (ImageView) findViewById(R.id.img);

AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); 
alpha.setFillAfter(true); 
myImageView.startAnimation(alpha);

The request failed or the service did not respond in a timely fashion?

After chasing this issue for some hours, we found an log in the SQL Server Agent logs stating the following:

This installation of SQL Server Agent is disabled. The edition of SQL server that installed this service does not support SQL server agent.

We were using SQL Server Express. After some Googling it appears SQL Server Express does not support SQL Server Agent.

I didn't find a direct piece of Microsoft communications stating that SQL Express doesn't support SQL Server Agent, however this sentiment seems to be echoed across many forums.

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

DROP IF EXISTS VS DROP?

Standard SQL syntax is

DROP TABLE table_name;

IF EXISTS is not standard; different platforms might support it with different syntax, or not support it at all. In PostgreSQL, the syntax is

DROP TABLE IF EXISTS table_name;

The first one will throw an error if the table doesn't exist, or if other database objects depend on it. Most often, the other database objects will be foreign key references, but there may be others, too. (Views, for example.) The second will not throw an error if the table doesn't exist, but it will still throw an error if other database objects depend on it.

To drop a table, and all the other objects that depend on it, use one of these.

DROP TABLE table_name CASCADE;
DROP TABLE IF EXISTS table_name CASCADE;

Use CASCADE with great care.

Count the number of commits on a Git branch

How about git log --pretty=oneline | wc -l

That should count all the commits from the perspective of your current branch.

How do you round a number to two decimal places in C#?

Math.Floor(123456.646 * 100) / 100 Would return 123456.64

Swift - Integer conversion to Hours/Minutes/Seconds

Here is a more structured/flexible approach: (Swift 3)

struct StopWatch {

    var totalSeconds: Int

    var years: Int {
        return totalSeconds / 31536000
    }

    var days: Int {
        return (totalSeconds % 31536000) / 86400
    }

    var hours: Int {
        return (totalSeconds % 86400) / 3600
    }

    var minutes: Int {
        return (totalSeconds % 3600) / 60
    }

    var seconds: Int {
        return totalSeconds % 60
    }

    //simplified to what OP wanted
    var hoursMinutesAndSeconds: (hours: Int, minutes: Int, seconds: Int) {
        return (hours, minutes, seconds)
    }
}

let watch = StopWatch(totalSeconds: 27005 + 31536000 + 86400)
print(watch.years) // Prints 1
print(watch.days) // Prints 1
print(watch.hours) // Prints 7
print(watch.minutes) // Prints 30
print(watch.seconds) // Prints 5
print(watch.hoursMinutesAndSeconds) // Prints (7, 30, 5)

Having an approach like this allows the adding of convenience parsing like this:

extension StopWatch {

    var simpleTimeString: String {
        let hoursText = timeText(from: hours)
        let minutesText = timeText(from: minutes)
        let secondsText = timeText(from: seconds)
        return "\(hoursText):\(minutesText):\(secondsText)"
    }

    private func timeText(from number: Int) -> String {
        return number < 10 ? "0\(number)" : "\(number)"
    }
}
print(watch.simpleTimeString) // Prints 07:30:05

It should be noted that purely Integer based approaches don't take leap day/seconds into account. If the use case is dealing with real dates/times Date and Calendar should be used.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

You may need to install gcc after install ruby-devel

Upgrading PHP in XAMPP for Windows?

http://www.apachefriends.org/en/xampp-windows.html

In this site you can get

XAMPP Add-Ons

by using this add on you can upgrade the latest versions.

PHP error: "The zip extension and unzip command are both missing, skipping."

I had PHP7.2 on a Ubuntu 16.04 server and it solved my problem:

sudo apt-get install zip unzip php-zip

Update

Tried this for Ubuntu 18.04 and worked as well.

Why use pointers?

Here's my anwser, and I won't promse to be an expert, but I've found pointers to be great in one of my libraries I'm trying to write. In this library (It's a graphics API with OpenGL:-)) you can create a triangle with vertex objects passed into them. The draw method takes these triangle objects, and well.. draws them based on the vertex objects i created. Well, its ok.

But, what if i change a vertex coordinate? Move it or something with moveX() in the vertex class? Well, ok, now i have to update the triangle, adding more methods and performance is being wasted because i have to update the triangle every time a vertex moves. Still not a big deal, but it's not that great.

Now, what if i have a mesh with tons of vertices and tons of triangles, and the mesh is rotateing, and moveing, and such. I'll have to update every triangle that uses these vertices, and probably every triangle in the scene because i wouldn't know which ones use which vertices. That's hugely computer intensive, and if I have several meshes ontop of a landscape, oh god! I'm in trouble, because im updateing every triangle almost every frame because these vertices are changing al the time!

With pointers, you don't have to update the triangles.

If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion.

SQL Server String or binary data would be truncated

I came across this problem today, and in my search for an answer to this minimal informative error message i also found this link:

https://connect.microsoft.com/SQLServer/feedback/details/339410/please-fix-the-string-or-binary-data-would-be-truncated-message-to-give-the-column-name

So it seems microsoft has no plans to expand on error message anytime soon.

So i turned to other means.

I copied the errors to excel:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected) Msg 8152, Level 16, State 14, Line 13 String or binary data would be truncated. The statement has been terminated.

(1 row(s) affected)

counted the number of rows in excel, got to close to the records counter that caused the problem... adjusted my export code to print out the SQL close to it... then ran the 5 - 10 sql inserts around the problem sql and managed to pinpoint the problem one, see the string that was too long, increase size of that column and then big import file ran no problem.

Bit of a hack and a workaround, but when you left with very little choice you do what you can.

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Partly cherry-picking a commit with Git

Actually, the best solution for this question is to use checkout commend

git checkout <branch> <path1>,<path2> ..

For example, assume you are in master, you want to the changes from dev1 on project1/Controller/WebController1.java and project1/Service/WebService1.java, you can use this:

git checkout dev1 project1/Controller/WebController1.java project1/Service/WebService1.java

That means the master branch only updates from dev1 on those two paths.

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

for postgis is

alter table table01 drop columns col1, drop col2

What's the "Content-Length" field in HTTP header?

Consider if you have headers such as:

content-encoding: gzip
content-length: 52098
content-type: text/javascript; charset=UTF-8

The content-length is the size of the compressed message body, in "octets" (i.e. in units of 8 bits, which happen to be "bytes" for all modern computers).

The size of the actual message body can be something else, perhaps 150280 bytes.

The number of characters can be different again, perhaps 150231 characters, because some unicode characters use multiple bytes (note UTF-8 is a standard encoding).

So, different numbers depending on whether you care how much data is transmitted, or how much data is held, or how many symbols are seen. Of course, there is no guarantee that these headers will be provided..

How to Test Facebook Connect Locally

I couldn't use the other solutions... What worked for me was installing LocalTunnel.net (https://github.com/danielrmz/localtunnel-net-client), and then using the resulting url on Facebook.

Table border left and bottom

You need to use the border property as seen here: jsFiddle

HTML:

<table width="770">
    <tr>
        <td class="border-left-bottom">picture (border only to the left and bottom ) </td>
        <td>text</td>
    </tr>
    <tr>
        <td>text</td>
        <td class="border-left-bottom">picture (border only to the left and bottom) </td>
    </tr>
</table>`

CSS:

td.border-left-bottom{
    border-left: solid 1px #000;
    border-bottom: solid 1px #000;
}

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

How can I avoid ResultSet is closed exception in Java?

make sure you have closed all your statments and resultsets before running rs.next. Finaly guarantees this

public boolean flowExists( Integer idStatusPrevious, Integer idStatus, Connection connection ) {
    LogUtil.logRequestMethod();

    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = connection.prepareStatement( Constants.SCRIPT_SELECT_FIND_FLOW_STATUS_BY_STATUS );
        ps.setInt( 1, idStatusPrevious );
        ps.setInt( 2, idStatus );

        rs = ps.executeQuery();

        Long count = 0L;

        if ( rs != null ) {
            while ( rs.next() ) {
                count = rs.getLong( 1 );
                break;
            }
        }

        LogUtil.logSuccessMethod();

        return count > 0L;
    } catch ( Exception e ) {
        String errorMsg = String
            .format( Constants.ERROR_FINALIZED_METHOD, ( e.getMessage() != null ? e.getMessage() : "" ) );
        LogUtil.logError( errorMsg, e );

        throw new FatalException( errorMsg );
    } finally {
        rs.close();
        ps.close();
    }

What is the difference between a URI, a URL and a URN?

A URI identifies a resource either by location, or a name, or both. More often than not, most of us use URIs that defines a location to a resource. The fact that a URI can identify a resources by both name and location has lead to a lot of the confusion in my opinion. A URI has two specializations known as URL and URN.

A URL is a specialization of URI that defines the network location of a specific resource. Unlike a URN, the URL defines how the resource can be obtained. We use URLs every day in the form of http://stackoverflow.com, etc. But a URL doesn’t have to be an HTTP URL, it can be ftp://example.com, etc.

How to change colors of a Drawable in Android?

Int color = Color.GRAY; 
// or int color = Color.argb(123,255,0,5);
// or int color = 0xaaff000;

in XML /res/values/color.xml

<?xml version="1.0" encoding="utf-8">
<resources>
    <color name="colorRed">#ff0000</color>
</resoures> 

Java Code

int color = ContextCompat.getColor(context, R.color.colorRed);

GradientDrawable drawableBg = yourView.getBackground().mutate();
drawableBg.setColor(color);

A non well formed numeric value encountered

This helped me a lot -

$new_date = date_format(date_create($old_date), 'Y-m-d');

Here, date_create() provides you a date object for a given date & date_format() will set it in a given format.

for example,

<?php
    $date = date_create("13-02-2013");  // DateTime Object ( [date] => 2013-02-13 00:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York )
    echo date_format($date,"Y-m-d");    // 2013-02-13
?>

sql insert into table with select case values

You need commas after end finishing the case statement. And, the "as" goes after the case statement, not inside it:

Insert into TblStuff(FullName, Address, City, Zip)
    Select (Case When Middle is Null Then Fname + LName
                 Else Fname +' ' + Middle + ' '+ Lname
            End)  as FullName,
           (Case When Address2 is Null Then Address1
                 else Address1 +', ' + Address2
            End)  as  Address,
           City as City,
           Zip as Zip
    from tblImport

Sending HTML mail using a shell script

The question asked specifically on shell script and the question tag mentioning only about sendmail package. So, if someone is looking for this, here is the simple script with sendmail usage that is working for me on CentOS 8:

#!/bin/sh
TOEMAIL="[email protected]"
REPORT_FILE_HTML="$REPORT_FILE.html"
echo "Subject: EMAIL SUBJECT" >> "${REPORT_FILE_HTML}"
echo "MIME-Version: 1.0" >> "${REPORT_FILE_HTML}"
echo "Content-Type: text/html" >> "${REPORT_FILE_HTML}"
echo "<html>" >> "${REPORT_FILE_HTML}"
echo "<head>" >> "${REPORT_FILE_HTML}"
echo "<title>Best practice to include title to view online email</title>" >> "${REPORT_FILE_HTML}"
echo "</head>" >> "${REPORT_FILE_HTML}"
echo "<body>" >> "${REPORT_FILE_HTML}"
echo "<p>Hello there, you can put email html body here</p>" >> "${REPORT_FILE_HTML}"
echo "</body>" >> "${REPORT_FILE_HTML}"
echo "</html>" >> "${REPORT_FILE_HTML}"

sendmail $TOEMAIL < $REPORT_FILE_HTML

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

HTML button onclick event

on first button add the following.

onclick="window.location.href='Students.html';"

similarly do the rest 2 buttons.

<input type="button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">

Secondary axis with twinx(): how to add to legend?

I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                    axes=par2,
                                    offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

plt.draw()
plt.show()

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

Passing an array by reference in C?

Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!

struct Coordinate
{
    int x,y;
};

void resize( int **p, int size )
{
   free( *p );
   *p = (int*) malloc( size * sizeof(int) );
}

void resizeCoord( struct Coordinate **p, int size )
{
   free( *p );
   *p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}

void resizeCoordWithNew( struct Coordinate **p, int size )
{
   delete [] *p;
   *p = (struct Coordinate*) new struct Coordinate[size];
}

void SomeMethod(Coordinate Coordinates[])
{
    Coordinates[0].x++;
    Coordinates[0].y = 6;
}

void SomeOtherMethod(Coordinate Coordinates[], int size)
{
    for (int i=0; i<size; i++)
    {
        Coordinates[i].x = i;
        Coordinates[i].y = i*2;
    }
}

int main()
{
    //static array
    Coordinate tenCoordinates[10];
    tenCoordinates[0].x=0;
    SomeMethod(tenCoordinates);
    SomeMethod(&(tenCoordinates[0]));
    if(tenCoordinates[0].x - 2  == 0)
    {
        printf("test1 coord change successful\n");
    }
    else
    {
        printf("test1 coord change unsuccessful\n");
    }


   //dynamic int
   int *p = (int*) malloc( 10 * sizeof(int) );
   resize( &p, 20 );

   //dynamic struct with malloc
   int myresize = 20;
   int initSize = 10;
   struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
   resizeCoord(&pcoord, myresize); 
   SomeOtherMethod(pcoord, myresize);
   bool pass = true;
   for (int i=0; i<myresize; i++)
   {
       if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
       {        
           printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
           pass = false;
       }
   }
   if (pass)
   {
       printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
   }


   //dynamic struct with new
   myresize = 20;
   initSize = 10;
   struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
   resizeCoordWithNew(&pcoord2, myresize); 
   SomeOtherMethod(pcoord2, myresize);
   pass = true;
   for (int i=0; i<myresize; i++)
   {
       if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
       {        
           printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
           pass = false;
       }
   }
   if (pass)
   {
       printf("test3 coords for dynamic struct with new worked correctly\n");
   }


   return 0;
}

How to get bean using application context in spring boot

One API method I use when I'm not sure what the bean name is org.springframework.beans.factory.ListableBeanFactory#getBeanNamesForType(java.lang.Class<?>). I simple pass it the class type and it retrieves a list of beans for me. You can be as specific or general as you'd like to retrieve all the beans relate with that type and its subtypes, example

@Autowired
ApplicationContext ctx

...

SomeController controller = ctx.getBeanNamesForType(SomeController)

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

The 'Access-Control-Allow-Origin' header contains multiple values

The 'Access-Control-Allow-Origin' header contains multiple values

when i received this error i spent tons of hours searching solution for this but nothing works, finally i found solution to this problem which is very simple. when ''Access-Control-Allow-Origin' header added more than one time to your response this error occur, check your apache.conf or httpd.conf (Apache server), server side script, and remove unwanted entry header from these files.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

C++ code file extension? .cc vs .cpp

At the end of the day it doesn't matter because C++ compilers can deal with the files in either format. If it's a real issue within your team, flip a coin and move on to the actual work.

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

You might have pressed 0 (also used for insert, shortcut INS) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.

Post order traversal of binary tree without recursion

Simple Intuitive solution in python.

        while stack:
            node = stack.pop()
            if node:
                if isinstance(node,TreeNode):
                    stack.append(node.val)
                    stack.append(node.right)
                    stack.append(node.left)
                else:
                    post.append(node)
        return post

Converting string to Date and DateTime

to create date from any string use:
$date = DateTime::createFromFormat('d-m-y H:i', '01-01-01 01:00'); echo $date->format('Y-m-d H:i');

WampServer orange icon

Please read through the wamp installation carefully, It lists the steps for wamp not turning green clearly. Please read through steps while installing wamp server. It solves most of the bootstrap issues.

Your port 80 is actually used by : Server: Microsoft-HTTPAPI/2.0

Modify ports: It works Appache port from 8080 to 7080 Maria DB port from 3306 to 3307 Mysql DB port from 3308 to 3309

To verify that all VC ++ packages are installed and with the latest versions, you can use the tool: http://wampserver.aviatechno.net/files/tools/check_vcredist.exe Also know the difference between VC++ and VS code

Visual Studio is a suite of component-based software development tools and other technologies for building powerful, high-performance applications. On the other hand, Visual Studio Code is detailed as "Build and debug modern web and cloud applications, by Microsoft".

enter image description here

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

how can get index & count in vuejs

In case, your data is in the following structure, you get string as an index

items = {
   am:"Amharic",
   ar:"Arabic",
   az:"Azerbaijani",
   ba:"Bashkir",
   be:"Belarusian"
}

In this case, you can use extra variable to get the index in number:

<ul>
  <li v-for="(item, key, index) in items">
    {{ item }} - {{ key }} - {{ index }}
  </li>
</ul>

Source: https://alligator.io/vuejs/iterating-v-for/

restart mysql server on windows 7

These suggestions so far only work if the mysql server is installed as a windows service.

If it is not installed as a service, you can start the server by using the Windows Start button ==> Run, then browse to the /bin folder under your mysql installation path and execute mysqld. Or just open a command window in the bin folder and type: mysqld

Android layout replacing a view with another view on run time

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Output single character in C

yes, %c will print a single char:

printf("%c", 'h');

also, putchar/putc will work too. From "man putchar":

#include <stdio.h>

int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).

EDIT:

Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */

How to best display in Terminal a MySQL SELECT returning too many fields?

Try enabling vertical mode, using \G to execute the query instead of ;:

mysql> SELECT * FROM sometable \G

Your results will be listed in the vertical mode, so each column value will be printed on a separate line. The output will be narrower but obviously much longer.

Set background image on grid in WPF using C#

Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.

<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
    </Grid.Background>

    <...>
</Grid>

How to set the title of UIButton as left alignment?

There is a small error in the code of @DyingCactus. Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':

NSString *myLabelText = @"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight); 

CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];   
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentLeft;

[myButton addSubview:myLabel];
[myLabel release];

Hope this helps....

Al

If "0" then leave the cell blank

An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.

=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))

how to get all child list from Firebase android

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

to get List from this sequence you have to

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

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

Works fine for me, Hope it helps.

Sort a Custom Class List<T>

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

int object is not iterable?

for .. in statements expect you to use a type that has an iterator defined. A simple int type does not have an iterator.

What are the differences between JSON and JSONP?

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
  alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

How to get controls in WPF to fill available space?

Well, I figured it out myself, right after posting, which is the most embarassing way. :)

It seems every member of a StackPanel will simply fill its minimum requested size.

In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.

I would love to see a more elegant method of handling this, but it will do.

How to pass multiple parameters from ajax to mvc controller?

You can do it by not initializing url and writing it at hardcode like this

//var url = '@Url.Action("ActionName", "Controller");

$.post("/Controller/ActionName?para1=" + data + "&para2=" + data2, function (result) {
        $("#" + data).html(result);
        ............. Your code
    });

While your controller side code must be like this below:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

this was simple way. now we can do pass multiple data by json also like this:

var val1= $('#btn1').val();  
var val2= $('#btn2').val(); 
$.ajax({
                    type: "GET",
                    url: '@Url.Action("Actionre", "Contr")',
                    contentType: "application/json; charset=utf-8",
                    data: { 'para1': val1, 'para2': val2 },
                    dataType: "json",
                    success: function (cities) {
                        ur code.....
                    }
                });

While your controller side code will be same:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

How to remove unused C/C++ symbols with GCC and ld?

The answer is -flto. You have to pass it to both your compilation and link steps, otherwise it doesn't do anything.

It actually works very well - reduced the size of a microcontroller program I wrote to less than 50% of its previous size!

Unfortunately it did seem a bit buggy - I had instances of things not being built correctly. It may have been due to the build system I'm using (QBS; it's very new), but in any case I'd recommend you only enable it for your final build if possible, and test that build thoroughly.

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

Semi-transparent color layer over background-image?

Try this. Works for me.

.background {
    background-image: url(images/images.jpg);
    display: block;
    position: relative;
}

.background::after {
    content: "";
    background: rgba(45, 88, 35, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
}

.background > * {
    z-index: 10;
}

Rebase array keys after unsetting elements

100% working for me ! After unset elements in array you can use this for re-indexing the array

$result=array_combine(range(1, count($your_array)), array_values($your_array));

Failed Apache2 start, no error log

On XAMPP use

D:\xampp\apache\bin>httpd -t -D DUMP_VHOSTS

This will yield errors in your configuration of the virtual hosts

How do you programmatically update query params in react-router?

Within the push method of hashHistory, you can specify your query parameters. For instance,

history.push({
  pathname: '/dresses',
  search: '?color=blue'
})

or

history.push('/dresses?color=blue')

You can check out this repository for additional examples on using history

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

Iterate a list with indexes in Python

Here's another using the zip function.

>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]

Unresolved external symbol in object files

Check you are including all the source files within your solution that you are referencing.

If you are not including the source file (and thus the implementation) for the class Field in your project it won't be built and you will be unable to link during compilation.

Alternatively, perhaps you are using a static or dynamic library and have forgotten to tell the linker about the .libs?

postgresql: INSERT INTO ... (SELECT * ...)

If you want insert into specify column:

INSERT INTO table (time)
(SELECT time FROM 
    dblink('dbname=dbtest', 'SELECT time FROM tblB') AS t(time integer) 
    WHERE time > 1000
);

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

I get this error when my project .net framework version does not match the framework version of the DLL I am linking to. In my case, I was getting:

"The type or namespace name 'UserVoice' could not be found (are you missing a using directive or an assembly reference?).

UserVoice was .Net 4.0, and my project properties were set to ".Net 4.0 Client Profile". Changing to .Net 4.0 on the project cleared the error. I hope this helps someone.

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

Happened to me when my client Smartgit put a newline in my .git/HEAD file. Deleting the empty line fixed it.

Visual Studio Code cannot detect installed git

What worked for me was manually adding the path variable in my system.

I followed the instructions from Method 3 in this post:

https://appuals.com/fix-git-is-not-recognized-as-an-internal-or-external-command/

Importing a GitHub project into Eclipse

I think you need to create a branch before you can import into your local Eclipse, otherwise, there is an error leading to incapable of importing repository from Github or Bitbucket.

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>